namespace Spice86.Core.Emulator.CPU;
using Spice86.Core.Emulator.CPU.Registers;
using Spice86.Shared.Emulator.Memory;
using Spice86.Shared.Utils;
using System.Text;
///
/// Represents the state of the CPU Registers and Flags.
///
/// Visualization of the 32-bit general-purpose registers:
///
/// +-------------------+
/// | EAX |
/// +-------------------+
/// | EBX |
/// +-------------------+
/// | ECX |
/// +-------------------+
/// | EDX |
/// +-------------------+
/// | ESI |
/// +-------------------+
/// | EDI |
/// +-------------------+
/// | ESP |
/// +-------------------+
/// | EBP |
/// +-------------------+
///
///
/// Each of these registers can be accessed as a whole (32 bits), or in parts as AX/BX/CX/DX (lower 16 bits), AH/BH/CH/DH (high 8 bits of the 16-bit register), and AL/BL/CL/DL (low 8 bits of the 16-bit register).
///
public class State(CpuModel cpuModel) {
/// Whether this machine has the 386 descriptor-cache and privilege-checking MMU.
public bool SupportsProtectedMode { get; } = cpuModel == CpuModel.INTEL_80386;
private const ushort InitialFpuControlWord = 0x03FF;
private const ushort FpuInterruptMask = 0x0080;
private ushort _fpuControlWord = InitialFpuControlWord;
/// Gets or sets the control word of the limited 8087-compatible initialization state.
public ushort FpuControlWord { get => _fpuControlWord; set => _fpuControlWord = value; }
/// Resets the FPU control word to the 8087 initial value, including its interrupt mask.
public void InitializeFpu() => _fpuControlWord = InitialFpuControlWord;
/// Sets the 8087 interrupt mask, allowing startup probes to distinguish it from later FPUs.
public void DisableFpuInterrupts() => _fpuControlWord |= FpuInterruptMask;
///
/// Gets or sets the second byte (high byte) in the general purpose EAX register
///
/// The EAX register is often used as an accumulator register in arithmetic operations, or to store the result of a function.
///
///
public byte AH { get => GeneralRegisters.UInt8High[(uint)RegisterIndex.AxIndex]; set => GeneralRegisters.UInt8High[(uint)RegisterIndex.AxIndex] = value; }
///
/// Gets or sets the first byte (low byte) in the general purpose EAX register
///
/// The EAX register is often used as an accumulator register in arithmetic operations, or to store the result of a function.
///
///
public byte AL { get => GeneralRegisters.UInt8Low[(uint)RegisterIndex.AxIndex]; set => GeneralRegisters.UInt8Low[(uint)RegisterIndex.AxIndex] = value; }
///
/// Gets or sets the first word (16 bits) in the general purpose EAX register
///
/// The EAX register is often used as an accumulator register in arithmetic operations, or to store the result of a function.
///
///
public ushort AX { get => GeneralRegisters.UInt16[(uint)RegisterIndex.AxIndex]; set => GeneralRegisters.UInt16[(uint)RegisterIndex.AxIndex] = value; }
///
/// Gets or sets the full range of the general purpose EAX register
///
/// The "Extended Accumulator" register is often used as an accumulator register in arithmetic operations, or to store the result of a function.
///
///
public uint EAX { get => GeneralRegisters.UInt32[(uint)RegisterIndex.AxIndex]; set => GeneralRegisters.UInt32[(uint)RegisterIndex.AxIndex] = value; }
///
/// Gets or sets the Base Register High Byte
///
public byte BH { get => GeneralRegisters.UInt8High[(uint)RegisterIndex.BxIndex]; set => GeneralRegisters.UInt8High[(uint)RegisterIndex.BxIndex] = value; }
///
/// Gets or sets the Base Register Low Byte
///
public byte BL { get => GeneralRegisters.UInt8Low[(uint)RegisterIndex.BxIndex]; set => GeneralRegisters.UInt8Low[(uint)RegisterIndex.BxIndex] = value; }
///
/// Gets or sets the Base Register First Word
///
public ushort BX { get => GeneralRegisters.UInt16[(uint)RegisterIndex.BxIndex]; set => GeneralRegisters.UInt16[(uint)RegisterIndex.BxIndex] = value; }
///
/// Gets or sets the Extended Base general purpose register
///
public uint EBX { get => GeneralRegisters.UInt32[(uint)RegisterIndex.BxIndex]; set => GeneralRegisters.UInt32[(uint)RegisterIndex.BxIndex] = value; }
///
/// Gets or sets the Counter High Byte general purpose register
///
public byte CH { get => GeneralRegisters.UInt8High[(uint)RegisterIndex.CxIndex]; set => GeneralRegisters.UInt8High[(uint)RegisterIndex.CxIndex] = value; }
///
/// Gets or sets the Counter Low Byte general purpose register
///
public byte CL { get => GeneralRegisters.UInt8Low[(uint)RegisterIndex.CxIndex]; set => GeneralRegisters.UInt8Low[(uint)RegisterIndex.CxIndex] = value; }
///
/// Gets or sets the word value of the Counter general purpose register.
///
public ushort CX { get => GeneralRegisters.UInt16[(uint)RegisterIndex.CxIndex]; set => GeneralRegisters.UInt16[(uint)RegisterIndex.CxIndex] = value; }
///
/// Gets or sets the Extended Counter general purpose register.
///
/// This general purpose register is often used for loop and string operations, as well as for storing function arguments.
///
///
public uint ECX { get => GeneralRegisters.UInt32[(uint)RegisterIndex.CxIndex]; set => GeneralRegisters.UInt32[(uint)RegisterIndex.CxIndex] = value; }
///
/// Gets or sets the Data High Byte general purpose register.
///
public byte DH { get => GeneralRegisters.UInt8High[(uint)RegisterIndex.DxIndex]; set => GeneralRegisters.UInt8High[(uint)RegisterIndex.DxIndex] = value; }
///
/// Gets or sets the Data Low Byte general purpose register.
///
public byte DL { get => GeneralRegisters.UInt8Low[(uint)RegisterIndex.DxIndex]; set => GeneralRegisters.UInt8Low[(uint)RegisterIndex.DxIndex] = value; }
///
/// Gets or sets the word value of the Data general purpose register.
///
public ushort DX { get => GeneralRegisters.UInt16[(uint)RegisterIndex.DxIndex]; set => GeneralRegisters.UInt16[(uint)RegisterIndex.DxIndex] = value; }
///
/// Extended Data general purpose register.
///
/// This general purpose register is often used for I/O operations and for storing function arguments.
///
///
public uint EDX { get => GeneralRegisters.UInt32[(uint)RegisterIndex.DxIndex]; set => GeneralRegisters.UInt32[(uint)RegisterIndex.DxIndex] = value; }
///
/// Gets or sets the word value of the Destination Index general purpose register.
///
public ushort DI { get => GeneralRegisters.UInt16[(uint)RegisterIndex.DiIndex]; set => GeneralRegisters.UInt16[(uint)RegisterIndex.DiIndex] = value; }
///
/// Extended Destination Index general purpose register.
///
/// This general purpose register often used as a pointer to a destination operand in string operations.
///
///
public uint EDI { get => GeneralRegisters.UInt32[(uint)RegisterIndex.DiIndex]; set => GeneralRegisters.UInt32[(uint)RegisterIndex.DiIndex] = value; }
///
/// Gets or sets the word value of the Source Index general purpose register.
///
public ushort SI { get => GeneralRegisters.UInt16[(uint)RegisterIndex.SiIndex]; set => GeneralRegisters.UInt16[(uint)RegisterIndex.SiIndex] = value; }
///
/// Extended Source Index general purpose register.
///
/// This general purpose register is often used as a pointer to a source operand in string operations.
///
///
public uint ESI { get => GeneralRegisters.UInt32[(uint)RegisterIndex.SiIndex]; set => GeneralRegisters.UInt32[(uint)RegisterIndex.SiIndex] = value; }
///
/// Gets or sets the word value of the Base Pointer general purpose register.
///
public ushort BP { get => GeneralRegisters.UInt16[(uint)RegisterIndex.BpIndex]; set => GeneralRegisters.UInt16[(uint)RegisterIndex.BpIndex] = value; }
///
/// Gets or sets the value of the Extended Base Pointer general purpose register.
///
/// This general purpose register is often used as a pointer to the base of the current stack frame.
///
///
public uint EBP { get => GeneralRegisters.UInt32[(uint)RegisterIndex.BpIndex]; set => GeneralRegisters.UInt32[(uint)RegisterIndex.BpIndex] = value; }
///
/// Gets or sets the word value of the Stack Pointer general purpose register.
///
public ushort SP { get => GeneralRegisters.UInt16[(uint)RegisterIndex.SpIndex]; set => GeneralRegisters.UInt16[(uint)RegisterIndex.SpIndex] = value; }
///
/// Gets or sets the value of the Extended Stack Pointer general purpose register.
///
/// This general purpose register is often used as a pointer to the top of the current stack frame.
///
///
public uint ESP { get => GeneralRegisters.UInt32[(uint)RegisterIndex.SpIndex]; set => GeneralRegisters.UInt32[(uint)RegisterIndex.SpIndex] = value; }
///
/// Code Segment Register. CS:IP points to the current instruction being executed.
///
public ushort CS { get => SegmentRegisters.UInt16[(uint)SegmentRegisterIndex.CsIndex]; set => SetSegmentRegister(SegmentRegisterIndex.CsIndex, value); }
///
/// Gets or sets the DS Register value. (DATA SEGMENT)
///
public ushort DS { get => SegmentRegisters.UInt16[(uint)SegmentRegisterIndex.DsIndex]; set => SetSegmentRegister(SegmentRegisterIndex.DsIndex, value); }
///
/// Gets or sets the Extra segment register value. (DATA SEGMENT)
///
public ushort ES { get => SegmentRegisters.UInt16[(uint)SegmentRegisterIndex.EsIndex]; set => SetSegmentRegister(SegmentRegisterIndex.EsIndex, value); }
///
/// Gets or sets the FS segment register value. (DATA SEGMENT)
///
public ushort FS { get => SegmentRegisters.UInt16[(uint)SegmentRegisterIndex.FsIndex]; set => SetSegmentRegister(SegmentRegisterIndex.FsIndex, value); }
///
/// Gets or sets the GS segment register value. (DATA SEGMENT)
///
public ushort GS { get => SegmentRegisters.UInt16[(uint)SegmentRegisterIndex.GsIndex]; set => SetSegmentRegister(SegmentRegisterIndex.GsIndex, value); }
///
/// Gets or sets the Stack Segment Register value.
///
public ushort SS { get => SegmentRegisters.UInt16[(uint)SegmentRegisterIndex.SsIndex]; set => SetSegmentRegister(SegmentRegisterIndex.SsIndex, value); }
///
/// Writes a segment register. Outside protected mode the hidden descriptor cache is refreshed as a
/// real-mode segment load would, so emulated DOS/BIOS code writing registers directly never leaves
/// a stale base behind. In protected mode the caller owns the cache.
///
private void SetSegmentRegister(SegmentRegisterIndex index, ushort value) {
SegmentRegisters.UInt16[(uint)index] = value;
if (CpuMode != CpuMode.Protected) {
SegmentDescriptorCaches[index] = SegmentDescriptorCache.CreateRealMode(value);
}
}
///
/// Gets or sets the low 16 bits of the instruction pointer (a view over , mirroring
/// the AX/EAX relationship): the authoritative value for real mode and 16-bit-default protected-mode
/// code segments.
///
public ushort IP { get => (ushort)EIP; set => EIP = (EIP & 0xFFFF_0000) | value; }
///
/// Gets or sets the full 32-bit instruction pointer. Authoritative once a 32-bit-default code
/// segment (CS descriptor D/B bit set) is executing; real mode and 16-bit segments never set bits
/// 16-31, so alone is equivalent for them.
///
public uint EIP { get; set; }
///
/// Contains the flags of the CPU. This is the flags register.
///
public Flags Flags { get; } = new(cpuModel);
///
/// Gets or sets the value of the Overflow Flag. Set if result is too large a positive number or too small a negative number (excluding sign-bit) to fit in destination operand; cleared otherwise.
///
public bool OverflowFlag { get => Flags.GetFlag(Flags.Overflow); set => Flags.SetFlag(Flags.Overflow, value); }
///
/// Gets or sets the value of the Direction Flag. It controls the direction in which string instructions are processed.
/// If set, string operations will decrement their pointer registers after processing.
/// If unset, string operations will increment their pointer registers after processing.
/// In this context, a 'string' refers to a sequence of bytes, words, or doublewords, depending on the instruction being executed and the setting of the Operand Size attribute.
///
public bool DirectionFlag { get => Flags.GetFlag(Flags.Direction); set => Flags.SetFlag(Flags.Direction, value); }
///
/// Gets or sets the value of the Interrupt Flag. If set, an interrupt must be serviced.
/// See also: STI and CLI instructions.
///
public bool InterruptFlag { get => Flags.GetFlag(Flags.Interrupt); set => Flags.SetFlag(Flags.Interrupt, value); }
///
/// Gets or sets the value of the Trap Flag.
///
/// If set, the processor will generate a debug exception after the execution of each instruction.
/// Setting TF puts the processor into single-step mode for debugging. In
/// this mode, the CPU automatically generates an exception after each
/// instruction, allowing a program to be inspected as it executes each
/// instruction.
///
///
public bool TrapFlag { get => Flags.GetFlag(Flags.Trap); set => Flags.SetFlag(Flags.Trap, value); }
///
/// Gets or sets the sign flag. Set equal to high-order bit of result (0 is positive, 1 if negative).
///
public bool SignFlag { get => Flags.GetFlag(Flags.Sign); set => Flags.SetFlag(Flags.Sign, value); }
///
/// Gets or sets the value of the Zero Flag. Set if result is zero; cleared otherwise.
///
public bool ZeroFlag { get => Flags.GetFlag(Flags.Zero); set => Flags.SetFlag(Flags.Zero, value); }
///
/// Gets or sets the value of the Auxiliary Flag. Set if there is a carry from bit 3 to bit 4 of the result; cleared otherwise.
///
public bool AuxiliaryFlag { get => Flags.GetFlag(Flags.Auxiliary); set => Flags.SetFlag(Flags.Auxiliary, value); }
///
/// Gets or sets the value of the Parity Flag.
Set if low-order eight bits of result contain an even number of 1 bits; cleared otherwise.
///
public bool ParityFlag { get => Flags.GetFlag(Flags.Parity); set => Flags.SetFlag(Flags.Parity, value); }
///
/// Gets or sets the value of the Carry Flag.
Set on high-order bit carry or borrow; cleared otherwise
///
public bool CarryFlag { get => Flags.GetFlag(Flags.Carry); set => Flags.SetFlag(Flags.Carry, value); }
///
/// Gets the offset value of the Direction Flag for 8 bit CPU instructions.
///
public short Direction8 => (short)(DirectionFlag ? -1 : 1);
///
/// Gets the offset value of the Direction Flag for 16 bit CPU instructions.
///
public short Direction16 => (short)(DirectionFlag ? -2 : 2);
///
/// Gets the offset value of the Direction Flag for 32 bit CPU instructions.
///
public short Direction32 => (short)(DirectionFlag ? -4 : 4);
///
/// Gets or sets the value of the Zero Flag instruction prefix.
///
public bool? ContinueZeroFlagValue { get; set; }
///
/// Gets or sets the value of the Segment Override instruction prefix.
///
public uint? SegmentOverrideIndex { get; set; }
///
/// The number of CPU cycles, incremented on each new instruction.
///
public long Cycles { get; set; }
///
/// The physical address of the instruction pointer in memory
///
public uint IpPhysicalAddress => MemoryUtils.ToPhysicalAddress(CS, IP);
///
/// The segmented address representation of the instruction pointer in memory
///
public SegmentedAddress IpSegmentedAddress {
get => new(CS, IP);
set {
IP = value.Offset;
CS = value.Segment;
}
}
///
/// The physical address of the stack in memory
///
public uint StackPhysicalAddress => MemoryUtils.ToPhysicalAddress(SS, SP);
///
/// The CPU registers
///
public GeneralRegisters GeneralRegisters { get; } = new();
///
/// The CPU segment registers
/// The segment registers are registers that store segment selectors, which are used to access different parts of memory.
///
public SegmentRegisters SegmentRegisters { get; } = new();
///
/// The hidden descriptor cache (base, limit, access rights) loaded for each segment register.
///
public SegmentDescriptorCaches SegmentDescriptorCaches { get; } = new();
///
/// The 386 control registers (CR0-CR4).
///
public ControlRegisters ControlRegisters { get; } = new();
///
/// The 386 debug registers (DR0-DR7).
///
public DebugRegisters DebugRegisters { get; } = new();
///
/// The Global Descriptor Table register, loaded by LGDT and read back by SGDT.
///
public DescriptorTableRegister Gdtr { get; } = new();
///
/// The Interrupt Descriptor Table register, loaded by LIDT and read back by SIDT.
///
public DescriptorTableRegister Idtr { get; } = new();
///
/// The Local Descriptor Table register, loaded by LLDT and read back by SLDT.
///
public SystemSegmentRegister Ldtr { get; } = new();
///
/// The Task Register, loaded by LTR and read back by STR.
///
public SystemSegmentRegister Tr { get; } = new();
///
/// The addressing/execution mode the CPU is currently operating in, derived from
/// and the EFLAGS VM bit.
///
public CpuMode CpuMode {
get {
if (!ControlRegisters.ProtectionEnable) {
return CpuMode.Real;
}
return Flags.GetFlag(Flags.Virtual8086Mode) ? CpuMode.Virtual8086 : CpuMode.Protected;
}
}
///
/// The Current Privilege Level: 0 outside protected mode, the CS selector's RPL in protected mode
/// (kept in sync with CPL by every control transfer), or 3 in Virtual-8086 mode. Right after CR0.PE
/// is set, CS still holds its real-mode cache until the far jump reloads it, and CPL stays 0.
///
public byte Cpl => CpuMode switch {
CpuMode.Real => 0,
CpuMode.Virtual8086 => 3,
_ => SegmentDescriptorCaches[SegmentRegisterIndex.CsIndex].IsCode ? new SegmentSelector(CS).RequestedPrivilegeLevel : (byte)0
};
///
/// Gets or sets the I/O Privilege Level (EFLAGS bits 12-13): the minimum CPL allowed to execute
/// `IN`/`OUT`/`CLI`/`STI` (and, in V86 mode, the level always required to be 3 for those to succeed).
///
public byte IoPrivilegeLevel {
get => (byte)((Flags.FlagRegister & Flags.IoPrivilegeLevelMask) >> 12);
set => Flags.FlagRegister = (Flags.FlagRegister & ~Flags.IoPrivilegeLevelMask) | (((uint)value & 0b11) << 12);
}
///
/// Gets or sets a value indicating whether the CPU is running.
///
public bool IsRunning { get; set; } = true;
///
/// Gets or sets a value indicating whether the CPU executed HLT and waits for a hardware interrupt.
///
public bool IsHalted { get; set; }
///
/// Sets and to null.
///
public void ClearPrefixes() {
ContinueZeroFlagValue = null;
SegmentOverrideIndex = null;
}
///
/// Increments the count.
///
public void IncCycles() {
Cycles++;
}
///
/// Returns all the CPU registers dumped into a string
///
/// All the CPU registers dumped into a string
public string DumpedRegFlags {
get {
StringBuilder res = new();
res.Append(nameof(Cycles)).Append('=');
res.Append(Cycles);
res.Append(" CS:IP=").Append(ConvertUtils.ToSegmentedAddressRepresentation(CS, IP)).Append('/').Append(ConvertUtils.ToHex(MemoryUtils.ToPhysicalAddress(CS, IP)));
res.Append(" EAX=").Append(ConvertUtils.ToHex32(EAX));
res.Append(" EBX=").Append(ConvertUtils.ToHex32(EBX));
res.Append(" ECX=").Append(ConvertUtils.ToHex32(ECX));
res.Append(" EDX=").Append(ConvertUtils.ToHex32(EDX));
res.Append(" ESI=").Append(ConvertUtils.ToHex32(ESI));
res.Append(" EDI=").Append(ConvertUtils.ToHex32(EDI));
res.Append(" EBP=").Append(ConvertUtils.ToHex32(EBP));
res.Append(" ESP=").Append(ConvertUtils.ToHex32(ESP));
res.Append(" SS=").Append(ConvertUtils.ToHex16(SS));
res.Append(" DS=").Append(ConvertUtils.ToHex16(DS));
res.Append(" ES=").Append(ConvertUtils.ToHex16(ES));
res.Append(" FS=").Append(ConvertUtils.ToHex16(FS));
res.Append(" GS=").Append(ConvertUtils.ToHex16(GS));
res.Append(" flags=").Append(ConvertUtils.ToHex32(Flags.FlagRegister));
res.Append(" (");
res.Append(Flags);
res.Append(')');
res.Append(" " + nameof(InterruptShadowing) + "=").Append(InterruptShadowing);
return res.ToString();
}
}
///
/// Gets or sets a value indicating whether interrupt shadowing is enabled for the current CPU state.
///
/// Interrupt shadowing temporarily prevents external interrupts from being handled for a limited duration,
/// typically during the execution of certain critical instructions such as POP SS, MOV SS/sreg, LSS, or STI.
/// Once the shadowing period ends, external interrupts can be processed as usual.
///
/// More details in the Intel Manual Volume 3A, 6.8.3 - Masking Exceptions and Interrupts When Switching Stacks
///
///
public bool InterruptShadowing { get; set; }
///
/// Returns all the CPU registers dumped into a string
///
/// All the CPU registers dumped into a string
public override string ToString() {
return DumpedRegFlags;
}
}