[NTVDM]: Implement and export VDDTerminateVDM.
[reactos.git] / subsystems / ntvdm / emulator.c
index 2d09c58..49a52fb 100644 (file)
@@ -8,33 +8,68 @@
 
 /* INCLUDES *******************************************************************/
 
-#include "ntvdm.h"
-#include <softx86/softx86.h>
-#include <softx86/softx87.h>
+#define NDEBUG
 
-softx86_ctx EmulatorContext;
-softx87_ctx FpuEmulatorContext;
+#include "emulator.h"
+#include "bios.h"
+#include "bop.h"
+#include "vddsup.h"
+#include "io.h"
+#include "registers.h"
+#include "vga.h"
+#include "pic.h"
 
-static VOID EmulatorReadMemory(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+// HACK
+typedef INT VDM_MODE;
+
+/* PRIVATE VARIABLES **********************************************************/
+
+FAST486_STATE EmulatorContext;
+
+static BOOLEAN A20Line = FALSE;
+
+/* BOP Identifiers */
+#define BOP_DEBUGGER    0x56    // Break into the debugger from a 16-bit app
+
+/* PRIVATE FUNCTIONS **********************************************************/
+
+VOID WINAPI EmulatorReadMemory(PFAST486_STATE State, ULONG Address, PVOID Buffer, ULONG Size)
 {
+    UNREFERENCED_PARAMETER(State);
+
+    /* If the A20 line is disabled, mask bit 20 */
+    if (!A20Line) Address &= ~(1 << 20);
+
     /* Make sure the requested address is valid */
     if ((Address + Size) >= MAX_ADDRESS) return;
 
-    /* Are we reading some of the console video memory? */
-    if (((Address + Size) >= CONSOLE_VIDEO_MEM_START)
-        && (Address < CONSOLE_VIDEO_MEM_END))
+    /*
+     * Check if we are going to read the VGA memory and
+     * copy it into the virtual address space if needed.
+     */
+    if (((Address + Size) >= VgaGetVideoBaseAddress())
+        && (Address < VgaGetVideoLimitAddress()))
     {
-        /* Call the VDM BIOS to update the video memory */
-        BiosUpdateConsole(max(Address, CONSOLE_VIDEO_MEM_START),
-                          min(Address + Size, CONSOLE_VIDEO_MEM_END));
+        DWORD VgaAddress = max(Address, VgaGetVideoBaseAddress());
+        DWORD ActualSize = min(Address + Size - 1, VgaGetVideoLimitAddress())
+                           - VgaAddress + 1;
+        LPBYTE DestBuffer = (LPBYTE)((ULONG_PTR)BaseAddress + VgaAddress);
+
+        /* Read from the VGA memory */
+        VgaReadMemory(VgaAddress, DestBuffer, ActualSize);
     }
 
     /* Read the data from the virtual address space and store it in the buffer */
     RtlCopyMemory(Buffer, (LPVOID)((ULONG_PTR)BaseAddress + Address), Size);
 }
 
-static VOID EmulatorWriteMemory(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+VOID WINAPI EmulatorWriteMemory(PFAST486_STATE State, ULONG Address, PVOID Buffer, ULONG Size)
 {
+    UNREFERENCED_PARAMETER(State);
+
+    /* If the A20 line is disabled, mask bit 20 */
+    if (!A20Line) Address &= ~(1 << 20);
+
     /* Make sure the requested address is valid */
     if ((Address + Size) >= MAX_ADDRESS) return;
 
@@ -44,267 +79,176 @@ static VOID EmulatorWriteMemory(PVOID Context, UINT Address, LPBYTE Buffer, INT
     /* Read the data from the buffer and store it in the virtual address space */
     RtlCopyMemory((LPVOID)((ULONG_PTR)BaseAddress + Address), Buffer, Size);
 
-    /* Check if we modified the console video memory */
-    if (((Address + Size) >= CONSOLE_VIDEO_MEM_START)
-        && (Address < CONSOLE_VIDEO_MEM_END))
+    /*
+     * Check if we modified the VGA memory.
+     */
+    if (((Address + Size) >= VgaGetVideoBaseAddress())
+        && (Address < VgaGetVideoLimitAddress()))
     {
-        /* Call the VDM BIOS to update the screen */
-        BiosUpdateConsole(max(Address, CONSOLE_VIDEO_MEM_START),
-                          min(Address + Size, CONSOLE_VIDEO_MEM_END));
-    }
-}
+        DWORD VgaAddress = max(Address, VgaGetVideoBaseAddress());
+        DWORD ActualSize = min(Address + Size - 1, VgaGetVideoLimitAddress())
+                           - VgaAddress + 1;
+        LPBYTE SrcBuffer = (LPBYTE)((ULONG_PTR)BaseAddress + VgaAddress);
 
-static VOID EmulatorReadIo(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
-{
-    switch (Address)
-    {
-        case PIC_MASTER_CMD:
-        case PIC_SLAVE_CMD:
-        {
-            *Buffer = PicReadCommand(Address);
-            break;
-        }
-
-        case PIC_MASTER_DATA:
-        case PIC_SLAVE_DATA:
-        {
-            *Buffer = PicReadData(Address);
-            break;
-        }
+        /* Write to the VGA memory */
+        VgaWriteMemory(VgaAddress, SrcBuffer, ActualSize);
     }
 }
 
-static VOID EmulatorWriteIo(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+UCHAR WINAPI EmulatorIntAcknowledge(PFAST486_STATE State)
 {
-    BYTE Byte = *Buffer;
+    UNREFERENCED_PARAMETER(State);
 
-    switch (Address)
-    {
-        case PIT_COMMAND_PORT:
-        {
-            PitWriteCommand(Byte);
-            break;
-        }
-
-        case PIT_DATA_PORT(0):
-        case PIT_DATA_PORT(1):
-        case PIT_DATA_PORT(2):
-        {
-            PitWriteData(Address - PIT_DATA_PORT(0), Byte);
-            break;
-        }
-
-        case PIC_MASTER_CMD:
-        case PIC_SLAVE_CMD:
-        {
-            PicWriteCommand(Address, Byte);
-            break;
-        }
-
-        case PIC_MASTER_DATA:
-        case PIC_SLAVE_DATA:
-        {
-            PicWriteData(Address, Byte);
-            break;
-        }
-    }
+    /* Get the interrupt number from the PIC */
+    return PicGetInterrupt();
 }
 
-static VOID EmulatorSoftwareInt(PVOID Context, BYTE Number)
+VOID WINAPI EmulatorDebugBreak(LPWORD Stack)
 {
-    WORD StackSegment, StackPointer, CodeSegment, InstructionPointer;
-    BYTE IntNum;
-
-    /* Check if this is the special interrupt */
-    if (Number == SPECIAL_INT_NUM)
-    {
-        /* Get the SS:SP */
-        StackSegment = EmulatorContext.state->segment_reg[SX86_SREG_SS].val;
-        StackPointer = EmulatorContext.state->general_reg[SX86_REG_SP].val;
-
-        /* Get the interrupt number */
-        IntNum = *(LPBYTE)((ULONG_PTR)BaseAddress + TO_LINEAR(StackSegment, StackPointer));
-
-        /* Move the stack pointer forward one word to skip the interrupt number */
-        StackPointer += sizeof(WORD);
-
-        /* Get the CS:IP */
-        InstructionPointer = *(LPWORD)((ULONG_PTR)BaseAddress
-                             + TO_LINEAR(StackSegment, StackPointer));
-        CodeSegment = *(LPWORD)((ULONG_PTR)BaseAddress
-                      + TO_LINEAR(StackSegment, StackPointer + sizeof(WORD)));
-
-        /* Check if this was an exception */
-        if (IntNum < 8)
-        {
-            /* Display a message to the user */
-            DisplayMessage(L"Exception: %s occured at %04X:%04X",
-                           ExceptionName[IntNum],
-                           CodeSegment,
-                           InstructionPointer);
-
-            /* Stop the VDM */
-            VdmRunning = FALSE;
-            return;
-        }
-
-        /* Check if this was an PIC IRQ */
-        if (IntNum >= BIOS_PIC_MASTER_INT && IntNum < BIOS_PIC_MASTER_INT + 8)
-        {
-            /* It was an IRQ from the master PIC */
-            BiosHandleIrq(IntNum - BIOS_PIC_MASTER_INT);
-        }
-        else if (IntNum >= BIOS_PIC_SLAVE_INT && IntNum < BIOS_PIC_SLAVE_INT + 8)
-        {
-            /* It was an IRQ from the slave PIC */
-            BiosHandleIrq(IntNum - BIOS_PIC_SLAVE_INT + 8);
-        }
-
-        switch (IntNum)
-        {
-            case VIDEO_BIOS_INTERRUPT:
-            {
-                /* This is the video BIOS interrupt, call the BIOS */
-                BiosVideoService();
-                break;
-            }
-            case 0x20:
-            {
-                DosInt20h(CodeSegment);
-                break;
-            }
-            case 0x21:
-            {
-                DosInt21h(CodeSegment);
-                break;
-            }
-            case 0x23:
-            {
-                DosBreakInterrupt();
-                break;
-            }
-        }
-    }
+    DPRINT1("NTVDM: BOP_DEBUGGER\n");
+    DebugBreak();
 }
 
 /* PUBLIC FUNCTIONS ***********************************************************/
 
-BOOLEAN EmulatorInitialize()
+BOOLEAN EmulatorInitialize(VOID)
 {
     /* Allocate memory for the 16-bit address space */
-    BaseAddress = HeapAlloc(GetProcessHeap(), 0, MAX_ADDRESS);
+    BaseAddress = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_ADDRESS);
     if (BaseAddress == NULL) return FALSE;
 
-    /* Initialize the softx86 CPU emulator */
-    if (!softx86_init(&EmulatorContext, SX86_CPULEVEL_80186))
-    {
-        HeapFree(GetProcessHeap(), 0, BaseAddress);
-        return FALSE;
-    }
-
-    /* Initialize the softx87 FPU emulator*/
-    if(!softx87_init(&FpuEmulatorContext, SX87_FPULEVEL_8087))
-    {
-        softx86_free(&EmulatorContext);
-        HeapFree(GetProcessHeap(), 0, BaseAddress);
-        return FALSE;
-    }
-
-    /* Set memory read/write callbacks */
-    EmulatorContext.callbacks->on_read_memory = EmulatorReadMemory;
-    EmulatorContext.callbacks->on_write_memory = EmulatorWriteMemory;
+    /* Initialize the CPU */
+    Fast486Initialize(&EmulatorContext,
+                      EmulatorReadMemory,
+                      EmulatorWriteMemory,
+                      EmulatorReadIo,
+                      EmulatorWriteIo,
+                      NULL,
+                      EmulatorBiosOperation,
+                      EmulatorIntAcknowledge,
+                      NULL /* TODO: Use a TLB */);
 
-    /* Set MMIO read/write callbacks */
-    EmulatorContext.callbacks->on_read_io = EmulatorReadIo;
-    EmulatorContext.callbacks->on_write_io = EmulatorWriteIo;
+    /* Enable interrupts */
+    setIF(1);
 
-    /* Set interrupt callbacks */
-    EmulatorContext.callbacks->on_sw_int = EmulatorSoftwareInt;
+    /* Initialize VDD support */
+    VDDSupInitialize();
 
-    /* Connect the emulated FPU to the emulated CPU */
-    softx87_connect_to_CPU(&EmulatorContext, &FpuEmulatorContext);
+    /* Register the DebugBreak BOP */
+    RegisterBop(BOP_DEBUGGER, EmulatorDebugBreak);
 
     return TRUE;
 }
 
-VOID EmulatorSetStack(WORD Segment, WORD Offset)
+VOID EmulatorCleanup(VOID)
 {
-    /* Call the softx86 API */
-    softx86_set_stack_ptr(&EmulatorContext, Segment, Offset);
+    /* Free the memory allocated for the 16-bit address space */
+    if (BaseAddress != NULL) HeapFree(GetProcessHeap(), 0, BaseAddress);
 }
 
+// FIXME: This function assumes 16-bit mode!!!
 VOID EmulatorExecute(WORD Segment, WORD Offset)
 {
-    /* Call the softx86 API */
-    softx86_set_instruction_ptr(&EmulatorContext, Segment, Offset);
+    /* Tell Fast486 to move the instruction pointer */
+    Fast486ExecuteAt(&EmulatorContext, Segment, Offset);
 }
 
 VOID EmulatorInterrupt(BYTE Number)
 {
-    LPDWORD IntVecTable = (LPDWORD)((ULONG_PTR)BaseAddress);
-    UINT Segment, Offset;
-
-    /* Get the segment and offset */
-    Segment = HIWORD(IntVecTable[Number]);
-    Offset = LOWORD(IntVecTable[Number]);
+    /* Call the Fast486 API */
+    Fast486Interrupt(&EmulatorContext, Number);
+}
 
-    /* Call the softx86 API */
-    softx86_make_simple_interrupt_call(&EmulatorContext, &Segment, &Offset);
+VOID EmulatorInterruptSignal(VOID)
+{
+    /* Call the Fast486 API */
+    Fast486InterruptSignal(&EmulatorContext);
 }
 
-ULONG EmulatorGetRegister(ULONG Register)
+VOID EmulatorStep(VOID)
 {
-    if (Register < EMULATOR_REG_CS)
-    {
-        return EmulatorContext.state->general_reg[Register].val;
-    }
-    else
-    {
-        return EmulatorContext.state->segment_reg[(Register >> 3) - 1].val;
-    }
+    /* Dump the state for debugging purposes */
+    // Fast486DumpState(&EmulatorContext);
+
+    /* Execute the next instruction */
+    Fast486StepInto(&EmulatorContext);
 }
 
-VOID EmulatorSetRegister(ULONG Register, ULONG Value)
+VOID EmulatorSetA20(BOOLEAN Enabled)
 {
-    if (Register < EMULATOR_REG_CS)
-    {
-        EmulatorContext.state->general_reg[Register].val = Value;
-    }
-    else
-    {
-        EmulatorContext.state->segment_reg[(Register >> 3) - 1].val = Value;
-    }
+    A20Line = Enabled;
 }
 
-BOOLEAN EmulatorGetFlag(ULONG Flag)
+
+
+VOID
+WINAPI
+VDDTerminateVDM(VOID)
 {
-    return (EmulatorContext.state->reg_flags.val & Flag);
+    /* Stop the VDM */
+    VdmRunning = FALSE;
 }
 
-VOID EmulatorSetFlag(ULONG Flag)
+PBYTE
+WINAPI
+Sim32pGetVDMPointer(IN ULONG   Address,
+                    IN BOOLEAN ProtectedMode)
 {
-    EmulatorContext.state->reg_flags.val |= Flag;
+    // FIXME
+    UNREFERENCED_PARAMETER(ProtectedMode);
+
+    /*
+     * HIWORD(Address) == Segment  (if ProtectedMode == FALSE)
+     *                 or Selector (if ProtectedMode == TRUE )
+     * LOWORD(Address) == Offset
+     */
+    return (PBYTE)FAR_POINTER(Address);
 }
 
-VOID EmulatorClearFlag(ULONG Flag)
+PBYTE
+WINAPI
+MGetVdmPointer(IN ULONG   Address,
+               IN ULONG   Size,
+               IN BOOLEAN ProtectedMode)
 {
-    EmulatorContext.state->reg_flags.val &= ~Flag;
+    UNREFERENCED_PARAMETER(Size);
+    return Sim32pGetVDMPointer(Address, ProtectedMode);
 }
 
-VOID EmulatorStep()
+PVOID
+WINAPI
+VdmMapFlat(IN USHORT   Segment,
+           IN ULONG    Offset,
+           IN VDM_MODE Mode)
 {
-    /* Call the softx86 API */
-    softx86_step(&EmulatorContext);
+    // FIXME
+    UNREFERENCED_PARAMETER(Mode);
+
+    return SEG_OFF_TO_PTR(Segment, Offset);
 }
 
-VOID EmulatorCleanup()
+BOOL 
+WINAPI
+VdmFlushCache(IN USHORT   Segment,
+              IN ULONG    Offset,
+              IN ULONG    Size,
+              IN VDM_MODE Mode)
 {
-    /* Free the memory allocated for the 16-bit address space */
-    if (BaseAddress != NULL) HeapFree(GetProcessHeap(), 0, BaseAddress);
+    // FIXME
+    UNIMPLEMENTED;
+    return TRUE;
+}
 
-    /* Free the softx86 CPU and FPU emulator */
-    softx86_free(&EmulatorContext);
-    softx87_free(&FpuEmulatorContext);
+BOOL
+WINAPI
+VdmUnmapFlat(IN USHORT   Segment,
+             IN ULONG    Offset,
+             IN PVOID    Buffer,
+             IN VDM_MODE Mode)
+{
+    // FIXME
+    UNIMPLEMENTED;
+    return TRUE;
 }
 
 /* EOF */