namespace Spice86.Core.Emulator.ReverseEngineer; using Microsoft.Extensions.Logging; using Spice86.Core.Emulator.CPU; using Spice86.Core.Emulator.CPU.CfgCpu.Ast; using Spice86.Core.Emulator.CPU.CfgCpu.Feeder; using Spice86.Core.Emulator.CPU.CfgCpu.ParsedInstruction; using Spice86.Core.Emulator.CPU.Exceptions; using Spice86.Core.Emulator.CPU.InterruptDelivery; using Spice86.Core.Emulator.CPU.DescriptorTables; using Spice86.Core.Emulator.CPU.Registers; using Spice86.Core.Emulator.Devices.Cmos; using Spice86.Core.Emulator.Devices.DirectMemoryAccess; using Spice86.Core.Emulator.Devices.ExternalInput; using Spice86.Core.Emulator.Devices.Input.Joystick; using Spice86.Core.Emulator.Devices.Input.Keyboard; using Spice86.Core.Emulator.Devices.Sound; using Spice86.Core.Emulator.Devices.Sound.Blaster; using Spice86.Core.Emulator.Devices.Sound.Midi; using Spice86.Core.Emulator.Devices.Timer; using Spice86.Core.Emulator.Devices.Video; using Spice86.Core.Emulator.Function; using Spice86.Core.Emulator.InterruptHandlers; using Spice86.Core.Emulator.InterruptHandlers.Bios; using Spice86.Core.Emulator.InterruptHandlers.Common.Callback; using Spice86.Core.Emulator.InterruptHandlers.Common.Contracts; using Spice86.Core.Emulator.InterruptHandlers.Dos; using Spice86.Core.Emulator.InterruptHandlers.Dos.Ems; using Spice86.Core.Emulator.InterruptHandlers.Input.Keyboard; using Spice86.Core.Emulator.InterruptHandlers.Input.Mouse; using Spice86.Core.Emulator.InterruptHandlers.SystemClock; using Spice86.Core.Emulator.InterruptHandlers.Timer; using Spice86.Core.Emulator.InterruptHandlers.VGA; using Spice86.Core.Emulator.Memory; using Spice86.Core.Emulator.Memory.Indexer; using Spice86.Core.Emulator.ReverseEngineer; using Spice86.Core.Emulator.StateSerialization; using Spice86.Core.Emulator.VM; using Spice86.Core.Emulator.VM.Breakpoint; using Spice86.Shared.Emulator.Errors; using Spice86.Shared.Emulator.Memory; using Spice86.Shared.Emulator.VM.Breakpoint; using Spice86.Shared.Utils; using System.Linq; using System.Numerics; /// /// Provides a set of properties and methods to facilitate the creation of C# overrides of machine code. /// public class CSharpOverrideHelper { /// /// The two programmable interrupt controllers. /// protected readonly DualPic _dualPic; private readonly HardwareInterruptGate _interruptGate; /// /// The class that stores callback instructions definitions. /// protected readonly CallbackHandler _callbackHandler; /// /// The IBM PC timer device. /// protected readonly PitTimer _timer; /// /// The class that manages software breakpoints. /// protected readonly EmulatorBreakpointsManager EmulatorBreakpointsManager; /// /// The service used for logging. /// protected readonly ILogger _loggerService; /// /// The Spice86 configuration /// protected Configuration Configuration { get; } /// /// The emulator machine. /// public Machine Machine { get; } private readonly InterruptVectorTable _interruptVectorTable; private readonly TypedCallRunner _typedCalls; private readonly ServiceCallRunner _serviceCalls; private readonly DosChildProcessRunner _dosChildProcesses; private readonly HashSet<(SegmentedAddress, SegmentedAddress)> _warnedNestedOverrideCalls = new(); /// /// The memory bus of the IBM PC. /// public IMemory Memory { get; } /// /// Gets the 8-bit indexer of the memory bus. /// public UInt8Indexer UInt8 => Memory.UInt8; /// /// Gets the 16-bit indexer of the memory bus. /// public UInt16Indexer UInt16 => Memory.UInt16; /// /// Gets the 32-bit indexer of the memory bus. /// public UInt32Indexer UInt32 => Memory.UInt32; /// /// Gets the big-endian 16-bit indexer of the memory bus. /// public UInt16BigEndianIndexer UInt16BigEndian => Memory.UInt16BigEndian; /// /// Gets the signed 8-bit indexer of the memory bus. /// public Int8Indexer Int8 => Memory.Int8; /// /// Gets the signed 16-bit indexer of the memory bus. /// public Int16Indexer Int16 => Memory.Int16; /// /// Gets the signed 32-bit indexer of the memory bus. /// public Int32Indexer Int32 => Memory.Int32; /// /// Gets the SS-relative 8-bit indexer of the memory bus: stack accesses, so a segment-limit /// fault raises #SS like the CPU's own SS-relative access. /// public SsIndexer SsUInt8 { get; } /// /// Gets the SS-relative 16-bit indexer of the memory bus, a stack access. /// public SsIndexer SsUInt16 { get; } /// /// Gets the SS-relative 32-bit indexer of the memory bus, a stack access. /// public SsIndexer SsUInt32 { get; } /// /// Gets the SS-relative signed 8-bit indexer of the memory bus, a stack access. /// public SsIndexer SsInt8 { get; } /// /// Gets the SS-relative signed 16-bit indexer of the memory bus, a stack access. /// public SsIndexer SsInt16 { get; } /// /// Gets the SS-relative signed 32-bit indexer of the memory bus, a stack access. /// public SsIndexer SsInt32 { get; } /// /// Gets the 16-bit segmented address indexer of the memory bus. /// public SegmentedAddress16Indexer SegmentedAddress16 => Memory.SegmentedAddress16; /// /// Gets the 32-bit segmented address indexer of the memory bus. /// public SegmentedAddress32Indexer SegmentedAddress32 => Memory.SegmentedAddress32; /// /// Gets the stack of the CPU. /// public Stack Stack => Machine.Stack; /// /// Gets the state of the CPU. /// public State State => Machine.CpuState; /// /// Loads a raw selector value into a segment register and refreshes its descriptor cache. Mirrors /// /// so generated/hand-written overrides behave identically to interpreted execution. /// public void LoadSegmentRegister(uint segmentRegisterIndex, ushort selector) { SegmentAndControlRegisterOperations.LoadSegmentRegister(State, Memory, segmentRegisterIndex, selector); } /// Validates and loads the code segment for a direct far transfer. public void LoadFarCodeSegment(ushort selector) => SegmentAndControlRegisterOperations.LoadFarCodeSegment(State, Memory, selector); /// /// Validates a direct (non-gate) far JMP/CALL code-segment transfer target. Called by generated code /// before loading CS for a same-partition far jump, so the compiled override enforces the same /// DPL/RPL rules as the interpreter (). /// public void ValidateFarCodeSegmentTransfer(ushort selector) { PrivilegeChecks.ValidateFarCodeSegmentTransfer(State, Memory, selector); } /// LGDT: loads GDTR from a 6-byte memory pointer (2-byte limit, 4-byte base; 24-bit base with a 16-bit operand). public void LoadGdtr(ushort segment, uint offset, bool operandSize32) { SegmentAndControlRegisterOperations.LoadGdtr(State, Memory, segment, offset, operandSize32); } /// SGDT: stores GDTR to a 6-byte memory pointer (2-byte limit, 4-byte base). public void StoreGdtr(ushort segment, uint offset) { SegmentAndControlRegisterOperations.StoreGdtr(State, Memory, segment, offset); } /// LIDT: loads IDTR from a 6-byte memory pointer (2-byte limit, 4-byte base; 24-bit base with a 16-bit operand). public void LoadIdtr(ushort segment, uint offset, bool operandSize32) { SegmentAndControlRegisterOperations.LoadIdtr(State, Memory, segment, offset, operandSize32); } /// SIDT: stores IDTR to a 6-byte memory pointer (2-byte limit, 4-byte base). public void StoreIdtr(ushort segment, uint offset) { SegmentAndControlRegisterOperations.StoreIdtr(State, Memory, segment, offset); } /// MOV r32, CRn: reads CR0/CR2/CR3/CR4. public uint ReadControlRegister(uint crNumber) { return SegmentAndControlRegisterOperations.ReadControlRegister(State, crNumber); } /// MOV CRn, r32: writes CR0/CR2/CR3/CR4. public void WriteControlRegister(uint crNumber, uint value) { SegmentAndControlRegisterOperations.WriteControlRegister(State, crNumber, value); } /// MOV DRn, r/m32 (0F 23): writes a debug register. public void WriteDebugRegister(uint drNumber, uint value) { DebugRegisterOperations.WriteDebugRegister(State, drNumber, value); } /// SMSW: reads the low 16 bits of CR0. public ushort ReadMachineStatusWord() { return SegmentAndControlRegisterOperations.ReadMachineStatusWord(State); } /// LMSW: writes the low 4 bits of CR0 (PE, MP, EM, TS). public void LoadMachineStatusWord(ushort value) { SegmentAndControlRegisterOperations.LoadMachineStatusWord(State, value); } /// CLTS: clears CR0.TS. public void Clts() { SegmentAndControlRegisterOperations.Clts(State); } /// Throws #GP if CPL/IOPL do not permit `IN`/`OUT`/`CLI`/`STI`. public void EnsureIoPrivilege() { PrivilegeChecks.EnsureIoPrivilege(State); } /// Checks I/O privilege before returning an interrupt flag value. public bool CheckedInterruptFlag(bool value) => PrivilegeChecks.CheckedInterruptFlag(State, value); /// Returns whether the CPU is in real mode. public bool IsRealMode() { return State.CpuMode == CpuMode.Real; } /// LLDT: loads LDTR from a GDT selector. public void LoadLdtr(ushort selector) { SegmentAndControlRegisterOperations.LoadLdtr(State, Memory, selector); } /// SLDT: reads the current LDTR selector. public ushort StoreLdtr() { return SegmentAndControlRegisterOperations.StoreLdtr(State); } /// LTR: loads the Task Register from a GDT selector. public void LoadTr(ushort selector) { SegmentAndControlRegisterOperations.LoadTr(State, Memory, selector); } /// STR: reads the current Task Register selector. public ushort StoreTr() { return SegmentAndControlRegisterOperations.StoreTr(State); } /// ARPL: returns the r/m operand with its RPL raised to the register operand's RPL if lower. public ushort AdjustRequestedPrivilegeLevel(ushort rmSelector, ushort regSelector) { return SegmentAndControlRegisterOperations.AdjustRequestedPrivilegeLevel(rmSelector, regSelector); } /// ARPL: whether the r/m operand's RPL was raised (sets ZF). public bool WasPrivilegeLevelAdjusted(ushort rmSelector, ushort regSelector) { return SegmentAndControlRegisterOperations.WasPrivilegeLevelAdjusted(rmSelector, regSelector); } /// LAR: whether a selector resolves to a present descriptor (sets ZF). public bool IsSelectorValidForLar(ushort selector) { return SegmentAndControlRegisterOperations.IsSelectorValidForLar(State, Memory, selector); } /// LAR: loads the packed access-rights doubleword for a selector. public uint LoadAccessRights(ushort selector) { return SegmentAndControlRegisterOperations.LoadAccessRights(State, Memory, selector); } /// LSL: whether a selector resolves to a present segment descriptor (sets ZF). public bool IsSelectorValidForLsl(ushort selector) { return SegmentAndControlRegisterOperations.IsSelectorValidForLsl(State, Memory, selector); } /// LSL: loads the granularity-scaled limit for a selector. public uint LoadSegmentLimit(ushort selector) { return SegmentAndControlRegisterOperations.LoadSegmentLimit(State, Memory, selector); } /// VERR: whether a selector is a present, readable data or code segment. public bool VerifyReadable(ushort selector) { return SegmentAndControlRegisterOperations.VerifyReadable(State, Memory, selector); } /// VERW: whether a selector is a present, writable data segment. public bool VerifyWritable(ushort selector) { return SegmentAndControlRegisterOperations.VerifyWritable(State, Memory, selector); } /// /// Arithmetic-logic unit for 8 bit operations /// public Alu8 Alu8 { get; } /// /// Arithmetic-logic unit for 16 bit operations /// public Alu16 Alu16 { get; } /// /// Arithmetic-logic unit for 32 bit operations /// public Alu32 Alu32 { get; } /// /// Gets or sets the value of AX register. /// public ushort AX { get => State.AX; set => State.AX = value; } /// /// Gets or sets the value of AH register. /// public byte AH { get => State.AH; set => State.AH = value; } /// /// Gets or sets the value of AL register. /// public byte AL { get => State.AL; set => State.AL = value; } /// /// Gets or sets the value of BX register. /// public ushort BX { get => State.BX; set => State.BX = value; } /// /// Gets or sets the value of BH register. /// public byte BH { get => State.BH; set => State.BH = value; } /// /// Gets or sets the value of BL register. /// public byte BL { get => State.BL; set => State.BL = value; } /// /// Gets or sets the value of CX register. /// public ushort CX { get => State.CX; set => State.CX = value; } /// /// Gets or sets the value of CH register. /// public byte CH { get => State.CH; set => State.CH = value; } /// /// Gets or sets the value of CL register. /// public byte CL { get => State.CL; set => State.CL = value; } /// /// Gets or sets the value of DX register. /// public ushort DX { get => State.DX; set => State.DX = value; } /// /// Gets or sets the value of DH register. /// public byte DH { get => State.DH; set => State.DH = value; } /// /// Gets or sets the value of DL register. /// public byte DL { get => State.DL; set => State.DL = value; } /// /// Gets or sets the value of SP register. /// public ushort SP { get => State.SP; set => State.SP = value; } /// /// Gets or sets the value of BP register. /// public ushort BP { get => State.BP; set => State.BP = value; } /// /// Gets or sets the value of SI register. /// public ushort SI { get => State.SI; set => State.SI = value; } /// /// Gets or sets the value of DI register. /// public ushort DI { get => State.DI; set => State.DI = value; } /// /// Gets or sets the value of CS register. /// public ushort CS { get => State.CS; set => State.CS = value; } /// /// Gets or sets the value of DS register. /// public ushort DS { get => State.DS; set => State.DS = value; } /// /// Gets or sets the value of ES register. /// public ushort ES { get => State.ES; set => State.ES = value; } /// /// Gets or sets the value of FS register. /// public ushort FS { get => State.FS; set => State.FS = value; } /// /// Gets or sets the value of GS register. /// public ushort GS { get => State.GS; set => State.GS = value; } /// /// Gets or sets the value of SS register. /// public ushort SS { get => State.SS; set => State.SS = value; } /// /// Gets or sets the value of IP register. /// public ushort IP { get => State.IP; set => State.IP = value; } /// /// Gets or sets the value of the 32-bit EAX register. /// public uint EAX { get => State.EAX; set => State.EAX = value; } /// /// Gets or sets the value of the 32-bit EBX register. /// public uint EBX { get => State.EBX; set => State.EBX = value; } /// /// Gets or sets the value of the 32-bit ECX register. /// public uint ECX { get => State.ECX; set => State.ECX = value; } /// /// Gets or sets the value of the 32-bit EDX register. /// public uint EDX { get => State.EDX; set => State.EDX = value; } /// /// Gets or sets the value of the 32-bit ESP register. /// public uint ESP { get => State.ESP; set => State.ESP = value; } /// /// Gets or sets the value of the 32-bit EBP register. /// public uint EBP { get => State.EBP; set => State.EBP = value; } /// /// Gets or sets the value of the 32-bit ESI register. /// public uint ESI { get => State.ESI; set => State.ESI = value; } /// /// Gets or sets the value of the 32-bit EDI register. /// public uint EDI { get => State.EDI; set => State.EDI = value; } /// /// Gets or sets the value of the auxiliary flag. /// public bool AuxiliaryFlag { get => State.AuxiliaryFlag; set => State.AuxiliaryFlag = value; } /// /// Gets or sets the value of the carry flag. /// public bool CarryFlag { get => State.CarryFlag; set => State.CarryFlag = value; } /// /// Gets or sets the value of the direction flag. /// public bool DirectionFlag { get => State.DirectionFlag; set => State.DirectionFlag = value; } /// /// Gets or sets the value of the interrupt flag. /// public bool InterruptFlag { get => State.InterruptFlag; set => State.InterruptFlag = value; } /// /// Gets or sets the value of the overflow flag. /// public bool OverflowFlag { get => State.OverflowFlag; set => State.OverflowFlag = value; } /// /// Gets or sets the value of the parity flag. /// public bool ParityFlag { get => State.ParityFlag; set => State.ParityFlag = value; } /// /// Gets or sets the value of the sign flag. /// public bool SignFlag { get => State.SignFlag; set => State.SignFlag = value; } /// /// Gets or sets the value of the trap flag. /// public bool TrapFlag { get => State.TrapFlag; set => State.TrapFlag = value; } /// /// Gets or sets the value of the zero flag. /// public bool ZeroFlag { get => State.ZeroFlag; set => State.ZeroFlag = value; } /// /// Sets the six status flags at once, the flag result of one operation. /// public void SetStatusFlags(bool carry, bool parity, bool auxiliary, bool zero, bool sign, bool overflow) { CarryFlag = carry; ParityFlag = parity; AuxiliaryFlag = auxiliary; ZeroFlag = zero; SignFlag = sign; OverflowFlag = overflow; } /// /// Gets or sets the value of the flags register (32 bit value). /// public uint FlagRegister { get => State.Flags.FlagRegister; set => State.Flags.FlagRegister = value; } /// /// Gets or sets the value of the flags register (16 bit value). /// public ushort FlagRegister16 { get => State.Flags.FlagRegister16; set => State.Flags.FlagRegister = value; } /// /// Gets the offset value of the Direction Flag for 8 bit CPU instructions. /// public short Direction8 => State.Direction8; /// /// Gets the offset value of the Direction Flag for 16 bit CPU instructions. /// public short Direction16 => State.Direction16; /// /// Gets the offset value of the Direction Flag for 32 bit CPU instructions. /// public short Direction32 => State.Direction32; /// /// A dictionary that stores the function information of each function defined in memory. /// public IDictionary FunctionInformations { get; private set; } /// /// Functions registered by their protected-mode flat linear address (see ), /// kept separate from because a linear address has no /// to key the latter dictionary by, and because /// a call target's linear address must be resolved live through the current GDT/LDT (a selector's base /// can be repointed by a descriptor edit after registration) rather than cached once at registration time. /// public IDictionary LinearFunctionInformations { get; } = new Dictionary(); /// /// Gets or sets the /// public JumpDispatcher JumpDispatcher { get; set; } public ReturnOperationsHelper ReturnOperationsHelper { get; } /// /// Typed wrappers for the VGA I/O ports. /// protected VgaPorts VgaPorts { get; } /// /// Typed wrappers for the programmable interval timer I/O ports. /// protected PitPorts PitPorts { get; } /// /// Typed wrappers for the interrupt controller I/O ports. /// protected PicPorts PicPorts { get; } /// /// Typed wrappers for the DMA controller I/O ports. /// protected DmaPorts DmaPorts { get; } /// /// Typed wrappers for the keyboard controller I/O ports. /// protected KeyboardControllerPorts KeyboardControllerPorts { get; } /// /// Typed wrappers for the CMOS/RTC I/O ports. /// protected RealTimeClockPorts RealTimeClockPorts { get; } /// /// Typed wrappers for the PC speaker PPI port. /// protected PcSpeakerPorts PcSpeakerPorts { get; } /// /// Typed wrappers for the Sound Blaster I/O ports. /// protected SoundBlasterPorts SoundBlasterPorts { get; } /// /// Typed wrappers for the OPL I/O ports. /// protected Opl3Ports Opl3Ports { get; } /// /// Typed wrappers for the MIDI I/O ports. /// protected MidiPorts MidiPorts { get; } /// /// Typed wrappers for the Gravis Ultrasound I/O ports. /// protected GravisUltrasoundPorts GravisUltrasoundPorts { get; } /// /// Typed wrappers for the joystick game port. /// protected JoystickPorts JoystickPorts { get; } /// /// Typed wrappers for the floppy disk controller I/O ports. /// protected FloppyControllerPorts FloppyControllerPorts { get; } /// /// The CMOS/RTC device; its register operations are the device-level form of the port 0x70/0x71 /// sequences. The interrupt-service helper of int 70h is . /// protected RealTimeClock Cmos { get; } /// /// The programmable interval timer device; its channel programming operation is the /// device-level form of the port 0x43 / 0x40+channel sequences. /// protected PitTimer Pit { get; } /// /// The VGA I/O port device; its register and palette operations are the device-level form of the /// index/data port sequences. /// protected VgaIoPortHandler Vga => Machine.VgaIoPortHandler as VgaIoPortHandler ?? throw FailAsUntested("The installed VGA port handler has no device-operation API"); /// /// The OPL synthesizer device; its register write operation is the device-level form of the /// address/data port pairs. /// protected Opl3Fm Opl { get; } /// /// Initializes a new instance. /// /// The dictionary of functions information. Each one can define an optional C# code override of the machine code. /// The emulator machine. /// The logger service implementation. /// The emulator configuration. public CSharpOverrideHelper(IDictionary functionInformations, Machine machine, ILogger loggerService, Configuration configuration) { Machine = machine; Memory = machine.Memory; _dualPic = machine.DualPic; _interruptGate = machine.CfgCpu.InterruptGate; _timer = machine.Timer; _callbackHandler = machine.CallbackHandler; EmulatorBreakpointsManager = machine.EmulatorBreakpointsManager; _loggerService = loggerService; Configuration = configuration; FunctionInformations = functionInformations; Machine = machine; _interruptVectorTable = machine.InterruptVectorTable; JumpDispatcher = new(); SsUInt8 = new(Memory.UInt8, machine.CpuState.SegmentRegisters); SsUInt16 = new(Memory.UInt16, machine.CpuState.SegmentRegisters); SsUInt32 = new(Memory.UInt32, machine.CpuState.SegmentRegisters); SsInt8 = new(Memory.Int8, machine.CpuState.SegmentRegisters); SsInt16 = new(Memory.Int16, machine.CpuState.SegmentRegisters); SsInt32 = new(Memory.Int32, machine.CpuState.SegmentRegisters); Alu8 = new(machine.CpuState); Alu16 = new(machine.CpuState); Alu32 = new(machine.CpuState); ReturnOperationsHelper = new(State, Stack); _typedCalls = new(State, Stack, FailAsUntested); _serviceCalls = new(State, Stack, FailAsUntested); _dosChildProcesses = new(State, Stack, Memory, () => Dos.ReadPspAddress(), _interruptVectorTable, FailAsUntested, SearchFunctionOverride); VgaPorts = new(machine.IoPortDispatcher); PitPorts = new(machine.IoPortDispatcher); PicPorts = new(machine.IoPortDispatcher); DmaPorts = new(machine.IoPortDispatcher); KeyboardControllerPorts = new(machine.IoPortDispatcher); RealTimeClockPorts = new(machine.IoPortDispatcher); PcSpeakerPorts = new(machine.IoPortDispatcher); SoundBlasterPorts = new(machine.IoPortDispatcher); Opl3Ports = new(machine.IoPortDispatcher); MidiPorts = new(machine.IoPortDispatcher); GravisUltrasoundPorts = new(machine.IoPortDispatcher); JoystickPorts = new(machine.IoPortDispatcher); FloppyControllerPorts = new(machine.IoPortDispatcher); Cmos = machine.RealTimeClock; Pit = machine.Timer; Opl = machine.OPL; } /// The installed INT 10h video handler. public VgaBios Video => GetInterruptHandler(); /// The installed INT 11h equipment list handler. public BiosEquipmentDeterminationInt11Handler Equipment => GetInterruptHandler(); /// The installed INT 12h conventional memory size handler. public SystemBiosInt12Handler MemorySize => GetInterruptHandler(); /// The installed INT 13h disk handler. public SystemBiosInt13Handler Disk => GetInterruptHandler(); /// The installed INT 14h serial port handler. public SystemBiosInt14Handler Serial => GetInterruptHandler(); /// The installed INT 15h system BIOS handler. public SystemBiosInt15Handler SystemBios => GetInterruptHandler(); /// The installed INT 16h keyboard handler. public KeyboardInt16Handler Keyboard => GetInterruptHandler(); /// The installed INT 17h printer handler. public SystemBiosInt17Handler Printer => GetInterruptHandler(); /// The installed INT 1Ah clock handler. public SystemClockInt1AHandler Clock => GetInterruptHandler(); /// The installed INT 1Ch user timer tick handler. public DummyInt1CHandler UserTimer => GetInterruptHandler(); /// The installed INT 21h DOS handler. public DosInt21Handler Dos => GetInterruptHandler(); /// DOS INT 20h handler (legacy program terminate). public DosInt20Handler DosInt20 => GetInterruptHandler(); /// DOS INT 22h handler (terminate address, invoked directly). public DosInt22Handler DosInt22 => GetInterruptHandler(); /// DOS INT 23h handler (Ctrl-Break terminate). public DosInt23Handler DosInt23 => GetInterruptHandler(); /// The installed INT 24h critical error handler. public DosInt24Handler CriticalError => GetInterruptHandler(); /// The installed INT 27h terminate-and-stay-resident handler. public DosInt27Handler DosInt27 => GetInterruptHandler(); /// The installed INT 28h DOS idle handler. public DosInt28Handler DosIdle => GetInterruptHandler(); /// The installed INT 2Ah DOS network handler. public DosInt2aHandler DosNetwork => GetInterruptHandler(); /// The installed INT 2Fh DOS multiplex handler. public DosInt2fHandler DosMultiplex => GetInterruptHandler(); /// The installed INT 33h mouse handler. public MouseInt33Handler Mouse => GetInterruptHandler(); /// The installed INT 67h expanded memory handler. public ExpandedMemoryManager Ems => GetInterruptHandler(); /// The installed INT 70h real-time clock handler. public RtcInt70Handler Rtc => GetInterruptHandler(); /// /// Registers a function at the specified segmented address.
///
/// The segment part of the segmented address. /// The offset part of the segmented address. /// The name of the function. /// /// Example of a valid function name: 'IncDialogueCount47A8_0x1ED_0xA1E8_0xC0B8' /// public void DefineFunction(ushort segment, ushort offset, string name) { SegmentedAddress address = new(segment, offset); GetFunctionAtAddress(true, address); FunctionInformation functionInformation = new(address, name, null); FunctionInformations.Add(address, functionInformation); } /// /// Registers a function at the specified segmented address.
///
/// The segment part of the segmented address. /// The offset part of the segmented address. /// The function to register. /// Whether to fail if a function is already defined at the specified address. Default is true. /// The name of the function. If null, the name of the provided function will be parsed using the GhidraSymbolsDumper utility. /// Thrown when is null and the name of the provided function cannot be parsed. /// /// Example of a valid function name: 'IncDialogueCount47A8_0x1ED_0xA1E8_0xC0B8' /// public void DefineFunction(ushort segment, ushort offset, Func overrideFunc, bool failOnExisting = true, string? name = null) { RegisterOverride(segment, offset, overrideFunc, failOnExisting, false, name); } /// /// Registers generated code at the specified segmented address. Generated code owns the complete /// control flow of its partitions, so the registration makes every control transfer of the override /// land on another override or on the call's expected return address instead of falling back to the /// interpreter. Fails when a function is already registered at that address. /// /// The segment part of the segmented address. /// The offset part of the segmented address. /// The function to register. /// The name of the function. /// A function is already registered at that address. public void DefineFunctionWithoutInterpreterFallback(ushort segment, ushort offset, Func overrideFunc, string name) { RegisterOverride(segment, offset, overrideFunc, true, true, name); } /// /// Registers an override at the specified segmented address, unless an entry already exists there and /// says that must fail. The name is , or is /// parsed from the delegate's method name when it is null. /// /// The segment part of the segmented address. /// The offset part of the segmented address. /// The function to register. /// Whether to fail when a function already exists at the specified address. /// Whether the override owns the complete control flow of its code. /// The name of the function, or null to parse it from the delegate's method name. /// A function already exists at the address and /// is set, or the name cannot be parsed. private void RegisterOverride(ushort segment, ushort offset, Func overrideFunc, bool failOnExisting, bool forbidsInterpreterFallback, string? name) { SegmentedAddress address = new(segment, offset); FunctionInformation? existing = GetFunctionAtAddress(failOnExisting, address); if (existing?.HasOverride is true) { // Do not overwrite existing code with override return; } string functionName; if (name != null) { functionName = name; } else { string methodName = overrideFunc.Method.Name; FunctionInformation? parsedFunctionInformation = GhidraSymbolsExporter.NameToFunctionInformation(_loggerService, methodName); if (parsedFunctionInformation == null) { throw new UnrecoverableException("Cannot parse " + methodName + " into a spice86 function name as format is not correct."); } functionName = parsedFunctionInformation.Name; } FunctionInformations[address] = new FunctionInformation(address, functionName, overrideFunc) { ForbidsInterpreterFallback = forbidsInterpreterFallback }; } /// /// Registers a function at a protected-mode flat linear address rather than a segment:offset pair, so /// the override keeps firing even if a later descriptor edit repoints the selector that currently maps /// to that address (see ). The /// stored is a synthetic placeholder (segment 0, offset truncated from the linear address) for display /// purposes only - lookup is always keyed by the raw linear address, never by that placeholder. /// /// The flat linear address the function starts at. /// The function to register. /// Whether to fail if a function is already defined at the specified address. Default is true. /// The name of the function. If null, the name of the provided function will be parsed using the GhidraSymbolsDumper utility. /// Thrown when is null and the name of the provided function cannot be parsed. public void DefineFunction(uint linearAddress, Func overrideFunc, bool failOnExisting = true, string? name = null) { if (failOnExisting && LinearFunctionInformations.TryGetValue(linearAddress, out FunctionInformation? existing)) { throw new UnrecoverableException( $"There is already a function overriden at linear address 0x{linearAddress:X8} named {existing.Name}. Please check your mappings for duplicates."); } string functionName; if (name != null) { functionName = name; } else { string methodName = overrideFunc.Method.Name; FunctionInformation? parsedFunctionInformation = GhidraSymbolsExporter.NameToFunctionInformation(_loggerService, methodName); if (parsedFunctionInformation == null) { throw new UnrecoverableException("Cannot parse " + methodName + " into a spice86 function name as format is not correct."); } functionName = parsedFunctionInformation.Name; } SegmentedAddress placeholderAddress = new(0, unchecked((ushort)linearAddress)); LinearFunctionInformations[linearAddress] = new FunctionInformation(placeholderAddress, functionName, overrideFunc); } /// /// Gets the function information for the function at the specified address. /// /// A flag indicating whether to throw an exception if a function already exists at the specified address. /// The address of the function to retrieve. /// The function information for the function at the specified address, or null if no function exists at that address. /// Thrown if a function already exists at the specified address and failOnExisting is true. public FunctionInformation? GetFunctionAtAddress(bool failOnExisting, SegmentedAddress address) { if (FunctionInformations.TryGetValue(address, out FunctionInformation? existingFunctionInformation)) { if (!failOnExisting) { return existingFunctionInformation; } string error = $"There is already a function overriden at address {address} named {existingFunctionInformation.Name}. Please check your mappings for duplicates."; if (_loggerService.IsEnabled(LogLevel.Error)) { _loggerService.LogError( "There is already a function defined at address {Address} named {ExistingFunctionInformationName} but you are trying to redefine it. Please check your mappings for duplicates", address, existingFunctionInformation.Name); } throw new UnrecoverableException(error); } return null; } /// /// Returns an that sets CS and IP to the provided values. /// /// The value for the CS register. /// The value for the IP register. /// The that will mutate CS and IP when invoked. public Action FarJump(ushort cs, ushort ip) { return () => { if (ProtectedModeCallGateDispatcher.TryReadCallGate(State, Memory, cs, out RawGateDescriptor gate)) { ProtectedModeCallGateDispatcher.DispatchJump(State, Memory, gate, cs); return; } PrivilegeChecks.ValidateFarCodeSegmentTransfer(State, Memory, cs); LoadSegmentRegister((uint)SegmentRegisterIndex.CsIndex, cs); State.IP = ip; }; } /// /// Returns an that performs a far return instruction when invoked. /// /// returns an that performs a far return instruction when invoked. public Action FarRet(ushort numberOfBytesToPop = 0) { return () => { if (State.CpuMode == CpuMode.Protected) { ProtectedModeInterruptDispatcher.FarReturn16(State, Memory, Stack, numberOfBytesToPop); } else { ReturnOperationsHelper.FarRet16(numberOfBytesToPop); LoadSegmentRegister((uint)SegmentRegisterIndex.CsIndex, State.CS); } }; } public Action FarRet32(ushort numberOfBytesToPop = 0) { return () => { if (State.CpuMode == CpuMode.Protected) { ProtectedModeInterruptDispatcher.FarReturn32(State, Memory, Stack, numberOfBytesToPop); return; } ReturnOperationsHelper.FarRet32(numberOfBytesToPop); LoadSegmentRegister((uint)SegmentRegisterIndex.CsIndex, State.CS); }; } /// /// Returns an that performs an IRET instruction when invoked. /// /// returns an that performs an interrupt return when invoked. public Action InterruptRet(ushort? instructionOffset = null) { return () => { if (State.CpuMode == CpuMode.Protected) { if (instructionOffset is ushort offset && State.Flags.GetFlag(Flags.NestedTask)) { State.IP = offset; } ProtectedModeInterruptDispatcher.InterruptReturn16(State, Memory, Stack); } else { ReturnOperationsHelper.InterruptRet(); } }; } /// /// Returns an that performs a 32-bit IRETD instruction when invoked. /// /// returns an that performs a 32-bit interrupt return when invoked. public Action InterruptRet32(ushort? instructionOffset = null) { return () => { if (State.CpuMode == CpuMode.Protected) { if (instructionOffset is ushort offset && State.Flags.GetFlag(Flags.NestedTask)) { State.IP = offset; } ProtectedModeInterruptDispatcher.InterruptReturn32(State, Memory, Stack); } else { ReturnOperationsHelper.InterruptRet32(); } }; } /// /// Returns an that will modify the IP register to the provided value. /// /// The target value for the IP register. /// The action that will modify the IP register when invoked. public Action NearJump(ushort ip) { return () => State.IP = ip; } /// /// Returns an action that performs a near return. /// /// The number of bytes to remove from the stack. /// An action that performs a near return. public Action NearRet(ushort numberOfBytesToPop = 0) { return () => ReturnOperationsHelper.NearRet16(numberOfBytesToPop); } public Action NearRet32(ushort numberOfBytesToPop = 0) { return () => ReturnOperationsHelper.NearRet32(numberOfBytesToPop); } /// /// Performs a near call. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The function to call. public void NearCall(ushort expectedReturnCs, ushort expectedReturnIp, Func function) { NearCallReturnedElsewhere(expectedReturnCs, expectedReturnIp, function, NoRedirectedReturns); } /// /// Performs a near call and tells whether it returned to one of the addresses the call was observed /// to be redirected to instead of :. /// The return address pushed on the stack is still the expected one; a callee that rewrites it and /// lands on a listed address ends the call there without running the override registered there. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The function to call. /// Addresses the call was observed to return to besides the expected one. /// true when the call ended at a redirected return address, false when it /// ended at the expected return address. public bool NearCallReturnedElsewhere(ushort expectedReturnCs, ushort expectedReturnIp, Func function, SegmentedAddress[] redirectedReturns) { return ExecuteCallEnsuringSameStack(expectedReturnCs, expectedReturnIp, expectedReturnCs, function, () => { Stack.PushReturnAddress(CallDistance.Near, BitWidth.WORD_16, new SegmentedAddress(expectedReturnCs, expectedReturnIp)); Action returnAction = function.Invoke(0); returnAction.Invoke(); }, redirectedReturns, State.StackPhysicalAddress, false); } /// /// Performs a near call with a 32-bit operand size, pushing a 32-bit return EIP onto the stack /// (matching Stack.Push32 used by the interpreter for 32-bit near calls). /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The function to call. public void NearCall32(ushort expectedReturnCs, ushort expectedReturnIp, Func function) { NearCall32ReturnedElsewhere(expectedReturnCs, expectedReturnIp, function, NoRedirectedReturns); } /// /// Performs a near call with a 32-bit operand size and tells whether it returned to one of the /// redirected return addresses in instead of the expected one. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The function to call. /// Addresses the call was observed to return to besides the expected one. /// true when the call ended at a redirected return address, false when it /// ended at the expected return address. public bool NearCall32ReturnedElsewhere(ushort expectedReturnCs, ushort expectedReturnIp, Func function, SegmentedAddress[] redirectedReturns) { return ExecuteCallEnsuringSameStack(expectedReturnCs, expectedReturnIp, expectedReturnCs, function, () => { Stack.PushReturnAddress(CallDistance.Near, BitWidth.DWORD_32, new SegmentedAddress(expectedReturnCs, expectedReturnIp)); Action returnAction = function.Invoke(0); returnAction.Invoke(); }, redirectedReturns, State.StackPhysicalAddress, false); } /// /// Performs a far call. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The CS value of the callee, executed in for the duration of the call. /// The function to call. public void FarCall(ushort expectedReturnCs, ushort expectedReturnIp, ushort targetCs, Func function) { FarCallReturnedElsewhere(expectedReturnCs, expectedReturnIp, targetCs, function, NoRedirectedReturns); } /// /// Performs a far call and tells whether it returned to one of the redirected return addresses in /// instead of the expected one. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The CS value of the callee, executed in for the duration of the call. /// The function to call. /// Addresses the call was observed to return to besides the expected one. /// true when the call ended at a redirected return address, false when it /// ended at the expected return address. public bool FarCallReturnedElsewhere(ushort expectedReturnCs, ushort expectedReturnIp, ushort targetCs, Func function, SegmentedAddress[] redirectedReturns) { uint expectedStackAddress = State.StackPhysicalAddress; SegmentedAddress expectedReturn = new(expectedReturnCs, expectedReturnIp); if (TaskSwitchOperations.TryReadAvailableTss(State, Memory, targetCs)) { SegmentedAddress taskTarget = TaskSwitchOperations.SwitchToNewTask(State, Memory, targetCs, expectedReturnIp); Func? taskFunction = SearchFunctionOverride(taskTarget); if (taskFunction is null) { throw FailAsUntested($"Could not find an override at address {taskTarget}"); } return ExecuteCallEnsuringSameStack(expectedReturnCs, expectedReturnIp, taskTarget.Segment, taskFunction, () => { Action taskReturnAction = taskFunction.Invoke(0); taskReturnAction.Invoke(); }, redirectedReturns, expectedStackAddress, false); } if (ProtectedModeCallGateDispatcher.TryReadCallGate(State, Memory, targetCs, out RawGateDescriptor gate)) { SegmentedAddress gateTarget = ProtectedModeCallGateDispatcher.Dispatch(State, Memory, Stack, gate, targetCs, expectedReturn); Func? gateFunction = SearchFunctionOverride(gateTarget); if (gateFunction is null) { throw FailAsUntested($"Could not find an override at address {gateTarget}"); } return ExecuteCallEnsuringSameStack(expectedReturnCs, expectedReturnIp, gateTarget.Segment, gateFunction, () => { Action gateReturnAction = gateFunction.Invoke(0); gateReturnAction.Invoke(); }, redirectedReturns, expectedStackAddress, false); } PrivilegeChecks.ValidateFarCodeSegmentTransfer(State, Memory, targetCs); return ExecuteCallEnsuringSameStack(expectedReturnCs, expectedReturnIp, targetCs, function, () => { Stack.PushReturnAddress(CallDistance.Far, BitWidth.WORD_16, new SegmentedAddress(expectedReturnCs, expectedReturnIp)); Action returnAction = function.Invoke(0); returnAction.Invoke(); }, redirectedReturns, State.StackPhysicalAddress, false); } /// /// Performs a far call with a 32-bit operand size, pushing the return address as a 32-bit far pointer /// (4-byte EIP + 2-byte CS + 2-byte padding) via , matching the /// interpreter's 32-bit far-call stack layout so reads back the right values. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The CS value of the callee, executed in for the duration of the call. /// The function to call. public void FarCall32(ushort expectedReturnCs, ushort expectedReturnIp, ushort targetCs, Func function) { FarCall32ReturnedElsewhere(expectedReturnCs, expectedReturnIp, targetCs, function, NoRedirectedReturns); } /// /// Performs a far call with a 32-bit operand size and tells whether it returned to one of the /// redirected return addresses in instead of the expected one. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The CS value of the callee, executed in for the duration of the call. /// The function to call. /// Addresses the call was observed to return to besides the expected one. /// true when the call ended at a redirected return address, false when it /// ended at the expected return address. public bool FarCall32ReturnedElsewhere(ushort expectedReturnCs, ushort expectedReturnIp, ushort targetCs, Func function, SegmentedAddress[] redirectedReturns) { uint expectedStackAddress = State.StackPhysicalAddress; SegmentedAddress expectedReturn = new(expectedReturnCs, expectedReturnIp); if (TaskSwitchOperations.TryReadAvailableTss(State, Memory, targetCs)) { SegmentedAddress taskTarget = TaskSwitchOperations.SwitchToNewTask(State, Memory, targetCs, expectedReturnIp); Func? taskFunction = SearchFunctionOverride(taskTarget); if (taskFunction is null) { throw FailAsUntested($"Could not find an override at address {taskTarget}"); } return ExecuteCallEnsuringSameStack(expectedReturnCs, expectedReturnIp, taskTarget.Segment, taskFunction, () => { Action taskReturnAction = taskFunction.Invoke(0); taskReturnAction.Invoke(); }, redirectedReturns, expectedStackAddress, false); } if (ProtectedModeCallGateDispatcher.TryReadCallGate(State, Memory, targetCs, out RawGateDescriptor gate)) { SegmentedAddress gateTarget = ProtectedModeCallGateDispatcher.Dispatch(State, Memory, Stack, gate, targetCs, expectedReturn); Func? gateFunction = SearchFunctionOverride(gateTarget); if (gateFunction is null) { throw FailAsUntested($"Could not find an override at address {gateTarget}"); } return ExecuteCallEnsuringSameStack(expectedReturnCs, expectedReturnIp, gateTarget.Segment, gateFunction, () => { Action gateReturnAction = gateFunction.Invoke(0); gateReturnAction.Invoke(); }, redirectedReturns, expectedStackAddress, false); } PrivilegeChecks.ValidateFarCodeSegmentTransfer(State, Memory, targetCs); return ExecuteCallEnsuringSameStack(expectedReturnCs, expectedReturnIp, targetCs, function, () => { Stack.PushReturnAddress(CallDistance.Far, BitWidth.DWORD_32, new SegmentedAddress(expectedReturnCs, expectedReturnIp)); Action returnAction = function.Invoke(0); returnAction.Invoke(); }, redirectedReturns, State.StackPhysicalAddress, false); } /// /// Performs a typed near call: pushes on the stack exactly like /// , runs the typed callee and then requires /// CS:IP to be the expected return address. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The typed callee. It ends with or /// , which pops the pushed return address, then returns its value. /// The return type of the typed callee. /// The value the typed callee returned. /// /// No dispatcher identity is taken and no override chain runs: typed calls are only emitted for callees /// without a cyclic jump that always return to their caller, and every call helper inside a typed callee /// opens its own dispatcher scope. A is not caught: a typed /// callee that returns to a different address than pushed unwinds to the outer call expecting it. /// Typed callees are eligible only when their return exits provably leave SP at its entry delta /// and never write their own return frame, so the unwind is a safety net for the cases that /// defeat those static checks at run time (for example an aliasing write through another /// segment), not the normal path. /// /// The typed callee did not return to the expected return address. public T NearCall(ushort expectedReturnCs, ushort expectedReturnIp, Func typedCall) { return _typedCalls.ExecuteTypedCall(expectedReturnCs, expectedReturnIp, expectedReturnCs, CallDistance.Near, BitWidth.WORD_16, typedCall); } /// /// Performs a typed near call of a callee that returns no value: same stack contract as /// . /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The typed callee, ending with or . /// The typed callee did not return to the expected return address. public void NearCall(ushort expectedReturnCs, ushort expectedReturnIp, Action typedCall) { _typedCalls.ExecuteTypedCall(expectedReturnCs, expectedReturnIp, expectedReturnCs, CallDistance.Near, BitWidth.WORD_16, typedCall); } /// /// Performs a typed far call: pushes then /// on the stack exactly like /// , sets CS to /// , runs the typed callee and then requires CS:IP to be the expected return /// address. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The CS value of the callee, executed in for the duration of the call. /// The typed callee, ending with or . /// The return type of the typed callee. /// The value the typed callee returned. /// The typed callee did not return to the expected return address. public T FarCall(ushort expectedReturnCs, ushort expectedReturnIp, ushort targetCs, Func typedCall) { return _typedCalls.ExecuteTypedCall(expectedReturnCs, expectedReturnIp, targetCs, CallDistance.Far, BitWidth.WORD_16, typedCall); } /// /// Performs a typed far call of a callee that returns no value: same stack contract as /// . /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The CS value of the callee, executed in for the duration of the call. /// The typed callee, ending with or . /// The typed callee did not return to the expected return address. public void FarCall(ushort expectedReturnCs, ushort expectedReturnIp, ushort targetCs, Action typedCall) { _typedCalls.ExecuteTypedCall(expectedReturnCs, expectedReturnIp, targetCs, CallDistance.Far, BitWidth.WORD_16, typedCall); } /// /// Performs a typed near call with a 32-bit operand size: pushes a 32-bit return EIP exactly like /// , runs the typed callee and then /// requires CS:IP to be the expected return address. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The typed callee, ending with or /// . /// The return type of the typed callee. /// The value the typed callee returned. /// The typed callee did not return to the expected return address. public T NearCall32(ushort expectedReturnCs, ushort expectedReturnIp, Func typedCall) { return _typedCalls.ExecuteTypedCall(expectedReturnCs, expectedReturnIp, expectedReturnCs, CallDistance.Near, BitWidth.DWORD_32, typedCall); } /// /// Performs a typed near call of a callee that returns no value: same stack contract as /// . /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The typed callee, ending with or /// . /// The typed callee did not return to the expected return address. public void NearCall32(ushort expectedReturnCs, ushort expectedReturnIp, Action typedCall) { _typedCalls.ExecuteTypedCall(expectedReturnCs, expectedReturnIp, expectedReturnCs, CallDistance.Near, BitWidth.DWORD_32, typedCall); } /// /// Performs a typed far call with a 32-bit operand size: pushes the return address as a 32-bit /// far pointer exactly like , /// sets CS to , runs the typed callee and then requires CS:IP to be /// the expected return address. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The CS value of the callee, executed in for the duration of the call. /// The typed callee, ending with or /// . /// The return type of the typed callee. /// The value the typed callee returned. /// The typed callee did not return to the expected return address. public T FarCall32(ushort expectedReturnCs, ushort expectedReturnIp, ushort targetCs, Func typedCall) { return _typedCalls.ExecuteTypedCall(expectedReturnCs, expectedReturnIp, targetCs, CallDistance.Far, BitWidth.DWORD_32, typedCall); } /// /// Performs a typed far call of a callee that returns no value: same stack contract as /// . /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The CS value of the callee, executed in for the duration of the call. /// The typed callee, ending with or /// . /// The typed callee did not return to the expected return address. public void FarCall32(ushort expectedReturnCs, ushort expectedReturnIp, ushort targetCs, Action typedCall) { _typedCalls.ExecuteTypedCall(expectedReturnCs, expectedReturnIp, targetCs, CallDistance.Far, BitWidth.DWORD_32, typedCall); } /// /// Pops the stacked near return address (IP) immediately, with the same operand bytes as a /// ret n: the return of a typed callee, which has no to return. /// /// Bytes to pop after the return address (0 for a plain ret). public void NearReturn(ushort numberOfBytesToPop) => ReturnOperationsHelper.NearRet16(numberOfBytesToPop); /// /// Pops the stacked near return address (IP) immediately, the plain ret of a typed callee that /// pops no parameter bytes. /// public void NearReturn() => NearReturn(0); /// /// Pops the stacked far return address (CS:IP) immediately, with the same operand bytes as a /// retf n: the return of a typed callee, which has no to return. /// /// Bytes to pop after the return address (0 for a plain retf). public void FarReturn(ushort numberOfBytesToPop) => ReturnOperationsHelper.FarRet16(numberOfBytesToPop); /// /// Pops the stacked far return address (CS:IP) immediately, the plain retf of a typed callee /// that pops no parameter bytes. /// public void FarReturn() => FarReturn(0); /// /// Pops the stacked near return address (EIP) immediately, with the same operand bytes as an /// o32 ret n: the return of a typed callee, which has no to return. /// /// Bytes to pop after the return address (0 for a plain o32 ret). public void NearReturn32(ushort numberOfBytesToPop) => ReturnOperationsHelper.NearRet32(numberOfBytesToPop); /// /// Pops the stacked near return address (EIP) immediately, the plain o32 ret of a typed /// callee that pops no parameter bytes. /// public void NearReturn32() => NearReturn32(0); /// /// Pops the stacked far return address (CS:EIP) immediately, with the same operand bytes as an /// o32 retf n: the return of a typed callee, which has no to return. /// /// Bytes to pop after the return address (0 for a plain o32 retf). public void FarReturn32(ushort numberOfBytesToPop) => ReturnOperationsHelper.FarRet32(numberOfBytesToPop); /// /// Pops the stacked far return address (CS:EIP) immediately, the plain o32 retf of a /// typed callee that pops no parameter bytes. /// public void FarReturn32() => FarReturn32(0); /// /// Performs a typed near call with the argument pushes folded into the call, without a caller /// clean-up: the no- form of /// . /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The typed callee, ending with or /// . /// The argument words in callee slot order (first slot first); the helper /// pushes the last word first. /// The return type of the typed callee. /// The value the typed callee returned. /// The typed callee did not return to the expected return address. public T CallWithStackArguments(ushort expectedReturnCs, ushort expectedReturnIp, Func typedCall, params ushort[] arguments) => CallWithStackArguments(expectedReturnCs, expectedReturnIp, 0, typedCall, arguments); /// /// Performs a typed near call with the argument pushes folded into the call: pushes /// in reverse argument order (the order the original /// push instructions ran, so the memory writes are identical), then performs the same /// near typed call as and finally steps SP by /// (the caller's add sp,n whose flags were dead). /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The bytes the caller pops after the call; 0 when the callee's /// ret n or no clean-up instruction consumes the arguments. /// The typed callee, ending with or /// . /// The argument words in callee slot order (first slot first); the helper /// pushes the last word first. /// The return type of the typed callee. /// The value the typed callee returned. /// The typed callee did not return to the expected return address. public T CallWithStackArguments(ushort expectedReturnCs, ushort expectedReturnIp, int cleanupBytes, Func typedCall, params ushort[] arguments) => _typedCalls.CallWithStackArgumentsCore(expectedReturnCs, expectedReturnIp, cleanupBytes, typedCall, arguments, 0); /// /// Performs a typed near call reserving the argument stack space without writing it: steps SP /// by exactly as the pushes of /// would, but /// leaves the bytes untouched because the callee reads them as parameters and the slots are /// proved private. Generated code calls this only under the /// AbandonedStackSlotsUnobserved relaxation. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The bytes the argument pushes would have written. /// The typed callee, ending with or /// . /// The return type of the typed callee. /// The value the typed callee returned. /// The typed callee did not return to the expected return address. public T CallWithStackSpace(ushort expectedReturnCs, ushort expectedReturnIp, int argumentBytes, Func typedCall) => CallWithStackSpace(expectedReturnCs, expectedReturnIp, 0, argumentBytes, typedCall); /// /// Performs a typed near call reserving the argument stack space without writing it: same /// stack contract as /// plus the caller's /// step afterwards. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The bytes the caller pops after the call. /// The bytes the argument pushes would have written. /// The typed callee, ending with or /// . /// The return type of the typed callee. /// The value the typed callee returned. /// The typed callee did not return to the expected return address. public T CallWithStackSpace(ushort expectedReturnCs, ushort expectedReturnIp, int cleanupBytes, int argumentBytes, Func typedCall) => _typedCalls.CallWithStackArgumentsCore(expectedReturnCs, expectedReturnIp, cleanupBytes, typedCall, [], argumentBytes); /// /// Performs a typed near call with the argument pushes folded into the call, for a callee that /// returns no value and whose caller runs no clean-up: the no-cleanup form of /// . /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The typed callee, ending with or /// . /// The argument words in callee slot order. /// The typed callee did not return to the expected return address. public void CallWithStackArguments(ushort expectedReturnCs, ushort expectedReturnIp, Action typedCall, params ushort[] arguments) => CallWithStackArguments(expectedReturnCs, expectedReturnIp, 0, typedCall, arguments); /// /// Performs a typed near call with the argument pushes folded into the call, for a callee that /// returns no value: same stack contract as /// . /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The bytes the caller pops after the call. /// The typed callee. /// The argument words in callee slot order. /// The typed callee did not return to the expected return address. public void CallWithStackArguments(ushort expectedReturnCs, ushort expectedReturnIp, int cleanupBytes, Action typedCall, params ushort[] arguments) => _typedCalls.CallWithStackArgumentsCore(expectedReturnCs, expectedReturnIp, cleanupBytes, typedCall, arguments, 0); /// /// Performs a typed near call reserving the argument stack space without writing it, for a /// callee that returns no value: same stack contract as /// . /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The bytes the argument pushes would have written. /// The typed callee. /// The typed callee did not return to the expected return address. public void CallWithStackSpace(ushort expectedReturnCs, ushort expectedReturnIp, int argumentBytes, Action typedCall) => CallWithStackSpace(expectedReturnCs, expectedReturnIp, 0, argumentBytes, typedCall); /// /// Performs a typed near call reserving the argument stack space without writing it, for a /// callee that returns no value and whose caller pops after /// the call. /// /// The expected value of the CS register after the call. /// The expected value of the IP register after the call. /// The bytes the caller pops after the call. /// The bytes the argument pushes would have written. /// The typed callee. /// The typed callee did not return to the expected return address. public void CallWithStackSpace(ushort expectedReturnCs, ushort expectedReturnIp, int cleanupBytes, int argumentBytes, Action typedCall) => _typedCalls.CallWithStackArgumentsCore(expectedReturnCs, expectedReturnIp, cleanupBytes, typedCall, [], argumentBytes); /// /// The no-op an entry wrapper returns after its typed method already performed /// the return ( / popped the stacked return address and /// set CS:IP). Returning it is exact: the wrapper adds no frame and the action does nothing. /// public static Action Returned { get; } = () => { }; /// /// Call the given callback number /// /// The callback identifier. public void Callback(ushort callbackNumber) { _callbackHandler.Run(callbackNumber); } /// /// Runs the callback whose instruction sits at : and tells /// whether the handler left CS:IP somewhere else. /// CS:IP is set first so handler code that reads it sees the callback's own address, like the interpreter does. /// A handler that stopped the machine (DOS terminate, TSR) exits here, because generated code would otherwise /// keep running the instruction after the callback. /// /// The segment of the callback instruction. /// The offset of the callback instruction. /// The callback identifier. /// true when the handler moved CS:IP away from the callback instruction (DOS EXEC, terminate, TSR). /// The callback stopped the machine. public bool CallbackMovedCsIp(ushort cs, ushort ip, ushort callbackNumber) { State.CS = cs; State.IP = ip; _callbackHandler.Run(callbackNumber); if (!State.IsRunning) { Exit(); } return State.CS != cs || State.IP != ip; } /// /// Runs the callback whose instruction sits at :, for callbacks /// whose handler is known to keep CS:IP at the callback instruction. A handler that moved CS:IP elsewhere /// fails as untested; generated code emits a dispatch over the observed targets instead (see /// ). /// /// The segment of the callback instruction. /// The offset of the callback instruction. /// The callback identifier. /// The callback stopped the machine. /// The callback moved CS:IP away from the callback instruction. public void Callback(ushort cs, ushort ip, ushort callbackNumber) { if (CallbackMovedCsIp(cs, ip, callbackNumber)) { throw FailAsUntested($"Untested callback CS:IP change at {cs:X4}:{ip:X4}: moved to {State.CS:X4}:{State.IP:X4}"); } } /// /// Runs a managed internal-program child to its terminate, then resumes the parent's observed /// fallthrough at :. A terminate /// targeting anywhere else propagates. /// /// Segment of the parent's observed resume address. /// Offset of the parent's observed resume address. /// The child's generated entry. /// The parent's generated continuation at the resume address. /// The action ending the dispatch. public Action RunInternalProgramChild(ushort resumeCs, ushort resumeIp, Func child, Func continuation) => _dosChildProcesses.RunInternalProgramChild(resumeCs, resumeIp, child, continuation); /// /// The root entry of a program a terminate can resume through the batch engine: runs /// , and while a terminate resumes at an entry /// arms - a batch launch's observed entry - runs that entry, /// so a batch of programs plays inside the root's dispatch like the interpreted run. A resume /// at an address discovery never armed fails as untested; a halt propagates. /// /// The generated entry the program starts at. /// The (resume address, entry) pairs the observed terminates /// resume at. /// The root entry action: it ends only when the program halts or an unobserved /// resume unwinds. public Func RunBatchPrograms(Func program, params CallLanding[] batchPrograms) => _dosChildProcesses.RunBatchPrograms(program, batchPrograms); /// /// Performs an interrupt call by executing the given function and returning to the specified return address. /// /// The expected value of the CS register after the interrupt call. /// The expected value of the IP register after the interrupt call. /// The CS value of the interrupt handler, executed in for the duration of the call. /// The function to execute as part of the interrupt call. public void InterruptCall(ushort expectedReturnCs, ushort expectedReturnIp, ushort targetCs, Func function) { ExecuteInterruptCall(expectedReturnCs, expectedReturnIp, targetCs, function, NoRedirectedReturns); } /// /// Performs an interrupt call and tells whether the handler returned to one of the addresses the /// call was observed to be redirected to instead of /// :. /// The return address pushed on the stack is still the expected one, so handlers that read operand /// bytes from it keep working; a handler that rewrites the stacked return address and lands on a /// listed address ends the call there without running the override registered there. /// /// The expected value of the CS register after the interrupt call. /// The expected value of the IP register after the interrupt call. /// The vector number to call for the interrupt. /// Addresses the call was observed to return to besides the expected one. /// true when the call ended at a redirected return address, false when it /// ended at the expected return address. /// If the interrupt vector number is not recognized. public bool InterruptCallReturnedElsewhere(ushort expectedReturnCs, ushort expectedReturnIp, byte vectorNumber, SegmentedAddress[] redirectedReturns) { if (State.CpuMode is CpuMode.Protected or CpuMode.Virtual8086) { return ExecuteProtectedInterruptCall(expectedReturnCs, expectedReturnIp, vectorNumber, redirectedReturns, SearchFunctionOverride); } SegmentedAddress target = Machine.InterruptVectorTable[vectorNumber]; Func? function = SearchFunctionOverride(target); if (function is null) { throw FailAsUntested($"Could not find an override at address {target}"); } return ExecuteInterruptCall(expectedReturnCs, expectedReturnIp, target.Segment, function, redirectedReturns); } private bool ExecuteProtectedInterruptCall(ushort expectedReturnCs, ushort expectedReturnIp, byte vectorNumber, SegmentedAddress[] redirectedReturns, Func?> resolveHandler) { uint expectedStackAddress = State.StackPhysicalAddress; // Dispatch already pushes the return frame and selects the gate's target. Generated code // passes the return address explicitly because it does not continuously synchronize IP. SegmentedAddress expectedReturn = new(expectedReturnCs, expectedReturnIp); SegmentedAddress target = ProtectedModeInterruptDispatcher.Dispatch( State, Memory, Stack, vectorNumber, checkGateDpl: true, errorCode: null, expectedReturn); Func function = resolveHandler(target) ?? throw FailAsUntested($"Could not find an override at address {target}"); return ExecuteCallEnsuringSameStack(expectedReturnCs, expectedReturnIp, target.Segment, function, () => { Action returnAction = function.Invoke(0); returnAction.Invoke(); }, redirectedReturns, expectedStackAddress, false); } private bool ExecuteInterruptCall(ushort expectedReturnCs, ushort expectedReturnIp, ushort targetCs, Func function, SegmentedAddress[] redirectedReturns) { return ExecuteCallEnsuringSameStack(expectedReturnCs, expectedReturnIp, targetCs, function, () => { Stack.PushInterruptFrame(new SegmentedAddress(expectedReturnCs, expectedReturnIp)); InterruptFlag = false; Action returnAction = function.Invoke(0); returnAction.Invoke(); }, redirectedReturns, State.StackPhysicalAddress, true); } /// /// Performs an interrupt call. /// /// The excepted value of the CS register after the interrupt call. /// The excepted value of the IP register after the interrupt call. /// The vector number to call for the interrupt. /// If the interrupt vector number is not recognized. public void InterruptCall(ushort expectedReturnCs, ushort expectedReturnIp, byte vectorNumber) { InterruptCallReturnedElsewhere(expectedReturnCs, expectedReturnIp, vectorNumber, NoRedirectedReturns); } /// /// A branch probe: reports the value of a condition to and /// returns it. Generated code produced with the branch probe option wraps the condition of each /// if, loop and conditional expression in a call of this method. /// /// The site number of the probe, as listed in the manifest of the generated program. /// /// The value of the condition. /// . public bool Branch(int site, bool condition) { Machine.BranchProbeObserver?.OnBranch(site, condition); return condition; } /// /// A switch probe: reports the value a switch selects on to /// and returns it with its type unchanged. /// /// The integer type of the value. /// The site number of the probe, as listed in the manifest of the generated program. /// /// The value of the switch. /// . public T Selector(int site, T value) where T : struct, IBinaryInteger { Machine.BranchProbeObserver?.OnSelector(site, uint.CreateTruncating(value)); return value; } /// /// Tells the service call observer that the statement after this one calls the implementation of an /// interrupt service directly. Generated code produced with the check build option calls it before each /// such call, because a direct call passes no handler code that could raise the event. The event equals /// the one the same service raises when it is reached through its stub, except for /// . /// Does nothing when is not set, and for a vector whose installed /// handler raises no event through its stub either (see ). /// /// The interrupt vector of the service. /// The selector value of the service, or null for a handler with a single /// service. /// The value of each input the service entry binds to its implementation, in the /// entry's order, encoded as encodes the registers. /// The number of inputs differs from the number the service /// entry binds. public void ServiceCalled(byte vectorNumber, int? selector, params uint[] inputs) { InstalledInterruptHandlers installed = Machine.InstalledInterruptHandlers; if (installed.ServiceCallEvents.ObserverFor(vectorNumber) is not { } observer || !installed.TryGetHandler(vectorNumber, out IInterruptHandler? handler) || handler is not InterruptHandler) { return; } InterruptServiceEntry entry = handler.Services switch { HandlerServices.SingleService single => single.Service, HandlerServices.SelectedServices selected when selector is { } selectorValue => selected.Services.GetValueOrDefault(selectorValue) ?? InterruptServiceEntry.Unknown, _ => InterruptServiceEntry.Unknown }; if (entry.Inputs.Count != inputs.Length) { throw new InvalidOperationException( $"Service {entry.Name} of interrupt 0x{vectorNumber:X2} binds {entry.Inputs.Count} inputs, but {inputs.Length} were given."); } ServiceCallInput[] callInputs = new ServiceCallInput[inputs.Length]; for (int i = 0; i < inputs.Length; i++) { callInputs[i] = new ServiceCallInput(entry.Inputs[i], inputs[i]); } observer.OnServiceCall(new ServiceCall(vectorNumber, selector, entry, true, callInputs)); } /// /// Performs a typed interrupt service call with the same stack traffic the interpreted /// int + stub + iret path performs: pushes the FLAGS/CS/IP frame, clears IF, /// runs the handler's entry bookkeeping (), /// invokes the service implementation, then pops the frame like iret does and restores /// the stacked FLAGS (including the flags wrote into the stack /// image). Used only where the service returns normally. /// /// The CS of the continuation the frame must return to. /// The IP of the continuation the frame must return to. /// The installed handler the service belongs to. /// The typed service implementation call; runs with the frame pushed. /// Writes the service's flag results into the stacked FLAGS word, /// the way the interpreted dispatch's SetFlagOnInterruptStack does. /// The service implementation's return value. /// The frame the service left does not return to the /// expected continuation. public T ServiceCall(ushort expectedReturnCs, ushort expectedReturnIp, IInterruptHandler handler, Func invocation, Action stackedFlags) => _serviceCalls.ServiceCallCore(expectedReturnCs, expectedReturnIp, invocation, stackedFlags, handler as InterruptHandler); /// /// for a /// typed service that has no entry bookkeeping: the printer selects this overload when the /// bound service entry keeps the handler's entry hook off. /// public T ServiceCall(ushort expectedReturnCs, ushort expectedReturnIp, Func invocation, Action stackedFlags) => _serviceCalls.ServiceCallCore(expectedReturnCs, expectedReturnIp, invocation, stackedFlags, null); /// /// for a /// service that returns no flag on the interrupt stack. /// public T ServiceCall(ushort expectedReturnCs, ushort expectedReturnIp, IInterruptHandler handler, Func invocation) => ServiceCall(expectedReturnCs, expectedReturnIp, handler, invocation, _ => { }); /// /// for a service that returns /// no flag on the interrupt stack. /// public T ServiceCall(ushort expectedReturnCs, ushort expectedReturnIp, Func invocation) => ServiceCall(expectedReturnCs, expectedReturnIp, invocation, _ => { }); /// /// for a /// service with no return value. /// public void ServiceCall(ushort expectedReturnCs, ushort expectedReturnIp, IInterruptHandler handler, Action invocation) { ServiceCall(expectedReturnCs, expectedReturnIp, handler, () => { invocation(); return 0; }, _ => { }); } /// /// for a service with no /// return value. /// public void ServiceCall(ushort expectedReturnCs, ushort expectedReturnIp, Action invocation) { ServiceCall(expectedReturnCs, expectedReturnIp, () => { invocation(); return 0; }, _ => { }); } /// /// A typed service call that does not write the interrupt frame: IF is saved and cleared for /// the call, SP is lowered by six around the handler's /// so the entry bookkeeping sees the stack pointer the frame would have left, and the /// invocation runs frameless. Flag results stay plain outputs; no return address is checked. /// /// The installed handler whose entry bookkeeping the call runs. /// The typed service implementation to call. /// The service implementation's return value. public T ServiceCall(IInterruptHandler handler, Func invocation) => _serviceCalls.ServiceCallFramelessCore(handler as InterruptHandler, invocation); /// /// for a service with no return value. /// public void ServiceCall(IInterruptHandler handler, Action invocation) { ServiceCall(handler, () => { invocation(); return 0; }); } /// /// A terminating service call invoked directly by generated code /// (return TerminateCall(cs1, 0x0451, () => Dos.Terminate(AL))): positions CS:IP at the /// int's return address so the implementation pushes the same frame bytes the /// interpreted int pushed, then never returns to the call site - it halts or unwinds. /// /// The segment the interpreted int frame returns to. /// The offset the interpreted int frame returns to. /// The terminating service implementation to call. /// Never returns: the type only lets the call print as a method's returned action. public Action TerminateCall(ushort expectedReturnCs, ushort expectedReturnIp, Func invocation) => _serviceCalls.TerminateCall(expectedReturnCs, expectedReturnIp, invocation); /// /// A typed DOS EXEC-and-run call /// ((AX, flag1, DS, ES) = ExecChild(cs1, 0x0193, 0x21)): the helper pushes the /// int frame the interpreted call pushed, clears IF like interrupt entry, then invokes /// the generated interrupt stub of the call's vector. The stub runs its dispatch, the DOS /// callback loads and launches the child and the callback-moved CS:IP check jumps to the /// observed child entry, which runs to its terminate; the termination restores this parent /// and unwinds here through the pushed frame. A failed EXEC ran no child: the stub's own /// iret pops the frame back and the service's carry/AX outputs are returned. /// /// The segment the interpreted int frame returns to. /// The offset the interpreted int frame returns to. /// The interrupt vector whose generated stub the call runs. /// AX, the carry flag and DS/ES as the resumed parent leaves them. /// The EXEC vector had no generated stub or a /// termination resumed at an address discovery did not observe. public (ushort ax, bool carryFlag, ushort ds, ushort es) ExecChild( ushort expectedReturnCs, ushort expectedReturnIp, byte vectorNumber) => _dosChildProcesses.ExecChild(expectedReturnCs, expectedReturnIp, vectorNumber); /// Writes a carry result into the stacked FLAGS of a /// frame. protected void CarryOnInterruptStack(bool value) => Stack.SetFlagOnInterruptStack(Flags.Carry, value); /// protected void ParityOnInterruptStack(bool value) => Stack.SetFlagOnInterruptStack(Flags.Parity, value); /// protected void AuxiliaryOnInterruptStack(bool value) => Stack.SetFlagOnInterruptStack(Flags.Auxiliary, value); /// protected void ZeroOnInterruptStack(bool value) => Stack.SetFlagOnInterruptStack(Flags.Zero, value); /// protected void SignOnInterruptStack(bool value) => Stack.SetFlagOnInterruptStack(Flags.Sign, value); /// protected void OverflowOnInterruptStack(bool value) => Stack.SetFlagOnInterruptStack(Flags.Overflow, value); /// /// Returns the installed interrupt handler of type . /// /// The handler type. /// No handler of the type is installed. internal THandler GetInterruptHandler() where THandler : class, IInterruptHandler { return Machine.InstalledInterruptHandlers.Handlers.Values.OfType() .FirstOrDefault() ?? throw FailAsUntested( $"No installed interrupt handler of type {typeof(THandler).Name}"); } /// /// Performs an interrupt call to a handler of the generated program itself. The generated code /// calls directly because the observed vector target was the handler; /// when the vector no longer points to : /// the call cannot deliver that handler and fails as untested. Otherwise the same /// pushed-FLAGS / cleared-IF / pushed-return-address frame as /// applies. /// /// The expected value of the CS register after the interrupt call. /// The expected value of the IP register after the interrupt call. /// The vector number to call for the interrupt. /// The CS of the handler entry the vector must point to. /// The IP of the handler entry the vector must point to. /// The generated method of the handler, executed as part of the interrupt call. /// If the interrupt vector no longer points to the handler. public void InterruptCall(ushort expectedReturnCs, ushort expectedReturnIp, byte vectorNumber, ushort handlerCs, ushort handlerIp, Func handler) { if (State.CpuMode is CpuMode.Protected or CpuMode.Virtual8086) { ExecuteProtectedInterruptCall(expectedReturnCs, expectedReturnIp, vectorNumber, NoRedirectedReturns, target => { if (target.Segment != handlerCs || target.Offset != handlerIp) { throw FailAsUntested($"Interrupt vector 0x{vectorNumber:X2} points to {target}, not to the handler {handlerCs:X4}:{handlerIp:X4} the generated code calls"); } return handler; }); return; } SegmentedAddress target = Machine.InterruptVectorTable[vectorNumber]; if (target.Segment != handlerCs || target.Offset != handlerIp) { throw FailAsUntested($"Interrupt vector 0x{vectorNumber:X2} points to {target}, not to the handler {handlerCs:X4}:{handlerIp:X4} the generated code calls"); } ExecuteInterruptCall(expectedReturnCs, expectedReturnIp, handlerCs, handler, NoRedirectedReturns); } /// /// Performs the CPU-fault entry sequence used by generated code: pushes the flags register and the /// faulting instruction's address as the return frame, clears the interrupt flag, and sets CS:IP to the /// resolved fault handler target. Control transfer into the handler partition happens at the call site. /// /// The CS of the instruction that faulted, pushed as the return segment. /// The IP of the instruction that faulted, pushed as the return offset. /// The fault handler address resolved through the interrupt vector table. public void EnterCpuFaultHandler(ushort faultingInstructionCs, ushort faultingInstructionIp, SegmentedAddress target) { Stack.PushInterruptFrame(new SegmentedAddress(faultingInstructionCs, faultingInstructionIp)); InterruptFlag = false; LoadSegmentRegister((uint)SegmentRegisterIndex.CsIndex, target.Segment); IP = target.Offset; } /// /// Dispatches a CPU fault to the matching generated handler partition. /// /// The CPU exception that triggered the fault. /// The CS of the faulting instruction. /// The IP of the faulting instruction. /// The list of fault handler targets to match against the live IVT or IDT. /// The addresses discovery observed this fault resuming at; the /// return action fails as untested when the handler leaves control anywhere else. /// The return action from the matching handler partition. /// Thrown when no target matches the live fault handler. public Action DispatchCpuFault(CpuException exception, ushort faultCs, ushort faultIp, IReadOnlyList targets, SegmentedAddress[] resumeTargets) { bool protectedMode = State.CpuMode is CpuMode.Protected or CpuMode.Virtual8086; SegmentedAddress handler; if (protectedMode) { handler = ResolveCpuFaultTarget(exception.InterruptVector, exception.ErrorCode, faultCs, faultIp); } else { handler = _interruptVectorTable[exception.InterruptVector]; } foreach (CpuFaultTarget target in targets) { if (target.Handler == handler) { if (!protectedMode) { EnterCpuFaultHandler(faultCs, faultIp, handler); } Action resume = target.Invoke(); if (resume.Target is FaultResumeAction nested && resume == nested.Invoke) { return resume; } return new FaultResumeAction(this, resume, faultCs, faultIp, handler, resumeTargets).Invoke; } } throw FailAsUntested($"Untested CPU fault target {handler} at {faultCs:X4}:{faultIp:X4}"); } private sealed class FaultResumeAction(CSharpOverrideHelper owner, Action resume, ushort faultCs, ushort faultIp, SegmentedAddress handler, SegmentedAddress[] resumeTargets) { public void Invoke() { resume(); owner.VerifyObservedFaultResume(faultCs, faultIp, handler, resumeTargets); } } /// Fails as untested when the fault handler's return left control at an address /// discovery did not observe the fault resuming at. private void VerifyObservedFaultResume(ushort faultCs, ushort faultIp, SegmentedAddress handler, SegmentedAddress[] resumeTargets) { SegmentedAddress landedAddress = State.IpSegmentedAddress; foreach (SegmentedAddress target in resumeTargets) { if (target == landedAddress) { return; } } throw FailAsUntested($"The fault at {faultCs:X4}:{faultIp:X4} through {handler} resumed at {landedAddress}, which discovery did not observe it resuming on"); } /// /// Resolves the fault-handler target for a CPU exception caught in generated code and performs the /// full entry sequence: protected mode AND Virtual-8086 mode both walk the IDT via /// (respecting DPL escalation, stack switch, and /// error-code push); only real mode uses the real-mode IVT via . /// Mirrors /// . /// /// The CPU exception vector. /// The error code pushed by exceptions that carry one. /// The faulting instruction's code segment. /// The faulting instruction's offset. /// The handler address selected by the current interrupt table. public SegmentedAddress ResolveCpuFaultTarget(byte vectorNumber, ushort? errorCode, ushort faultingCs, ushort faultingIp) { if (State.CpuMode is CpuMode.Protected or CpuMode.Virtual8086) { return ProtectedModeInterruptDispatcher.Dispatch( State, Memory, Stack, vectorNumber, checkGateDpl: false, errorCode, new SegmentedAddress(faultingCs, faultingIp)); } SegmentedAddress target = Machine.InterruptVectorTable[vectorNumber]; EnterCpuFaultHandler(faultingCs, faultingIp, target); return target; } /// /// Returns the C# function override, or null if not found. /// /// The where the function is defined. /// The C# function override, or null if not found. /// /// Returns the C# function override, or null if not found. Checks /// (keyed by segment:offset) first, then, in protected mode only, resolves 's /// segment live through the current GDT/LDT to a flat linear address and checks /// - so a linear-address override keeps firing even if the /// selector currently mapping to that address changed since registration. /// /// The where the function is defined. /// The C# function override, or null if not found. public Func? SearchFunctionOverride(SegmentedAddress target) { if (FunctionInformations.TryGetValue(target, out FunctionInformation? functionInformation)) { return functionInformation.FunctionOverride; } if (State.CpuMode != CpuMode.Protected) { return null; } if (!DescriptorTableReader.TryReadDescriptor(target.Segment, State.Gdtr.Base, State.Gdtr.Limit, State.Ldtr.DescriptorCache.Base, State.Ldtr.DescriptorCache.Limit, address => Memory[Memory.Mmu.TranslateLinearAddress(address, isWrite: false)], out SegmentDescriptorCache descriptor)) { return null; } uint linearAddress = descriptor.Base + target.Offset; return LinearFunctionInformations.TryGetValue(linearAddress, out FunctionInformation? linearFunctionInformation) ? linearFunctionInformation.FunctionOverride : null; } private static readonly SegmentedAddress[] NoRedirectedReturns = []; private readonly Dictionary<(SegmentedAddress ExpectedReturn, Func? Target), CallLanding[]> _callLandings = new(); /// /// Whether generated code may only run the call landings and hardware interrupt handlers that /// discovery observed () or any override registered there /// (). The base implementation keeps the permissive chain for hand-written /// overrides; a generated program overrides it so unobserved landings and unobserved handler /// deliveries fail as untested. /// protected virtual bool ObservedTransfersOnly => false; /// /// Arms the mid-call landings discovery observed for the call site expecting to return to /// , for every callee of that site. A landing on another registered /// override fails as untested. /// protected void DefineCallLandings(SegmentedAddress expectedReturn, Func?[] targets, params CallLanding[] landings) { foreach (Func? target in targets) { _callLandings[(expectedReturn, target)] = landings; } } /// /// Runs a call dispatch and its override chain, then tells whether the call ended at one of /// (true) or at the expected return address /// (false). /// private bool ExecuteCallEnsuringSameStack(ushort expectedReturnCs, ushort expectedReturnIp, ushort targetCs, Func function, Action action, SegmentedAddress[] redirectedReturns, uint expectedStackAddress, bool interruptCall) { // CS is set to the callee's segment for the duration of the call: this is the segment the emulated // CPU runs in while inside the callee, so reads of CS (e.g. a "push CS" idiom, or a protected-mode // CPL/privilege check) observe the right value and descriptor cache. For near calls targetCs equals // expectedReturnCs so this is a same-selector no-op reload. IP is set to the expected return offset // as a fallback for the post-call validation below; generated code never reads State.IP mid-call // (CheckExternalEvents takes the offset explicitly), and the callee's return action overwrites CS:IP // with the actual return address before the loop runs. LoadSegmentRegister((uint)SegmentRegisterIndex.CsIndex, targetCs); State.IP = expectedReturnIp; SegmentedAddress expectedReturn = new SegmentedAddress(expectedReturnCs, expectedReturnIp); ExecuteCallConsumingUnwindTo(function, action, expectedReturn, expectedStackAddress, redirectedReturns); CSharpCallChainCaller caller = new(this, expectedReturn, expectedStackAddress, redirectedReturns); if (!ObservedTransfersOnly) { Machine.CfgCpu.FunctionHandlerInUse.RunOverrideChain(caller, null); return caller.EndedAtRedirectedReturn; } Func? landingTarget = interruptCall ? null : function; return RunObservedLandingChain(caller, expectedReturn, _callLandings.GetValueOrDefault((expectedReturn, landingTarget), [])); } /// /// The generated calls' landing dispatch: where the override chain runs whatever override is /// registered at a mid-call landing, this loop runs only the entries /// arms - the landings discovery observed for this call. Landing on an address another override /// is registered at but the call never observed fails as untested; a landing with no override at /// all unwinds exactly like the chain does. /// private bool RunObservedLandingChain(CSharpCallChainCaller caller, SegmentedAddress expectedReturn, CallLanding[] landings) { while (true) { if (!State.IsRunning) { caller.OnMachineStopped(); return caller.EndedAtRedirectedReturn; } SegmentedAddress landedAddress = State.IpSegmentedAddress; if (landedAddress == expectedReturn || caller.AcceptsRedirectedReturn(landedAddress, State.StackPhysicalAddress)) { return caller.EndedAtRedirectedReturn; } CallLanding? landing = null; foreach (CallLanding candidate in landings) { if (candidate.Address == landedAddress) { landing = candidate; break; } } if (landing is { } armed) { caller.RunLanding(armed); continue; } if (SearchFunctionOverride(landedAddress) is not null) { throw FailAsUntested( $"The call expecting to return to {expectedReturn} landed at {landedAddress}, which discovery did not observe it landing on"); } throw new CallStackUnwindException(landedAddress, $"The call expecting to return to {expectedReturn} transferred control to {landedAddress} " + $"but there is no C# override at {landedAddress} and it is not the call's expected return address. " + "Refusing to fall back to the interpreter."); } } /// /// Runs a dispatch started by a call and consumes an unwind that landed on the call's expected return /// address, which is how code that unwinds its own call stack frame returns. Any other unwind is not /// this call's return, so it keeps propagating towards the frame that can interpret it. /// /// Starting point of the dispatch in the jump dispatcher. /// Dispatch to run. /// Address the call that started the dispatch expects to return to. /// Physical stack address before the call's pushes. /// Other addresses the call accepts as its return. private void ExecuteCallConsumingUnwindTo(Func function, Action action, SegmentedAddress expectedReturn, uint expectedStackAddress, SegmentedAddress[] redirectedReturns) { try { ExecuteCall(function, action); } catch (CallStackUnwindException exception) when (IsAcceptedUnwindTarget(exception.Target, expectedReturn, expectedStackAddress, redirectedReturns)) { // The unwound code already left CS:IP at an accepted return address, so the validation loop // of the surrounding call sees it and does not run. } } private bool IsAcceptedUnwindTarget(SegmentedAddress target, SegmentedAddress expectedReturn, uint expectedStackAddress, SegmentedAddress[] redirectedReturns) { if (target == expectedReturn) { return true; } return CSharpCallChainCaller.IsRedirectedReturn(redirectedReturns, target, State.StackPhysicalAddress, expectedStackAddress); } /// /// Logs a nested override call: once at warning level per (expected return, landing) pair of this /// helper, then at debug level, since each occurrence grows the C# stack once more. /// private void LogNestedOverrideCall(SegmentedAddress expectedReturn, SegmentedAddress actualReturn, uint expectedStackAddress, uint actualStackAddress, string? functionName) { if (_warnedNestedOverrideCalls.Add((expectedReturn, actualReturn))) { if (_loggerService.IsEnabled(LogLevel.Warning)) { _loggerService.LogWarning( "The call expecting to return to {ExpectedReturn} continued at {ActualReturn} (stack {ActualStackAddress}, before the call {ExpectedStackAddress}). Running {FunctionName} inside the call: the C# stack grows each time this happens. Logged once per call and target.", expectedReturn, actualReturn, actualStackAddress, expectedStackAddress, functionName); } } else if (_loggerService.IsEnabled(LogLevel.Debug)) { _loggerService.LogDebug( "The call expecting to return to {ExpectedReturn} continued at {ActualReturn} again. Running {FunctionName} inside the call.", expectedReturn, actualReturn, functionName); } } /// /// Executes the given action with the specified function as starting point in the jump dispatcher. /// /// The function to set as starting point in the jump dispatcher. /// The action to execute. /// /// This method temporarily replaces the current jump dispatcher with a new instance that has the specified function /// as its starting point. After the action has been executed, the original jump dispatcher is restored. /// private void ExecuteCall(Func function, Action action) { JumpDispatcher currentJumpDispatcher = JumpDispatcher; // Ensure the jump dispatcher has the function we are calling as starting point JumpDispatcher = JumpDispatcher.CreateNew(function); try { action.Invoke(); } finally { // Restored even when the call throws (e.g. an unwind to an outer frame), so an exception leaves // the dispatcher as it found it. JumpDispatcher = currentJumpDispatcher; } } /// /// Overrides the machine code at the specified segment and offset with a new implementation provided by the function. /// /// The segment of the instruction to override. /// The offset of the instruction to override. /// An action that provides the new implementation to use for the instruction. public void OverrideInstruction(ushort segment, ushort offset, Func renamedOverride) { AddressBreakPoint breakPoint = new( BreakPointType.CPU_EXECUTION_ADDRESS, MemoryUtils.ToPhysicalAddress( segment, offset), (_, _) => renamedOverride.Invoke().Invoke() , false); EmulatorBreakpointsManager.ToggleBreakPoint(breakPoint, true); } /// /// Overrides the machine code at the specified flat linear address, for protected-mode code whose /// selector's base may not be known/stable at registration time. See /// for the segment:offset overload. /// /// The flat linear address of the instruction to override. /// An action that provides the new implementation to use for the instruction. public void OverrideInstruction(uint linearAddress, Func renamedOverride) { AddressBreakPoint breakPoint = new( BreakPointType.CPU_EXECUTION_ADDRESS, linearAddress, (_, _) => renamedOverride.Invoke().Invoke() , false); EmulatorBreakpointsManager.ToggleBreakPoint(breakPoint, true); } /// /// Executes the specified action on top of the instruction at the specified segment and offset. /// /// The segment of the instruction to execute the action on. /// The offset of the instruction to execute the action on. /// The action to execute on top of the instruction. public void DoOnTopOfInstruction(ushort segment, ushort offset, Action action) { AddressBreakPoint breakPoint = new( BreakPointType.CPU_EXECUTION_ADDRESS, MemoryUtils.ToPhysicalAddress( segment, offset), (_, _) => action.Invoke() , false); EmulatorBreakpointsManager.ToggleBreakPoint(breakPoint, true); } /// /// Executes the specified action on top of the instruction at the specified flat linear address, for /// protected-mode code. See for the /// segment:offset overload. /// /// The flat linear address of the instruction to execute the action on. /// The action to execute on top of the instruction. public void DoOnTopOfInstruction(uint linearAddress, Action action) { AddressBreakPoint breakPoint = new( BreakPointType.CPU_EXECUTION_ADDRESS, linearAddress, (_, _) => action.Invoke() , false); EmulatorBreakpointsManager.ToggleBreakPoint(breakPoint, true); } /// /// Executes the specified action when the byte at the specified segment and offset is written to. /// /// The segment of the memory location to watch. /// The offset of the memory location to watch. /// The action to execute when the memory location is written to. public void DoOnMemoryWrite(ushort segment, ushort offset, Action action) { AddressBreakPoint breakPoint = new( BreakPointType.MEMORY_WRITE, MemoryUtils.ToPhysicalAddress(segment, offset), (_, _) => action.Invoke() , false); EmulatorBreakpointsManager.ToggleBreakPoint(breakPoint, true); } /// /// Executes the specified action when the byte at the specified segment and offset is written to. /// /// The segment of the memory location to watch. /// The offset of the memory location to watch. /// The action to execute when the memory location is written to. public void DoOnMemoryRead(ushort segment, ushort offset, Action action) { AddressBreakPoint breakPoint = new( BreakPointType.MEMORY_READ, MemoryUtils.ToPhysicalAddress(segment, offset), (_, _) => action.Invoke() , false); EmulatorBreakpointsManager.ToggleBreakPoint(breakPoint, true); } /// /// Checks if the vtable contains the expected segment and offset values. /// /// The index of the segment register to use. /// The offset of the vtable entry to check. /// The expected segment value. /// The expected offset value. /// Thrown when the found segment or offset value doesn't match the expected values. public void CheckVtableContainsExpected( int segmentRegisterIndex, ushort offset, ushort expectedSegment, ushort expectedOffset) { uint address = MemoryUtils.ToPhysicalAddress(State.SegmentRegisters.UInt16[segmentRegisterIndex], offset); (ushort foundSegment, ushort foundOffset) = Memory.SegmentedAddress16[address]; if (foundOffset != expectedOffset || foundSegment != expectedSegment) { throw FailAsUntested( $"Call table value changed, we would not call the method the game is calling. Expected: {new SegmentedAddress(expectedSegment, expectedOffset)} found: {new SegmentedAddress(foundSegment, foundOffset)}"); } } /// /// Call this in your override when you re-implement a function with a branch that seems to be never /// reached. /// The error message for the /// An new instance of that you should throw. /// public UnrecoverableException FailAsUntested(string message) { string error = $"Untested code reached, please tell us how to reach this state. Here is the message: {message}. Here is the Machine stack: {State}"; if (_loggerService.IsEnabled(LogLevel.Error)) { _loggerService.LogError("{Error}", error); } return new UnrecoverableException(error); } /// /// Compares instruction bytes at the segmented address against a selector signature using the /// current memory mapping. Null signature entries match any byte. /// /// The segment of the address whose bytes are compared. /// The offset of the address whose bytes are compared. /// The expected byte pattern; null entries match any byte. /// true when every non-null signature byte matches memory; otherwise false. public bool SelectorSignatureMatches(ushort segment, ushort offset, byte?[] signature) { return MemoryInstructionMatcher.MatchesSignature(Memory, new SegmentedAddress(segment, offset), signature); } /// /// Verifies that a single speculative instruction at the given segmented address still matches the /// signature decoded at exploration time. The generated code calls this immediately before the /// instruction's body so that self-modifying code performed by an earlier instruction in the same block /// is detected before the modified instruction's decode-time-baked body executes. If memory no longer /// matches, the speculative decode was wrong and execution falls back to . /// The current memory mapping is used to read the instruction bytes. /// /// The segment of the speculative instruction. /// The offset of the speculative instruction. /// The signature of the speculative instruction; null entries are wildcards for fields the decoder reads from memory at execution time. /// Thrown when memory at the instruction address does not match the expected signature. public void VerifySpeculativeEntryOrFail(ushort segment, ushort offset, byte?[] runSignature) { if (!SelectorSignatureMatches(segment, offset, runSignature)) { throw FailAsUntested($"Speculative code at {segment:X4}:{offset:X4} no longer matches memory"); } } /// /// Verifies the signatures of a straight-line run of speculative instructions, checked in memory /// order before the first instruction of the run executes. The generator emits this instead of one /// per instruction when it proves nothing between the run /// entry and a later instruction can change the run's bytes or leave the run. The failure message /// names the first instruction whose bytes differ, so a mid-run mutation is reported at the /// instruction that actually changed. /// /// The segment of the run's first instruction. /// The offset of the run's first instruction. /// The signature of each instruction of the run, in memory order; /// each signature's length is its instruction's length in bytes. /// Thrown when memory at any instruction of the run does not match its expected signature. public void VerifySpeculativeRunOrFail(ushort segment, ushort offset, byte?[][] runSignatures) { foreach (byte?[] signature in runSignatures) { VerifySpeculativeEntryOrFail(segment, offset, signature); offset = (ushort)(offset + signature.Length); } } /// /// Throws an exception if the given value is not one of the possible values. /// /// The value to check for support. /// The list of possible values that are supported. /// Thrown if the value is not in the list of supported values. public void FailIfValueIsNot(uint value, params uint[] possibleValues) { if (!possibleValues.Contains(value)) { throw FailAsUntested($"Value {value} not in list of supported values"); } } /// /// Runs any pending interrupt requests.
/// As long as the target programs triggers interrupts, you must call this often enough so interrupts can run. ///
/// The excepted value of the CS register after the interruption is done. /// The excepted value of the IP register after the interruption is done public void CheckExternalEvents(ushort expectedReturnCs, ushort expectedReturnIp) { // Like the interpreter after iret, check again at the same address each time a handler returns. bool interruptTaken; do { interruptTaken = CheckExternalEventsOnce(expectedReturnCs, expectedReturnIp); } while (interruptTaken); } private bool CheckExternalEventsOnce(ushort expectedReturnCs, ushort expectedReturnIp) { if (!State.IsRunning) { Exit(); } State.IncCycles(); // Override/generated code runs without returning to the interpreter run loop that pumps each of // these between instructions, so mirror that order here: increment the cycle, fire cycle // breakpoints (which may enqueue input events), process pending input, advance scheduled device // events (e.g. the PIT raising IRQ0), then deliver a pending PIC interrupt. Without this, queued // UI/headless input and external hardware interrupts would never reach generated code. Machine.EmulatorBreakpointsManager.CheckCpuCycleBreakPoints(); if (!_interruptGate.IsDeliveryHeld) { // Under a delivery hold (HardwareInterruptGate.HoldDelivery) input and device events are left pending as well, // so this code sees the same absence of events as a caller that runs CfgCpu.ExecuteNext itself. Machine.InputEventHub.ProcessAllPendingInputEvents(); Machine.EmulationLoopScheduler.ProcessEvents(); } if (!InterruptFlag || !_interruptGate.MustAsk || _interruptGate.AcceptInterrupt(new SegmentedAddress(expectedReturnCs, expectedReturnIp)) is not { } vectorNumber) { return false; } State.IsHalted = false; SegmentedAddress target = Machine.InterruptVectorTable[vectorNumber]; Func function = HardwareInterruptFunction(vectorNumber, target); ExecuteInterruptCall(expectedReturnCs, expectedReturnIp, target.Segment, function, NoRedirectedReturns); return true; } /// /// Resolves the function a hardware interrupt on invokes when its IVT /// entry points at . The base implementation accepts any override registered /// at , except that a delivery under /// fails as untested; a generated program that observed deliveries overrides it with a switch over /// the (vector, handler) pairs discovery observed. /// /// The interrupt vector the PIC raised. /// The address the vector's IVT entry holds. /// No override is registered at , /// or rejects the delivery. protected virtual Func HardwareInterruptFunction(byte vectorNumber, SegmentedAddress target) { if (ObservedTransfersOnly) { throw FailAsUntested($"Hardware interrupt 0x{vectorNumber:X2} targets {target}, which discovery did not observe as a handler of that vector"); } return SearchFunctionOverride(target) ?? throw FailAsUntested($"Could not find an override at address {target}"); } /// /// Call this to perform an interrupt request. /// /// The vector number to call public void Interrupt(byte vectorNumber) { _callbackHandler.Run(vectorNumber); } /// /// Defines C# functions for provided interrupt handlers so that when overriden code generates an interrupt, an override for it is found and executed. /// Does not currently handle mouse code which has more than a callback + iret. /// public void SetProvidedInterruptHandlersAsOverridden() { InterruptVectorTable ivt = new InterruptVectorTable(Memory); for (byte i = 0; i < 0xFF; i++) { SegmentedAddress handlerAddress = ivt[i]; if (handlerAddress.Segment == 0 && handlerAddress.Offset == 0) { continue; } int callback = i; DefineFunction(handlerAddress.Segment, handlerAddress.Offset, (offset) => { _callbackHandler.Run(callback); return InterruptRet(); }, false, $"provided_interrupt_handler_{ConvertUtils.ToHex(i)}"); } } /// /// Performs unsigned 8-bit division. /// /// The 16-bit dividend (AX). /// The 8-bit divisor. /// A tuple containing the 8-bit quotient (AL) and 8-bit remainder (AH) as unsigned register bits. /// Thrown when the divisor is zero or the quotient does not fit in a byte. public (byte Quotient, byte Remainder) Div8(ushort dividend, byte divisor) { byte quotient = Alu8.Div(dividend, divisor); return (quotient, (byte)(dividend % divisor)); } /// /// Performs unsigned 16-bit division. /// /// The 32-bit dividend (DX:AX). /// The 16-bit divisor. /// A tuple containing the 16-bit quotient (AX) and 16-bit remainder (DX) as unsigned register bits. /// Thrown when the divisor is zero or the quotient does not fit in a word. public (ushort Quotient, ushort Remainder) Div16(uint dividend, ushort divisor) { ushort quotient = Alu16.Div(dividend, divisor); return (quotient, (ushort)(dividend % divisor)); } /// /// Performs unsigned 32-bit division. /// /// The 64-bit dividend (EDX:EAX). /// The 32-bit divisor. /// A tuple containing the 32-bit quotient (EAX) and 32-bit remainder (EDX) as unsigned register bits. /// Thrown when the divisor is zero or the quotient does not fit in a dword. public (uint Quotient, uint Remainder) Div32(ulong dividend, uint divisor) { uint quotient = Alu32.Div(dividend, divisor); return (quotient, (uint)(dividend % divisor)); } /// /// Performs signed 8-bit division. /// /// The 16-bit signed dividend (AX). /// The 8-bit signed divisor. /// A tuple containing the 8-bit quotient (AL) and 8-bit remainder (AH) as unsigned register bits. /// Thrown when the divisor is zero or the quotient does not fit in a signed byte. public (byte Quotient, byte Remainder) IDiv8(short dividend, sbyte divisor) { sbyte quotient = Alu8.Idiv(dividend, divisor); return (unchecked((byte)quotient), unchecked((byte)(dividend % divisor))); } /// /// Performs signed 16-bit division. /// /// The 32-bit signed dividend (DX:AX). /// The 16-bit signed divisor. /// A tuple containing the 16-bit quotient (AX) and 16-bit remainder (DX) as unsigned register bits. /// Thrown when the divisor is zero or the quotient does not fit in a signed word. /// Thrown when the dividend is and the divisor is -1 (inherited ALU behavior). public (ushort Quotient, ushort Remainder) IDiv16(int dividend, short divisor) { short quotient = Alu16.Idiv(dividend, divisor); return (unchecked((ushort)quotient), unchecked((ushort)(dividend % divisor))); } /// /// Performs signed 32-bit division. /// /// The 64-bit signed dividend (EDX:EAX). /// The 32-bit signed divisor. /// A tuple containing the 32-bit quotient (EAX) and 32-bit remainder (EDX) as unsigned register bits. /// Thrown when the divisor is zero or the quotient does not fit in a signed dword. /// Thrown when the dividend is and the divisor is -1 (inherited ALU behavior). public (uint Quotient, uint Remainder) IDiv32(long dividend, int divisor) { int quotient = Alu32.Idiv(dividend, divisor); return (unchecked((uint)quotient), unchecked((uint)(dividend % divisor))); } /// /// Performs unsigned 16-bit multiplication. /// /// The 16-bit multiplicand (AX). /// The 16-bit multiplier. /// A tuple containing the 16-bit low half (AX) and 16-bit high half (DX) of the 32-bit product. public (ushort Low, ushort High) Mul16(ushort value1, ushort value2) { uint result = Alu16.Mul(value1, value2); return ((ushort)result, (ushort)(result >> 16)); } /// /// Performs unsigned 32-bit multiplication. /// /// The 32-bit multiplicand (EAX). /// The 32-bit multiplier. /// A tuple containing the 32-bit low half (EAX) and 32-bit high half (EDX) of the 64-bit product. public (uint Low, uint High) Mul32(uint value1, uint value2) { ulong result = Alu32.Mul(value1, value2); return ((uint)result, (uint)(result >> 32)); } /// /// Performs signed 16-bit multiplication. /// /// The 16-bit signed multiplicand (AX). /// The 16-bit signed multiplier. /// A tuple containing the 16-bit low half (AX) and 16-bit high half (DX) of the 32-bit product as unsigned register bits. public (ushort Low, ushort High) IMul16(short value1, short value2) { int result = Alu16.Imul(value1, value2); return (unchecked((ushort)result), unchecked((ushort)(result >> 16))); } /// /// Performs signed 32-bit multiplication. /// /// The 32-bit signed multiplicand (EAX). /// The 32-bit signed multiplier. /// A tuple containing the 32-bit low half (EAX) and 32-bit high half (EDX) of the 64-bit product as unsigned register bits. public (uint Low, uint High) IMul32(int value1, int value2) { long result = Alu32.Imul(value1, value2); return (unchecked((uint)result), unchecked((uint)(result >> 32))); } /// /// Reads a byte from an I/O port, like the in instruction. /// /// The I/O port to read from. /// The byte read from the port. public byte In8(ushort port) => Machine.IoPortDispatcher.ReadByte(port); /// /// Reads a word from an I/O port, like the in instruction. /// /// The I/O port to read from. /// The word read from the port. public ushort In16(ushort port) => Machine.IoPortDispatcher.ReadWord(port); /// /// Reads a double word from an I/O port, like the in instruction. /// /// The I/O port to read from. /// The double word read from the port. public uint In32(ushort port) => Machine.IoPortDispatcher.ReadDWord(port); /// /// Writes a byte to an I/O port, like the out instruction. /// /// The I/O port to write to. /// The byte to write. public void Out8(ushort port, byte value) => Machine.IoPortDispatcher.WriteByte(port, value); /// /// Writes a word to an I/O port, like the out instruction. /// /// The I/O port to write to. /// The word to write. public void Out16(ushort port, ushort value) => Machine.IoPortDispatcher.WriteWord(port, value); /// /// Writes a double word to an I/O port, like the out instruction. /// /// The I/O port to write to. /// The double word to write. public void Out32(ushort port, uint value) => Machine.IoPortDispatcher.WriteDWord(port, value); /// /// Index of the lowest set bit of a word, like the bsf instruction. /// /// The value to scan. /// The bit index (0-15) of the lowest set bit. public ushort BitScanForward16(ushort value) => (ushort)BitOperations.TrailingZeroCount(value); /// /// Index of the lowest set bit of a double word, like the bsf instruction. /// /// The value to scan. /// The bit index (0-31) of the lowest set bit. public uint BitScanForward32(uint value) => (uint)BitOperations.TrailingZeroCount(value); /// /// Index of the highest set bit of a word, like the bsr instruction. /// /// The value to scan. /// The bit index (0-15) of the highest set bit. public ushort BitScanReverse16(ushort value) => (ushort)BitOperations.Log2(value); /// /// Index of the highest set bit of a double word, like the bsr instruction. /// /// The value to scan. /// The bit index (0-31) of the highest set bit. public uint BitScanReverse32(uint value) => (uint)BitOperations.Log2(value); /// /// Checks that a 16-bit signed index lies within [lower, upper], like the bound instruction. /// /// The index is outside the bounds. public void CheckBound(short index, short lower, short upper) { if (index < lower || index > upper) { throw new CpuBoundRangeExceededException( $"BOUND check failed: index={index}, lower={lower}, upper={upper}."); } } /// /// Checks that a 32-bit signed index lies within [lower, upper], like the bound instruction. /// /// The index is outside the bounds. public void CheckBound(int index, int lower, int upper) { if (index < lower || index > upper) { throw new CpuBoundRangeExceededException( $"BOUND check failed: index={index}, lower={lower}, upper={upper}."); } } /// /// Halt the program. /// /// An that exits the program. /// HLT is attempted outside CPL 0. public Action Hlt() { PrivilegeChecks.EnsureCpl0(State, "HLT"); return () => { Exit(); }; } /// /// Exit the program. /// /// The exception throw in order to exit the program. protected void Exit() { _loggerService.LogTrace("Program requested exit. Terminating now"); throw new HaltRequestedException(); } /// C# code that called NearCall, FarCall or InterruptCall and waits for /// the chain to come back to the address that call expects to return to. private sealed class CSharpCallChainCaller : IOverrideChainCaller { private readonly CSharpOverrideHelper _helper; private readonly SegmentedAddress _expectedReturn; private readonly uint _expectedStackAddress; private readonly SegmentedAddress[] _redirectedReturns; /// Creates the caller waiting for a call that expects to return to /// , started with the stack at . /// Helper that executed the call. /// Address the call expects to return to. /// Stack address before the call. /// Other addresses the call accepts as its return. public CSharpCallChainCaller(CSharpOverrideHelper helper, SegmentedAddress expectedReturn, uint expectedStackAddress, SegmentedAddress[] redirectedReturns) { _helper = helper; _expectedReturn = expectedReturn; _expectedStackAddress = expectedStackAddress; _redirectedReturns = redirectedReturns; } /// True when the chain ended at a redirected return address instead of the expected one. public bool EndedAtRedirectedReturn { get; private set; } /// A landed address is an accepted redirected return of a call when it is listed in /// and the stack is back at or above its level before the /// call's pushes (at or above so ret n, which pops more than the frame, also counts). /// The runtime check is looser than discovery: discovery requires an exact stack match to /// record a redirected return, but generated code reads the stack pointer from the CPU state /// at landing time, so continuing at a listed address with a higher stack pointer does what /// the interpreter does. The address itself is always one discovery observed with an exact /// stack match. public static bool IsRedirectedReturn(SegmentedAddress[] redirectedReturns, SegmentedAddress landedAddress, uint stackPhysicalAddress, uint expectedStackAddress) => stackPhysicalAddress >= expectedStackAddress && redirectedReturns.Contains(landedAddress); /// public SegmentedAddress? ExpectedReturnAddress => _expectedReturn; /// public bool ContinuesAtExpectedReturn => true; /// public bool AcceptsRedirectedReturn(SegmentedAddress landedAddress, uint stackPhysicalAddress) { bool accepted = IsRedirectedReturn(_redirectedReturns, landedAddress, stackPhysicalAddress, _expectedStackAddress); EndedAtRedirectedReturn |= accepted; return accepted; } /// public bool RunOverride(FunctionInformation function, Func functionOverride) { SegmentedAddress actualReturn = _helper.State.IpSegmentedAddress; uint actualStackAddress = _helper.State.StackPhysicalAddress; if (actualStackAddress < _expectedStackAddress) { if (_helper._loggerService.IsEnabled(LogLevel.Debug)) { _helper._loggerService.LogDebug( "The call expecting to return to {ExpectedReturn} continued at {ActualReturn} while the callee's frame was still on the stack (stack {ActualStackAddress}, before the call {ExpectedStackAddress}). Running {FunctionName} inside the call.", _expectedReturn, actualReturn, actualStackAddress, _expectedStackAddress, function.Name); } } else { _helper.LogNestedOverrideCall(_expectedReturn, actualReturn, _expectedStackAddress, actualStackAddress, function.Name); } // A consumed unwind leaves CS:IP at an accepted return address, so the next step of the chain ends it. _helper.ExecuteCallConsumingUnwindTo(functionOverride, () => functionOverride.Invoke(0).Invoke(), _expectedReturn, _expectedStackAddress, _redirectedReturns); return false; } /// Runs an armed landing inside the call, with the same nesting logging /// performs. /// The observed landing control reached. public void RunLanding(CallLanding landing) { SegmentedAddress actualReturn = _helper.State.IpSegmentedAddress; uint actualStackAddress = _helper.State.StackPhysicalAddress; string? functionName = landing.Entry.Method.Name; if (actualStackAddress < _expectedStackAddress) { if (_helper._loggerService.IsEnabled(LogLevel.Debug)) { _helper._loggerService.LogDebug( "The call expecting to return to {ExpectedReturn} continued at {ActualReturn} while the callee's frame was still on the stack (stack {ActualStackAddress}, before the call {ExpectedStackAddress}). Running {FunctionName} inside the call.", _expectedReturn, actualReturn, actualStackAddress, _expectedStackAddress, functionName); } } else { _helper.LogNestedOverrideCall(_expectedReturn, actualReturn, _expectedStackAddress, actualStackAddress, functionName); } _helper.ExecuteCallConsumingUnwindTo(landing.Entry, () => landing.Entry.Invoke(0).Invoke(), _expectedReturn, _expectedStackAddress, _redirectedReturns); } /// public void OnMachineStopped() { _helper.Exit(); } } }