namespace Spice86.Core.Emulator.CPU;
using Spice86.Core.Emulator.CPU.Exceptions;
using Spice86.Core.Emulator.CPU.DescriptorTables;
using Spice86.Core.Emulator.CPU.Registers;
using Spice86.Core.Emulator.Memory;
using Spice86.Core.Emulator.Memory.Mmu;
using Spice86.Shared.Emulator.Memory;
using System.Runtime.CompilerServices;
using System.Text;
///
/// Represents the stack of the CPU.
/// In the x86 architecture, the stack grows downwards, meaning it grows from higher memory addresses to lower memory addresses.
///
/// Visualization:
///
/// Higher Memory Addresses
/// +-------------------+
/// | |
/// | |
/// | Stack Data |
/// | |
/// | |
/// +-------------------+ < Stack Pointer (SP)
/// | |
/// | Free Space |
/// | |
/// | |
/// +-------------------+
/// Lower Memory Addresses
///
///
/// SP vs ESP: the address computation uses SS:ESP (32-bit) when the SS descriptor's D/B bit is
/// set, and SS:SP (16-bit, matching real mode) otherwise - is the single
/// point that decides this for every method below. Note that the operand size (16-bit vs 32-bit values
/// pushed or popped) is entirely independent of the address size: and
/// correctly store 32-bit values regardless of which stack address width is active.
///
///
public class Stack {
/// Size in bytes of the frame a real-mode interrupt pushes (FLAGS, CS, IP).
public const int InterruptFrameSize = 6;
/// Byte offset of the pushed FLAGS word inside an interrupt frame, from the stack top.
public const int InterruptFrameFlagsOffset = 4;
private readonly IMemory _memory;
private readonly State _state;
///
/// Creates a new instance of the class
///
/// The memory bus.
/// The CPU Registers and Flags.
public Stack(IMemory memory, State state) {
this._memory = memory;
this._state = state;
}
/// Whether SS's descriptor has the D/B bit set, making ESP (not SP) the authoritative stack address.
private bool StackAddressIs32Bit => _state.SegmentDescriptorCaches[SegmentRegisterIndex.SsIndex].DefaultBig;
///
/// The authoritative stack pointer: when SS is a 32-bit-default segment,
/// (zero-extended) otherwise. Every push/pop/peek/poke method below reads and
/// writes through this single property so the SP/ESP choice is made in exactly one place.
///
private uint StackPointer {
get => StackAddressIs32Bit ? _state.ESP : _state.SP;
set {
if (StackAddressIs32Bit) {
_state.ESP = value;
} else {
_state.SP = (ushort)value;
}
}
}
///
/// Gets the active stack pointer for the current SS descriptor width.
///
public uint GetStackPointer() {
return StackPointer;
}
///
/// Updates the active stack pointer using the current SS descriptor width.
///
public void SetStackPointer(uint value) {
StackPointer = value;
}
///
/// Wraps an address computation to the current stack address width: full 32-bit range when SS is
/// 32-bit-default, or 16-bit (matching real hardware SP register wraparound) otherwise.
///
private uint MaskAddress(uint value) => StackAddressIs32Bit ? value : (ushort)value;
///
/// Computes + , wrapped to the current stack
/// address width. may be negative.
///
private uint OffsetStackPointer(int delta) => MaskAddress(unchecked((uint)((int)StackPointer + delta)));
///
/// Peeks a 8 bit value from the stack
///
/// The offset from the stack top
/// The value in memory.
public byte Peek8(int index) {
uint offset = OffsetStackPointer(index);
return _memory.UInt8[_state.SS, offset, SegmentAccessKind.Stack];
}
///
/// Peeks a 16 bit value from the stack
///
/// The offset from the stack top
/// The value in memory.
public ushort Peek16(int index) {
uint offset = OffsetStackPointer(index);
return _memory.UInt16[_state.SS, offset, SegmentAccessKind.Stack];
}
///
/// Pokes a 16 bit value on the stack
///
/// The offset from the stack top
/// The value to store in memory.
public void Poke16(int index, ushort value) {
uint offset = OffsetStackPointer(index);
_memory.UInt16[_state.SS, offset, SegmentAccessKind.Stack] = value;
}
///
/// Pops a 16 bit value from the stack
///
/// The value retrieved from the stack, therefore read from memory
public ushort Pop16() {
ushort res = _memory.UInt16[_state.SS, StackPointer, SegmentAccessKind.Stack];
StackPointer = OffsetStackPointer(2);
return res;
}
///
/// Pushes a 16 bit value on the stack
///
/// The value pushed onto the stack, therefore stored in memory.
public void Push16(ushort value) {
uint newSp = OffsetStackPointer(-2);
_memory.UInt16[_state.SS, newSp, SegmentAccessKind.Stack] = value;
StackPointer = newSp;
}
///
/// Peeks a 32 bit value from the stack
///
/// The offset from the stack top
public uint Peek32(int index) {
uint offset = OffsetStackPointer(index);
return _memory.UInt32[_state.SS, offset, SegmentAccessKind.Stack];
}
///
/// Pokes a 32 bit value on the stack
///
/// The offset from the stack top
/// The value to store in memory.
public void Poke32(int index, uint value) {
uint offset = OffsetStackPointer(index);
_memory.UInt32[_state.SS, offset, SegmentAccessKind.Stack] = value;
}
///
/// Pops a 32 bit value from the stack
///
/// The value popped from the stack.
public uint Pop32() {
uint res = _memory.UInt32[_state.SS, StackPointer, SegmentAccessKind.Stack];
StackPointer = OffsetStackPointer(4);
return res;
}
/// Pops and loads a segment selector, leaving the stack unchanged if the load faults.
public void PopSegmentRegister(uint segmentRegisterIndex, int slotSizeBytes) {
bool stackAddressIs32Bit = StackAddressIs32Bit;
uint nextPointer = OffsetStackPointer(slotSizeBytes);
ushort selector = Peek16(0);
SegmentAndControlRegisterOperations.LoadSegmentRegister(_state, _memory, segmentRegisterIndex, selector);
if (stackAddressIs32Bit) {
_state.ESP = nextPointer;
} else {
_state.SP = (ushort)nextPointer;
}
}
///
/// Performs LEAVE: releases the current stack frame by setting the stack pointer to the frame
/// pointer's value, then popping the caller's saved frame pointer back off the stack.
/// Two independent axes control this instruction:
/// - The ADDRESS used to locate the saved frame pointer (and the resulting new stack pointer)
/// follows the stack's own address width (SS's D/B bit via ):
/// EBP/ESP when the stack is 32-bit-default, BP/SP otherwise - resolved fresh every call since SS
/// can differ between calls to the same code address.
/// - The VALUE popped back into the frame-pointer register, and the WIDTH of that register write,
/// follow the instruction's operand size (, safe to fix at parse
/// time since it comes from CS): a 16-bit-operand LEAVE only ever writes BP (leaving EBP's upper
/// half untouched), even when the stack itself is 32-bit - matching a plain POP's semantics.
/// The saved frame pointer is read before the stack pointer is committed, so a fault reading it
/// leaves the stack pointer unchanged (matching real-80386 fault atomicity).
///
public void Leave(bool operandSize32) {
uint frameAddress = StackAddressIs32Bit ? _state.EBP : _state.BP;
uint poppedValue = ReadFrameValue(frameAddress, operandSize32);
int pointerSize = operandSize32 ? 4 : 2;
StackPointer = MaskAddress(frameAddress + (uint)pointerSize);
if (operandSize32) {
_state.EBP = poppedValue;
} else {
_state.BP = (ushort)poppedValue;
}
}
/// Performs LEAVE with a 16-bit operand and the active stack address width.
public void Leave16() => Leave(false);
/// Performs LEAVE with a 32-bit operand and the active stack address width.
public void Leave32() => Leave(true);
///
/// Pushes a 32 bit value on the stack
///
/// The value to store onto the stack.
public void Push32(uint value) {
uint newSp = OffsetStackPointer(-4);
_memory.UInt32[_state.SS, newSp, SegmentAccessKind.Stack] = value;
StackPointer = newSp;
}
///
/// Pre-validates that all slots for a multi-register push (PUSHA/PUSHAD) are accessible.
/// Checks each slot going downward from the current stack pointer. Raises #SS if any slot crosses
/// the segment limit. No state is modified if the check fails.
///
/// Size of each value in bytes (2 for 16-bit, 4 for 32-bit).
/// Number of values to push.
public void ValidateStackPushRange(ushort valueSizeBytes, ushort valueCount) {
uint offset = StackPointer;
for (ushort i = 0; i < valueCount; i++) {
offset = MaskAddress(offset - valueSizeBytes);
_memory.Mmu.CheckAccess(_state.SS, offset, valueSizeBytes, SegmentAccessKind.Stack, isWrite: true);
}
}
///
/// Pre-validates that all slots for a multi-register pop (POPA/POPAD) are accessible.
/// Checks each slot going upward from the current stack pointer. Raises #SS if any slot crosses the
/// segment limit. No state is modified if the check fails.
///
/// Size of each value in bytes (2 for 16-bit, 4 for 32-bit).
/// Number of values to pop.
public void ValidateStackPopRange(ushort valueSizeBytes, ushort valueCount) {
uint offset = StackPointer;
for (ushort i = 0; i < valueCount; i++) {
_memory.Mmu.CheckAccess(_state.SS, offset, valueSizeBytes, SegmentAccessKind.Stack, isWrite: false);
offset = MaskAddress(offset + valueSizeBytes);
}
}
///
/// Pushes all 8 general-purpose 16-bit registers (PUSHA order: AX, CX, DX, BX, SP, BP, SI, DI).
/// The range is validated up front, all eight slots are written, and the #SS (if any slot crossed
/// the segment limit) is raised only afterwards - matching real-80386 PUSHAD, which stores every
/// register before reporting the fault.
///
public void PushAll16(ushort ax, ushort cx, ushort dx, ushort bx, ushort sp, ushort bp, ushort si, ushort di) {
CpuStackSegmentFaultException? pendingFault = GetStackPushRangeFault(2, 8);
uint offset = StackPointer;
offset = MaskAddress(offset - 2); _memory.WriteUInt16Segmented(_state.SS, offset, ax);
offset = MaskAddress(offset - 2); _memory.WriteUInt16Segmented(_state.SS, offset, cx);
offset = MaskAddress(offset - 2); _memory.WriteUInt16Segmented(_state.SS, offset, dx);
offset = MaskAddress(offset - 2); _memory.WriteUInt16Segmented(_state.SS, offset, bx);
offset = MaskAddress(offset - 2); _memory.WriteUInt16Segmented(_state.SS, offset, sp);
offset = MaskAddress(offset - 2); _memory.WriteUInt16Segmented(_state.SS, offset, bp);
offset = MaskAddress(offset - 2); _memory.WriteUInt16Segmented(_state.SS, offset, si);
offset = MaskAddress(offset - 2); _memory.WriteUInt16Segmented(_state.SS, offset, di);
if (pendingFault is not null) {
throw pendingFault;
}
StackPointer = offset;
}
///
/// Pushes all 8 general-purpose 32-bit registers (PUSHAD order: EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI).
/// The range is validated up front, all eight slots are written, and the #SS (if any slot crossed
/// the segment limit) is raised only afterwards - matching real-80386 PUSHAD, which stores every
/// register before reporting the fault.
///
public void PushAll32(uint eax, uint ecx, uint edx, uint ebx, uint esp, uint ebp, uint esi, uint edi) {
CpuStackSegmentFaultException? pendingFault = GetStackPushRangeFault(4, 8);
uint offset = StackPointer;
offset = MaskAddress(offset - 4); _memory.WriteUInt32Segmented(_state.SS, offset, eax);
offset = MaskAddress(offset - 4); _memory.WriteUInt32Segmented(_state.SS, offset, ecx);
offset = MaskAddress(offset - 4); _memory.WriteUInt32Segmented(_state.SS, offset, edx);
offset = MaskAddress(offset - 4); _memory.WriteUInt32Segmented(_state.SS, offset, ebx);
offset = MaskAddress(offset - 4); _memory.WriteUInt32Segmented(_state.SS, offset, esp);
offset = MaskAddress(offset - 4); _memory.WriteUInt32Segmented(_state.SS, offset, ebp);
offset = MaskAddress(offset - 4); _memory.WriteUInt32Segmented(_state.SS, offset, esi);
offset = MaskAddress(offset - 4); _memory.WriteUInt32Segmented(_state.SS, offset, edi);
if (pendingFault is not null) {
throw pendingFault;
}
StackPointer = offset;
}
///
/// Walks the push slots going downward from the current stack pointer and captures the first #SS
/// any slot raises, without throwing. Returns null when the whole range is accessible so the caller
/// can complete its writes before re-raising the captured fault (deferred-fault PUSHAD semantics).
///
/// Size of each value in bytes (2 for 16-bit, 4 for 32-bit).
/// Number of values to push.
/// The first stack-segment fault encountered, or null if all slots are valid.
private CpuStackSegmentFaultException? GetStackPushRangeFault(ushort valueSizeBytes, ushort valueCount) {
uint offset = StackPointer;
for (ushort i = 0; i < valueCount; i++) {
offset = MaskAddress(offset - valueSizeBytes);
try {
_memory.Mmu.CheckAccess(_state.SS, offset, valueSizeBytes, SegmentAccessKind.Stack, isWrite: true);
} catch (CpuStackSegmentFaultException exception) {
return exception;
}
}
return null;
}
///
/// Pops all 8 general-purpose 16-bit registers (POPA order: DI, SI, BP, skip SP, BX, DX, CX, AX).
/// Each slot is read individually; if a slot raises #SS, earlier register assignments persist
/// while the stack pointer is left at its original value (matches 80386 partial-pop fault semantics).
///
public void PopAll16() {
uint offset = StackPointer;
_state.DI = _memory.UInt16[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 2);
_state.SI = _memory.UInt16[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 2);
_state.BP = _memory.UInt16[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 2);
_memory.Mmu.CheckAccess(_state.SS, offset, 2, SegmentAccessKind.Stack, isWrite: false); offset = MaskAddress(offset + 2); // skip SP slot
_state.BX = _memory.UInt16[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 2);
_state.DX = _memory.UInt16[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 2);
_state.CX = _memory.UInt16[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 2);
_state.AX = _memory.UInt16[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 2);
StackPointer = offset;
}
///
/// Pops all 8 general-purpose 32-bit registers (POPAD order: EDI, ESI, EBP, skip ESP, EBX, EDX, ECX, EAX).
/// Each slot is read individually; if a slot raises #SS, earlier register assignments persist
/// while the stack pointer is left at its original value (matches 80386 partial-pop fault semantics).
/// The ESP slot is never loaded into ESP; the stack pointer just advances past all 8 slots. On a
/// 16-bit stack only SP is addressed, and the upper half of ESP is left holding the discarded slot's
/// upper half; on a 32-bit stack ESP becomes the full new value.
///
public void PopAll32() {
uint offset = StackPointer;
_state.EDI = _memory.UInt32[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 4);
_state.ESI = _memory.UInt32[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 4);
_state.EBP = _memory.UInt32[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 4);
uint discardedEspSlot = _memory.UInt32[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 4);
_state.EBX = _memory.UInt32[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 4);
_state.EDX = _memory.UInt32[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 4);
_state.ECX = _memory.UInt32[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 4);
_state.EAX = _memory.UInt32[_state.SS, offset, SegmentAccessKind.Stack]; offset = MaskAddress(offset + 4);
if (StackAddressIs32Bit) {
_state.ESP = offset;
} else if (_state.CpuMode == CpuMode.Protected) {
_state.ESP = (_state.ESP & 0xFFFF0000u) | offset;
} else {
// Real-mode/V86 80386 POPAD preserves the discarded slot's upper half in ESP.
_state.ESP = (discardedEspSlot & 0xFFFF0000u) | offset;
}
}
///
/// Peeks a SegmentedAddress value from the stack
///
/// The offset from the stack top
/// The value in memory.
public SegmentedAddress PeekSegmentedAddress(int index) {
uint offset = OffsetStackPointer(index);
return _memory.SegmentedAddress16[_state.SS, offset, SegmentAccessKind.Stack];
}
///
/// Pokes a SegmentedAddress value on the stack
///
/// The offset from the stack top
/// The value to store in memory.
public void PokeSegmentedAddress(int index, SegmentedAddress value) {
uint offset = OffsetStackPointer(index);
ValidateStackAccess(offset, 4);
_memory.UInt16[_state.SS, offset, SegmentAccessKind.Stack] = value.Offset;
_memory.UInt16[_state.SS, MaskAddress(offset + 2), SegmentAccessKind.Stack] = value.Segment;
}
///
/// Pops a SegmentedAddress value from the stack
///
/// The value retrieved from the stack, therefore read from memory
public SegmentedAddress PopSegmentedAddress() {
ushort offset = Peek16(0);
ushort segment = Peek16(2);
StackPointer = OffsetStackPointer(4);
return new SegmentedAddress(segment, offset);
}
///
/// Pops a SegmentedAddress32 value from the stack.
/// The indexer performs two separate 4-byte MMU checks matching hardware's per-pop semantics.
///
/// The value retrieved from the stack, therefore read from memory
public SegmentedAddress32 PopSegmentedAddress32() {
SegmentedAddress32 res = _memory.SegmentedAddress32[_state.SS, StackPointer, SegmentAccessKind.Stack];
StackPointer = OffsetStackPointer(8);
return res;
}
///
/// Pops the padded 32-bit interrupt return pointer from the stack.
/// Reads 6 bytes for the return address then discards 2 bytes of padding.
///
public SegmentedAddress PopInterruptPointer32() {
return PopSegmentedAddress32().ToSegmentedAddress();
}
///
/// Pushes a SegmentedAddress value on the stack
///
/// The value pushed onto the stack, therefore stored in memory.
public void PushSegmentedAddress(SegmentedAddress value) {
uint newSp = OffsetStackPointer(-4);
ValidateStackAccess(newSp, 4);
_memory.UInt16[_state.SS, newSp, SegmentAccessKind.Stack] = value.Offset;
_memory.UInt16[_state.SS, MaskAddress(newSp + 2), SegmentAccessKind.Stack] = value.Segment;
StackPointer = newSp;
}
///
/// Pushes a 32-bit far pointer (4-byte offset and 2-byte segment) on the stack.
///
/// The 32-bit segmented address to push.
public void PushFarPointer32(SegmentedAddress32 value) {
uint newSp = OffsetStackPointer(-8);
ValidateStackAccess(newSp, 8);
_memory.UInt32[_state.SS, newSp, SegmentAccessKind.Stack] = value.Offset;
_memory.UInt16[_state.SS, MaskAddress(newSp + 4), SegmentAccessKind.Stack] = value.Segment;
_memory.UInt16[_state.SS, MaskAddress(newSp + 6), SegmentAccessKind.Stack] = 0;
StackPointer = newSp;
}
private void ValidateStackAccess(uint offset, uint accessSizeBytes) {
_memory.Mmu.CheckAccess(_state.SS, offset, accessSizeBytes, SegmentAccessKind.Stack, isWrite: true);
}
///
/// Pops a number of bytes from the stack (that is, increment the stack pointer), without returning any value
///
/// The number of bytes to pop. The Stack Pointer Register will be incremented by this value
public void Discard(int numberOfBytesToPop) {
StackPointer = OffsetStackPointer(numberOfBytesToPop);
}
///
/// Pushes a 16-bit interrupt frame (FLAGS, then CS, then IP) like a real-mode int.
/// Does not change the interrupt flag: the caller clears it as interrupt entry requires.
///
/// The CS:IP the frame returns to.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void PushInterruptFrame(SegmentedAddress returnAddress) {
Push16(_state.Flags.FlagRegister16);
Push16(returnAddress.Segment);
Push16(returnAddress.Offset);
}
///
/// Pops a 16-bit interrupt frame (IP, CS, then FLAGS) like iret. The caller assigns
/// the returned flags word to its flag register.
///
/// The return address and the FLAGS word the frame held.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public (SegmentedAddress ReturnAddress, ushort Flags) PopInterruptFrame() {
ushort ip = Pop16();
ushort cs = Pop16();
ushort flags = Pop16();
return (new SegmentedAddress(cs, ip), flags);
}
/// Reads the CS:IP return address of the interrupt frame on top of the stack.
public SegmentedAddress PeekInterruptFrameReturnAddress() => new(Peek16(2), Peek16(0));
/// Reads the pushed FLAGS word of the interrupt frame on top of the stack.
public ushort PeekInterruptFrameFlags() => Peek16(InterruptFrameFlagsOffset);
///
/// ENTER: creates a nested stack frame. Pushes the current frame pointer, then - for a nesting
/// level above 0 - copies -1 additional frame pointers from the enclosing
/// frames followed by the new frame pointer itself, before allocating
/// bytes of dynamic storage.
/// Two independent axes control this instruction, and must not be conflated:
/// - The stack's address width governs stack pointer and frame-chain address arithmetic.
/// - The operand size governs the pushed value width and whether BP or EBP is updated.
/// The stack pointer and frame-pointer register are committed only after the storage-allocation
/// validation succeeds, so a fault leaves both unchanged (matching real hardware's atomic fault semantics).
///
public void Enter(ushort storageSize, byte level, bool operandSize32) {
level = (byte)(level & 0x1F);
int pointerSize = operandSize32 ? 4 : 2;
uint oldBaseValue = operandSize32 ? _state.EBP : _state.BP;
uint newSp = OffsetStackPointer(-pointerSize);
WriteFrameValue(newSp, oldBaseValue, operandSize32);
// A 16-bit stack updates SP without changing the high half of ESP.
uint newFrameAddress = newSp;
if (!StackAddressIs32Bit) {
newFrameAddress = (_state.ESP & 0xFFFF0000u) | newSp;
}
uint sp = newSp;
if (level > 0) {
uint chainAddress = StackAddressIs32Bit ? _state.EBP : _state.BP;
for (int i = 1; i < level; i++) {
chainAddress = MaskAddress(chainAddress - (uint)pointerSize);
sp = OffsetStackPointerFrom(sp, -pointerSize);
WriteFrameValue(sp, ReadFrameValue(chainAddress, operandSize32), operandSize32);
}
sp = OffsetStackPointerFrom(sp, -pointerSize);
WriteFrameValue(sp, newFrameAddress, operandSize32);
}
// ENTER reserves storageSize bytes of dynamic storage without writing to it, but real hardware
// still validates that a write at the FINAL stack pointer (after this reservation) would
// succeed - raising the same #PF/#GP/#SS a later access there would, even though no data is
// actually stored at that address by ENTER itself.
uint finalSp = OffsetStackPointerFrom(sp, -storageSize);
_memory.Mmu.CheckAccess(_state.SS, finalSp, 1, SegmentAccessKind.Stack, isWrite: true);
_memory.Mmu.TranslateAddress(_state.SS, finalSp, isWrite: true);
StackPointer = finalSp;
if (operandSize32) {
_state.EBP = newFrameAddress;
} else {
_state.BP = (ushort)newFrameAddress;
}
}
///
/// Computes a stack pointer offset from an explicit base value (rather than the live
/// ), wrapped to the current stack address width.
///
private uint OffsetStackPointerFrom(uint baseValue, int delta) => MaskAddress(unchecked((uint)((int)baseValue + delta)));
private uint ReadFrameValue(uint offset, bool operandSize32) {
return operandSize32 ? _memory.UInt32[_state.SS, offset, SegmentAccessKind.Stack] : _memory.UInt16[_state.SS, offset, SegmentAccessKind.Stack];
}
private void WriteFrameValue(uint offset, uint value, bool operandSize32) {
if (operandSize32) {
_memory.UInt32[_state.SS, offset, SegmentAccessKind.Stack] = value;
} else {
_memory.UInt16[_state.SS, offset, SegmentAccessKind.Stack] = (ushort)value;
}
}
///
/// Sets the flag on the interrupt stack, which is at SS:SP+4
/// The interrupt stack is a special stack used to store the state of the processor when an interrupt occurs.
/// In Real Mode, the CPU pushes FLAGS, CS, and IP onto the interrupt stack.
///
/// The flag mask used to modify the uint value in memory
/// A boolean that determines whether the bits specified by the flagMask should be set (if true) or cleared (if false).
public void SetFlagOnInterruptStack(int flagMask, bool flagValue) {
int value = Peek16(InterruptFrameFlagsOffset);
if (flagValue) {
value |= flagMask;
} else {
value &= ~flagMask;
}
Poke16(InterruptFrameFlagsOffset, (ushort)value);
}
///
/// Returns a string representation of a window around the current stack address.
///
/// How many entries to show
/// A string detailing the addresses and values on the stack around the current stack pointer
public string PeekWindow(int range = 8) {
var sb = new StringBuilder();
ushort range16 = (ushort)(range << 1);
uint physicalAddress = _state.StackPhysicalAddress;
for (uint i = physicalAddress - range16; i < physicalAddress + range16; i += 2) {
if (i == physicalAddress) {
sb.Append('*');
}
sb.AppendLine($"[0x{i:X6}] 0x{_memory.UInt16[i]:X4}");
}
return sb.ToString();
}
}