* Sync up to trunk head (r64921).
[reactos.git] / subsystems / ntvdm / emulator.c
index 1c99b57..b8a43b6 100644 (file)
 #define NDEBUG
 
 #include "emulator.h"
-#include "bios.h"
-#include "dos.h"
-#include "vga.h"
-#include "pic.h"
-#include "ps2.h"
-#include "timer.h"
+
+#include "cpu/callback.h"
+#include "cpu/cpu.h"
+#include "cpu/bop.h"
+#include <isvbop.h>
+
+#include "int32.h"
+
+#include "clock.h"
+#include "bios/rom.h"
+#include "hardware/cmos.h"
+#include "hardware/keyboard.h"
+#include "hardware/mouse.h"
+#include "hardware/pic.h"
+#include "hardware/ps2.h"
+#include "hardware/speaker.h"
+#include "hardware/timer.h"
+#include "hardware/vga.h"
+
+#include "vddsup.h"
+#include "io.h"
 
 /* PRIVATE VARIABLES **********************************************************/
 
-#ifndef NEW_EMULATOR
-softx86_ctx EmulatorContext;
-softx87_ctx FpuEmulatorContext;
+LPVOID  BaseAddress = NULL;
+BOOLEAN VdmRunning  = TRUE;
+
+static BOOLEAN A20Line   = FALSE;
+static BYTE Port61hState = 0x00;
+
+static HANDLE InputThread = NULL;
+
+LPCWSTR ExceptionName[] =
+{
+    L"Division By Zero",
+    L"Debug",
+    L"Unexpected Error",
+    L"Breakpoint",
+    L"Integer Overflow",
+    L"Bound Range Exceeded",
+    L"Invalid Opcode",
+    L"FPU Not Available"
+};
+
+/* BOP Identifiers */
+#define BOP_DEBUGGER    0x56    // Break into the debugger from a 16-bit app
+
+/* PRIVATE FUNCTIONS **********************************************************/
+
+static inline VOID
+EmulatorMoveMemory(OUT VOID UNALIGNED *Destination,
+                   IN const VOID UNALIGNED *Source,
+                   IN SIZE_T Length)
+{
+#if 1
+    /*
+     * We use a switch here to detect small moves of memory, as these
+     * constitute the bulk of our moves.
+     * Using RtlMoveMemory for all these small moves would be slow otherwise.
+     */
+    switch (Length)
+    {
+        case 0:
+            return;
+
+        case sizeof(UCHAR):
+            *(PUCHAR)Destination = *(PUCHAR)Source;
+            return;
+
+        case sizeof(USHORT):
+            *(PUSHORT)Destination = *(PUSHORT)Source;
+            return;
+
+        case sizeof(ULONG):
+            *(PULONG)Destination = *(PULONG)Source;
+            return;
+
+        case sizeof(ULONGLONG):
+            *(PULONGLONG)Destination = *(PULONGLONG)Source;
+            return;
+
+        default:
+#if defined(__GNUC__)
+            __builtin_memmove(Destination, Source, Length);
 #else
-SOFT386_STATE EmulatorContext;
+            RtlMoveMemory(Destination, Source, Length);
 #endif
+    }
 
-static BOOLEAN A20Line = FALSE;
+#else // defined(_MSC_VER)
 
-/* PRIVATE FUNCTIONS **********************************************************/
+    PUCHAR Dest = (PUCHAR)Destination;
+    PUCHAR Src  = (PUCHAR)Source;
+
+    SIZE_T Count, NewSize = Length;
+
+    /* Move dword */
+    Count   = NewSize >> 2; // NewSize / sizeof(ULONG);
+    NewSize = NewSize  & 3; // NewSize % sizeof(ULONG);
+    __movsd(Dest, Src, Count);
+    Dest += Count << 2; // Count * sizeof(ULONG);
+    Src  += Count << 2;
+
+    /* Move word */
+    Count   = NewSize >> 1; // NewSize / sizeof(USHORT);
+    NewSize = NewSize  & 1; // NewSize % sizeof(USHORT);
+    __movsw(Dest, Src, Count);
+    Dest += Count << 1; // Count * sizeof(USHORT);
+    Src  += Count << 1;
+
+    /* Move byte */
+    Count   = NewSize; // NewSize / sizeof(UCHAR);
+    // NewSize = NewSize; // NewSize % sizeof(UCHAR);
+    __movsb(Dest, Src, Count);
+
+#endif
+}
 
-static VOID NTVDMCALL EmulatorReadMemory(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+VOID WINAPI EmulatorReadMemory(PFAST486_STATE State, ULONG Address, PVOID Buffer, ULONG Size)
 {
-    UNREFERENCED_PARAMETER(Context);
+    UNREFERENCED_PARAMETER(State);
+
+    // BIG HACK!!!! To make BIOS images working correctly,
+    // until Aleksander rewrites memory management!!
+    if (Address >= 0xFFFFFFF0) Address -= 0xFFF00000;
 
     /* If the A20 line is disabled, mask bit 20 */
     if (!A20Line) Address &= ~(1 << 20);
@@ -41,24 +143,33 @@ static VOID NTVDMCALL EmulatorReadMemory(PVOID Context, UINT Address, LPBYTE Buf
     /* Make sure the requested address is valid */
     if ((Address + Size) >= MAX_ADDRESS) return;
 
-    /* Read the data from the virtual address space and store it in the buffer */
-    RtlCopyMemory(Buffer, (LPVOID)((ULONG_PTR)BaseAddress + Address), Size);
-
-    /* Check if we modified the console video memory */
+    /*
+     * 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()))
     {
         DWORD VgaAddress = max(Address, VgaGetVideoBaseAddress());
-        LPBYTE VgaBuffer = &Buffer[VgaAddress - Address];
+        DWORD ActualSize = min(Address + Size - 1, VgaGetVideoLimitAddress())
+                           - VgaAddress + 1;
+        LPBYTE DestBuffer = (LPBYTE)REAL_TO_PHYS(VgaAddress);
 
         /* Read from the VGA memory */
-        VgaReadMemory(VgaAddress, VgaBuffer, Size);
+        VgaReadMemory(VgaAddress, DestBuffer, ActualSize);
     }
+
+    /* Read the data from the virtual address space and store it in the buffer */
+    EmulatorMoveMemory(Buffer, REAL_TO_PHYS(Address), Size);
 }
 
-static VOID NTVDMCALL EmulatorWriteMemory(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+VOID WINAPI EmulatorWriteMemory(PFAST486_STATE State, ULONG Address, PVOID Buffer, ULONG Size)
 {
-    UNREFERENCED_PARAMETER(Context);
+    UNREFERENCED_PARAMETER(State);
+
+    // BIG HACK!!!! To make BIOS images working correctly,
+    // until Aleksander rewrites memory management!!
+    if (Address >= 0xFFFFFFF0) Address -= 0xFFF00000;
 
     /* If the A20 line is disabled, mask bit 20 */
     if (!A20Line) Address &= ~(1 << 20);
@@ -70,563 +181,580 @@ static VOID NTVDMCALL EmulatorWriteMemory(PVOID Context, UINT Address, LPBYTE Bu
     if ((Address + Size) >= ROM_AREA_START && (Address < ROM_AREA_END)) return;
 
     /* Read the data from the buffer and store it in the virtual address space */
-    RtlCopyMemory((LPVOID)((ULONG_PTR)BaseAddress + Address), Buffer, Size);
+    EmulatorMoveMemory(REAL_TO_PHYS(Address), Buffer, Size);
 
-    /* Check if we modified the console video memory */
+    /*
+     * Check if we modified the VGA memory.
+     */
     if (((Address + Size) >= VgaGetVideoBaseAddress())
         && (Address < VgaGetVideoLimitAddress()))
     {
         DWORD VgaAddress = max(Address, VgaGetVideoBaseAddress());
-        LPBYTE VgaBuffer = &Buffer[VgaAddress - Address];
+        DWORD ActualSize = min(Address + Size - 1, VgaGetVideoLimitAddress())
+                           - VgaAddress + 1;
+        LPBYTE SrcBuffer = (LPBYTE)REAL_TO_PHYS(VgaAddress);
 
         /* Write to the VGA memory */
-        VgaWriteMemory(VgaAddress, VgaBuffer, Size);
+        VgaWriteMemory(VgaAddress, SrcBuffer, ActualSize);
     }
 }
 
-static VOID NTVDMCALL EmulatorReadIo(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+UCHAR WINAPI EmulatorIntAcknowledge(PFAST486_STATE State)
 {
-    UNREFERENCED_PARAMETER(Context);
-    UNREFERENCED_PARAMETER(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;
-        }
+    UNREFERENCED_PARAMETER(State);
 
-        case PIT_DATA_PORT(0):
-        case PIT_DATA_PORT(1):
-        case PIT_DATA_PORT(2):
-        {
-            *Buffer = PitReadData(Address - PIT_DATA_PORT(0));
-            break;
-        }
-
-        case PS2_CONTROL_PORT:
-        {
-            *Buffer = KeyboardReadStatus();
-            break;
-        }
-
-        case PS2_DATA_PORT:
-        {
-            *Buffer = KeyboardReadData();
-            break;
-        }
+    /* Get the interrupt number from the PIC */
+    return PicGetInterrupt();
+}
 
-        case VGA_AC_WRITE:
-        case VGA_AC_READ:
-        case VGA_SEQ_INDEX:
-        case VGA_SEQ_DATA:
-        case VGA_DAC_READ_INDEX:
-        case VGA_DAC_WRITE_INDEX:
-        case VGA_DAC_DATA:
-        case VGA_MISC_READ:
-        case VGA_MISC_WRITE:
-        case VGA_CRTC_INDEX:
-        case VGA_CRTC_DATA:
-        case VGA_GC_INDEX:
-        case VGA_GC_DATA:
-        case VGA_STAT_MONO:
-        case VGA_STAT_COLOR:
-        {
-            *Buffer = VgaReadPort(Address);
-            break;
-        }
+VOID EmulatorException(BYTE ExceptionNumber, LPWORD Stack)
+{
+    WORD CodeSegment, InstructionPointer;
+    PBYTE Opcode;
+
+    ASSERT(ExceptionNumber < 8);
+
+    /* Get the CS:IP */
+    InstructionPointer = Stack[STACK_IP];
+    CodeSegment = Stack[STACK_CS];
+    Opcode = (PBYTE)SEG_OFF_TO_PTR(CodeSegment, InstructionPointer);
+
+    /* Display a message to the user */
+    DisplayMessage(L"Exception: %s occured at %04X:%04X\n"
+                   L"Opcode: %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X",
+                   ExceptionName[ExceptionNumber],
+                   CodeSegment,
+                   InstructionPointer,
+                   Opcode[0],
+                   Opcode[1],
+                   Opcode[2],
+                   Opcode[3],
+                   Opcode[4],
+                   Opcode[5],
+                   Opcode[6],
+                   Opcode[7],
+                   Opcode[8],
+                   Opcode[9]);
+
+    Fast486DumpState(&EmulatorContext);
+
+    /* Stop the VDM */
+    EmulatorTerminate();
+    return;
+}
 
-        default:
-        {
-            DPRINT1("Read from unknown port: 0x%X\n", Address);
-        }
-    }
+VOID EmulatorTerminate(VOID)
+{
+    /* Stop the VDM */
+    CpuUnsimulate(); // Halt the CPU
+    VdmRunning = FALSE;
 }
 
-static VOID NTVDMCALL EmulatorWriteIo(PVOID Context, UINT Address, LPBYTE Buffer, INT Size)
+VOID EmulatorInterrupt(BYTE Number)
 {
-    BYTE Byte = *Buffer;
+    /* Call the Fast486 API */
+    Fast486Interrupt(&EmulatorContext, Number);
+}
 
-    UNREFERENCED_PARAMETER(Context);
-    UNREFERENCED_PARAMETER(Size);
+VOID EmulatorInterruptSignal(VOID)
+{
+    /* Call the Fast486 API */
+    Fast486InterruptSignal(&EmulatorContext);
+}
 
-    switch (Address)
-    {
-        case PIT_COMMAND_PORT:
-        {
-            PitWriteCommand(Byte);
-            break;
-        }
+VOID EmulatorSetA20(BOOLEAN Enabled)
+{
+    A20Line = Enabled;
+}
 
-        case PIT_DATA_PORT(0):
-        case PIT_DATA_PORT(1):
-        case PIT_DATA_PORT(2):
-        {
-            PitWriteData(Address - PIT_DATA_PORT(0), Byte);
-            break;
-        }
+static VOID WINAPI EmulatorDebugBreakBop(LPWORD Stack)
+{
+    DPRINT1("NTVDM: BOP_DEBUGGER\n");
+    DebugBreak();
+}
 
-        case PIC_MASTER_CMD:
-        case PIC_SLAVE_CMD:
-        {
-            PicWriteCommand(Address, Byte);
-            break;
-        }
+static BYTE WINAPI Port61hRead(USHORT Port)
+{
+    return Port61hState;
+}
 
-        case PIC_MASTER_DATA:
-        case PIC_SLAVE_DATA:
-        {
-            PicWriteData(Address, Byte);
-            break;
-        }
+static VOID WINAPI Port61hWrite(USHORT Port, BYTE Data)
+{
+    // BOOLEAN SpeakerStateChange = FALSE;
+    BYTE OldPort61hState = Port61hState;
 
-        case PS2_CONTROL_PORT:
-        {
-            KeyboardWriteCommand(Byte);
-            break;
-        }
+    /* Only the four lowest bytes can be written */
+    Port61hState = (Port61hState & 0xF0) | (Data & 0x0F);
 
-        case PS2_DATA_PORT:
-        {
-            KeyboardWriteData(Byte);
-            break;
-        }
+    if ((OldPort61hState ^ Port61hState) & 0x01)
+    {
+        DPRINT("PIT 2 Gate %s\n", Port61hState & 0x01 ? "on" : "off");
+        PitSetGate(2, !!(Port61hState & 0x01));
+        // SpeakerStateChange = TRUE;
+    }
 
-        case VGA_AC_WRITE:
-        case VGA_AC_READ:
-        case VGA_SEQ_INDEX:
-        case VGA_SEQ_DATA:
-        case VGA_DAC_READ_INDEX:
-        case VGA_DAC_WRITE_INDEX:
-        case VGA_DAC_DATA:
-        case VGA_MISC_READ:
-        case VGA_MISC_WRITE:
-        case VGA_CRTC_INDEX:
-        case VGA_CRTC_DATA:
-        case VGA_GC_INDEX:
-        case VGA_GC_DATA:
-        case VGA_STAT_MONO:
-        case VGA_STAT_COLOR:
-        {
-            VgaWritePort(Address, Byte);
-            break;
-        }
+    if ((OldPort61hState ^ Port61hState) & 0x02)
+    {
+        /* There were some change for the speaker... */
+        DPRINT("Speaker %s\n", Port61hState & 0x02 ? "on" : "off");
+        // SpeakerStateChange = TRUE;
+    }
+    // if (SpeakerStateChange) SpeakerChange();
+    SpeakerChange();
+}
 
-        default:
-        {
-            DPRINT1("Write to unknown port: 0x%X\n", Address);
-        }
+static VOID WINAPI PitChan0Out(LPVOID Param, BOOLEAN State)
+{
+    if (State)
+    {
+        DPRINT("PicInterruptRequest\n");
+        PicInterruptRequest(0); // Raise IRQ 0
     }
+    // else < Lower IRQ 0 >
 }
 
-static VOID EmulatorBop(WORD Code)
+static VOID WINAPI PitChan1Out(LPVOID Param, BOOLEAN State)
 {
-    WORD StackSegment, StackPointer, CodeSegment, InstructionPointer;
-    BYTE IntNum;
-    LPWORD Stack;
-
-    /* Get the SS:SP */
-#ifndef NEW_EMULATOR
-    StackSegment = EmulatorContext.state->segment_reg[SX86_SREG_SS].val;
-    StackPointer = EmulatorContext.state->general_reg[SX86_REG_SP].val;
+#if 0
+    if (State)
+    {
+        /* Set bit 4 of Port 61h */
+        Port61hState |= 1 << 4;
+    }
+    else
+    {
+        /* Clear bit 4 of Port 61h */
+        Port61hState &= ~(1 << 4);
+    }
 #else
-    StackSegment = EmulatorContext.SegmentRegs[SOFT386_REG_SS].Selector;
-    StackPointer = EmulatorContext.GeneralRegs[SOFT386_REG_ESP].LowWord;
+    Port61hState = (Port61hState & 0xEF) | (State << 4);
 #endif
+}
 
-    /* Get the stack */
-    Stack = (LPWORD)((ULONG_PTR)BaseAddress + TO_LINEAR(StackSegment, StackPointer));
+static VOID WINAPI PitChan2Out(LPVOID Param, BOOLEAN State)
+{
+    BYTE OldPort61hState = Port61hState;
+
+#if 0
+    if (State)
+    {
+        /* Set bit 5 of Port 61h */
+        Port61hState |= 1 << 5;
+    }
+    else
+    {
+        /* Clear bit 5 of Port 61h */
+        Port61hState &= ~(1 << 5);
+    }
+#else
+    Port61hState = (Port61hState & 0xDF) | (State << 5);
+#endif
 
-    if (Code == EMULATOR_INT_BOP)
+    if ((OldPort61hState ^ Port61hState) & 0x20)
     {
-        /* Get the interrupt number */
-        IntNum = LOBYTE(Stack[STACK_INT_NUM]);
+        DPRINT("PitChan2Out -- Port61hState changed\n");
+        SpeakerChange();
+    }
+}
 
-        /* Get the CS:IP */
-        InstructionPointer = Stack[STACK_IP];
-        CodeSegment = Stack[STACK_CS];
 
-        /* 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;
-        }
+static DWORD
+WINAPI
+PumpConsoleInput(LPVOID Parameter)
+{
+    HANDLE ConsoleInput = (HANDLE)Parameter;
+    INPUT_RECORD InputRecord;
+    DWORD Count;
 
-        /* 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, Stack);
-            return;
-        }
-        else if (IntNum >= BIOS_PIC_SLAVE_INT && IntNum < BIOS_PIC_SLAVE_INT + 8)
+    while (VdmRunning)
+    {
+        /* Make sure the task event is signaled */
+        WaitForSingleObject(VdmTaskEvent, INFINITE);
+
+        /* Wait for an input record */
+        if (!ReadConsoleInput(ConsoleInput, &InputRecord, 1, &Count))
         {
-            /* It was an IRQ from the slave PIC */
-            BiosHandleIrq(IntNum - BIOS_PIC_SLAVE_INT + 8, Stack);
-            return;
+            DWORD LastError = GetLastError();
+            DPRINT1("Error reading console input (0x%p, %lu) - Error %lu\n", ConsoleInput, Count, LastError);
+            return LastError;
         }
 
-        switch (IntNum)
+        ASSERT(Count != 0);
+
+        /* Check the event type */
+        switch (InputRecord.EventType)
         {
-            case BIOS_VIDEO_INTERRUPT:
-            {
-                /* This is the video BIOS interrupt, call the BIOS */
-                BiosVideoService(Stack);
-                break;
-            }
-            case BIOS_EQUIPMENT_INTERRUPT:
-            {
-                /* This is the BIOS "get equipment" command, call the BIOS */
-                BiosEquipmentService(Stack);
-                break;
-            }
-            case BIOS_KBD_INTERRUPT:
-            {
-                /* This is the keyboard BIOS interrupt, call the BIOS */
-                BiosKeyboardService(Stack);
+            /*
+             * Hardware events
+             */
+            case KEY_EVENT:
+                KeyboardEventHandler(&InputRecord.Event.KeyEvent);
                 break;
-            }
-            case BIOS_TIME_INTERRUPT:
-            {
-                /* This is the time BIOS interrupt, call the BIOS */
-                BiosTimeService(Stack);
-                break;
-            }
-            case BIOS_SYS_TIMER_INTERRUPT:
-            {
-                /* BIOS timer update */
-                BiosSystemTimerInterrupt(Stack);
+
+            case MOUSE_EVENT:
+                MouseEventHandler(&InputRecord.Event.MouseEvent);
                 break;
-            }
-            case 0x20:
-            {
-                DosInt20h(Stack);
+
+            case WINDOW_BUFFER_SIZE_EVENT:
+                ScreenEventHandler(&InputRecord.Event.WindowBufferSizeEvent);
                 break;
-            }
-            case 0x21:
-            {
-                DosInt21h(Stack);
+
+            /*
+             * Interface events
+             */
+            case MENU_EVENT:
+                MenuEventHandler(&InputRecord.Event.MenuEvent);
                 break;
-            }
-            case 0x23:
-            {
-                DosBreakInterrupt(Stack);
+
+            case FOCUS_EVENT:
+                FocusEventHandler(&InputRecord.Event.FocusEvent);
                 break;
-            }
+
             default:
-            {
-                DPRINT1("Unhandled interrupt: 0x%02X\n", IntNum);
                 break;
-            }
         }
     }
+
+    return 0;
 }
 
-#ifdef NEW_EMULATOR
-static VOID WINAPI EmulatorBiosOperation(PSOFT386_STATE State, WORD Code)
+static VOID EnableExtraHardware(HANDLE ConsoleInput)
 {
-    /*
-     * HACK: To maintain softx86 compatbility, just call the old EmulatorBop here.
-     * Later on, when softx86 is no longer needed, the code from EmulatorBop should
-     * be moved here and should use the "State" variable.
-     */
-    EmulatorBop(Code);
-}
+    DWORD ConInMode;
 
+    if (GetConsoleMode(ConsoleInput, &ConInMode))
+    {
+#if 0
+        // GetNumberOfConsoleMouseButtons();
+        // GetSystemMetrics(SM_CMOUSEBUTTONS);
+        // GetSystemMetrics(SM_MOUSEPRESENT);
+        if (MousePresent)
+        {
+#endif
+            /* Support mouse input events if there is a mouse on the system */
+            ConInMode |= ENABLE_MOUSE_INPUT;
+#if 0
+        }
+        else
+        {
+            /* Do not support mouse input events if there is no mouse on the system */
+            ConInMode &= ~ENABLE_MOUSE_INPUT;
+        }
 #endif
 
-#ifndef NEW_EMULATOR
+        SetConsoleMode(ConsoleInput, ConInMode);
+    }
+}
 
-static VOID EmulatorSoftwareInt(PVOID Context, BYTE Number)
-{
-    UNREFERENCED_PARAMETER(Context);
-    UNREFERENCED_PARAMETER(Number);
+/* PUBLIC FUNCTIONS ***********************************************************/
 
-    /* Do nothing */
+static VOID
+DumpMemoryRaw(HANDLE hFile)
+{
+    PVOID  Buffer;
+    SIZE_T Size;
+
+    /* Dump the VM memory */
+    SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
+    Buffer = REAL_TO_PHYS(NULL);
+    Size   = MAX_ADDRESS - (ULONG_PTR)(NULL);
+    WriteFile(hFile, Buffer, Size, &Size, NULL);
 }
 
-static VOID EmulatorHardwareInt(PVOID Context, BYTE Number)
+static VOID
+DumpMemoryTxt(HANDLE hFile)
 {
-    UNREFERENCED_PARAMETER(Context);
-    UNREFERENCED_PARAMETER(Number);
+#define LINE_SIZE   75 + 2
+    ULONG  i;
+    PBYTE  Ptr1, Ptr2;
+    CHAR   LineBuffer[LINE_SIZE];
+    PCHAR  Line;
+    SIZE_T LineSize;
+
+    /* Dump the VM memory */
+    SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
+    Ptr1 = Ptr2 = REAL_TO_PHYS(NULL);
+    while (MAX_ADDRESS - (ULONG_PTR)PHYS_TO_REAL(Ptr1) > 0)
+    {
+        Ptr1 = Ptr2;
+        Line = LineBuffer;
+
+        /* Print the address */
+        Line += snprintf(Line, LINE_SIZE + LineBuffer - Line, "%08x ", PHYS_TO_REAL(Ptr1));
+
+        /* Print up to 16 bytes... */
+
+        /* ... in hexadecimal form first... */
+        i = 0;
+        while (i++ <= 0x0F && (MAX_ADDRESS - (ULONG_PTR)PHYS_TO_REAL(Ptr1) > 0))
+        {
+            Line += snprintf(Line, LINE_SIZE + LineBuffer - Line, " %02x", *Ptr1);
+            ++Ptr1;
+        }
+
+        /* ... align with spaces if needed... */
+        RtlFillMemory(Line, 0x0F + 4 - i, ' ');
+        Line += 0x0F + 4 - i;
+
+        /* ... then in character form. */
+        i = 0;
+        while (i++ <= 0x0F && (MAX_ADDRESS - (ULONG_PTR)PHYS_TO_REAL(Ptr2) > 0))
+        {
+            *Line++ = ((*Ptr2 >= 0x20 && *Ptr2 <= 0x7E) || (*Ptr2 >= 0x80 && *Ptr2 < 0xFF) ? *Ptr2 : '.');
+            ++Ptr2;
+        }
 
-    /* Do nothing */
+        /* Newline */
+        *Line++ = '\r';
+        *Line++ = '\n';
+
+        /* Finally write the line to the file */
+        LineSize = Line - LineBuffer;
+        WriteFile(hFile, LineBuffer, LineSize, &LineSize, NULL);
+    }
 }
 
-static VOID EmulatorHardwareIntAck(PVOID Context, BYTE Number)
+VOID DumpMemory(BOOLEAN TextFormat)
 {
-    UNREFERENCED_PARAMETER(Context);
-    UNREFERENCED_PARAMETER(Number);
+    static ULONG DumpNumber = 0;
+
+    HANDLE hFile;
+    WCHAR  FileName[MAX_PATH];
+
+    /* Build a suitable file name */
+    _snwprintf(FileName, MAX_PATH,
+               L"memdump%lu.%s",
+               DumpNumber,
+               TextFormat ? L"txt" : L"dat");
+    ++DumpNumber;
+
+    DPRINT1("Creating memory dump file '%S'...\n", FileName);
+
+    /* Always create the dump file */
+    hFile = CreateFileW(FileName,
+                        GENERIC_WRITE,
+                        0,
+                        NULL,
+                        CREATE_ALWAYS,
+                        FILE_ATTRIBUTE_NORMAL,
+                        NULL);
+
+    if (hFile == INVALID_HANDLE_VALUE)
+    {
+        DPRINT1("Error when creating '%S' for memory dumping, GetLastError() = %u\n",
+                FileName, GetLastError());
+        return;
+    }
 
-    /* Do nothing */
-}
+    /* Dump the VM memory in the chosen format */
+    if (TextFormat)
+        DumpMemoryTxt(hFile);
+    else
+        DumpMemoryRaw(hFile);
 
-#endif
+    /* Close the file */
+    CloseHandle(hFile);
 
-/* PUBLIC FUNCTIONS ***********************************************************/
+    DPRINT1("Memory dump done\n");
+}
 
-BOOLEAN EmulatorInitialize()
+BOOLEAN EmulatorInitialize(HANDLE ConsoleInput, HANDLE ConsoleOutput)
 {
     /* Allocate memory for the 16-bit address space */
-    BaseAddress = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_ADDRESS);
-    if (BaseAddress == NULL) return FALSE;
-
-#ifndef NEW_EMULATOR
-    /* Initialize the softx86 CPU emulator */
-    if (!softx86_init(&EmulatorContext, SX86_CPULEVEL_80286))
+    BaseAddress = HeapAlloc(GetProcessHeap(), /*HEAP_ZERO_MEMORY*/ 0, MAX_ADDRESS);
+    if (BaseAddress == NULL)
     {
-        HeapFree(GetProcessHeap(), 0, BaseAddress);
+        wprintf(L"FATAL: Failed to allocate VDM memory.\n");
         return FALSE;
     }
+    /*
+     * For diagnostics purposes, we fill the memory with INT 0x03 codes
+     * so that if a program wants to execute random code in memory, we can
+     * retrieve the exact CS:IP where the problem happens.
+     */
+    RtlFillMemory(BaseAddress, MAX_ADDRESS, 0xCC);
+
+    /* Initialize I/O ports */
+    /* Initialize RAM */
 
-    /* Initialize the softx87 FPU emulator*/
-    if(!softx87_init(&FpuEmulatorContext, SX87_FPULEVEL_8087))
+    /* Initialize the CPU */
+
+    /* Initialize the internal clock */
+    if (!ClockInitialize())
     {
-        softx86_free(&EmulatorContext);
-        HeapFree(GetProcessHeap(), 0, BaseAddress);
+        wprintf(L"FATAL: Failed to initialize the clock\n");
         return FALSE;
     }
 
-    /* Set memory read/write callbacks */
-    EmulatorContext.callbacks->on_read_memory = EmulatorReadMemory;
-    EmulatorContext.callbacks->on_write_memory = EmulatorWriteMemory;
-
-    /* Set MMIO read/write callbacks */
-    EmulatorContext.callbacks->on_read_io = EmulatorReadIo;
-    EmulatorContext.callbacks->on_write_io = EmulatorWriteIo;
+    /* Initialize the CPU */
+    CpuInitialize();
+    // Fast486Initialize(&EmulatorContext,
+                      // EmulatorReadMemory,
+                      // EmulatorWriteMemory,
+                      // EmulatorReadIo,
+                      // EmulatorWriteIo,
+                      // NULL,
+                      // EmulatorBiosOperation,
+                      // EmulatorIntAcknowledge,
+                      // NULL /* TODO: Use a TLB */);
+
+    /* Initialize DMA */
+
+    /* Initialize the PIC, the PIT, the CMOS and the PC Speaker */
+    PicInitialize();
+    PitInitialize();
+    CmosInitialize();
+    SpeakerInitialize();
+
+    /* Set output functions */
+    PitSetOutFunction(0, NULL, PitChan0Out);
+    PitSetOutFunction(1, NULL, PitChan1Out);
+    PitSetOutFunction(2, NULL, PitChan2Out);
+
+    /* Register the I/O Ports */
+    RegisterIoPort(CONTROL_SYSTEM_PORT61H, Port61hRead, Port61hWrite);
+
+    /* Set the console input mode */
+    // FIXME: Activate ENABLE_WINDOW_INPUT when we will want to perform actions
+    // upon console window events (screen buffer resize, ...).
+    SetConsoleMode(ConsoleInput, ENABLE_PROCESSED_INPUT /* | ENABLE_WINDOW_INPUT */);
+    // SetConsoleMode(ConsoleOutput, ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
+
+    /**/EnableExtraHardware(ConsoleInput);/**/
+
+    /* Initialize the PS/2 port */
+    PS2Initialize();
+
+    /* Initialize the keyboard and mouse and connect them to their PS/2 ports */
+    KeyboardInit(0);
+    MouseInit(1);
+
+    /**************** ATTACH INPUT WITH CONSOLE *****************/
+    /* Start the input thread */
+    InputThread = CreateThread(NULL, 0, &PumpConsoleInput, ConsoleInput, 0, NULL);
+    if (InputThread == NULL)
+    {
+        DisplayMessage(L"Failed to create the console input thread.");
+        return FALSE;
+    }
+    /************************************************************/
 
-    /* Set interrupt callbacks */
-    EmulatorContext.callbacks->on_sw_int = EmulatorSoftwareInt;
-    EmulatorContext.callbacks->on_hw_int = EmulatorHardwareInt;
-    EmulatorContext.callbacks->on_hw_int_ack = EmulatorHardwareIntAck;
+    /* Initialize the VGA */
+    if (!VgaInitialize(ConsoleOutput))
+    {
+        DisplayMessage(L"Failed to initialize VGA support.");
+        return FALSE;
+    }
 
-    /* Connect the emulated FPU to the emulated CPU */
-    softx87_connect_to_CPU(&EmulatorContext, &FpuEmulatorContext);
-#else
-    /* Set the callbacks */
-    EmulatorContext.MemReadCallback = (SOFT386_MEM_READ_PROC)EmulatorReadMemory;
-    EmulatorContext.MemWriteCallback = (SOFT386_MEM_WRITE_PROC)EmulatorWriteMemory;
-    EmulatorContext.IoReadCallback = (SOFT386_IO_READ_PROC)EmulatorReadIo;
-    EmulatorContext.IoWriteCallback = (SOFT386_IO_WRITE_PROC)EmulatorWriteIo;
-    EmulatorContext.BopCallback = (SOFT386_BOP_PROC)EmulatorBiosOperation;
-
-    /* Reset the CPU */
-    Soft386Reset(&EmulatorContext);
-#endif
+    /* Initialize the software callback system and register the emulator BOPs */
+    InitializeInt32();
+    RegisterBop(BOP_DEBUGGER  , EmulatorDebugBreakBop);
+    // RegisterBop(BOP_UNSIMULATE, CpuUnsimulateBop);
 
-    /* Enable interrupts */
-    EmulatorSetFlag(EMULATOR_FLAG_IF);
+    /* Initialize VDD support */
+    VDDSupInitialize();
 
     return TRUE;
 }
 
-VOID EmulatorSetStack(WORD Segment, DWORD Offset)
+VOID EmulatorCleanup(VOID)
 {
-#ifndef NEW_EMULATOR
-    /* Call the softx86 API */
-    softx86_set_stack_ptr(&EmulatorContext, Segment, Offset);
-#else
-    Soft386SetStack(&EmulatorContext, Segment, Offset);
-#endif
-}
+    VgaCleanup();
 
-// FIXME: This function assumes 16-bit mode!!!
-VOID EmulatorExecute(WORD Segment, WORD Offset)
-{
-#ifndef NEW_EMULATOR
-    /* Call the softx86 API */
-    softx86_set_instruction_ptr(&EmulatorContext, Segment, Offset);
-#else
-    /* Tell Soft386 to move the instruction pointer */
-    Soft386ExecuteAt(&EmulatorContext, Segment, Offset);
-#endif
-}
+    /* Close the input thread handle */
+    if (InputThread != NULL) CloseHandle(InputThread);
+    InputThread = NULL;
 
-VOID EmulatorInterrupt(BYTE Number)
-{
-#ifndef NEW_EMULATOR
-    LPDWORD IntVecTable = (LPDWORD)((ULONG_PTR)BaseAddress);
-    UINT Segment, Offset;
+    PS2Cleanup();
 
-    /* Get the segment and offset */
-    Segment = HIWORD(IntVecTable[Number]);
-    Offset = LOWORD(IntVecTable[Number]);
+    SpeakerCleanup();
+    CmosCleanup();
+    // PitCleanup();
+    // PicCleanup();
 
-    /* Call the softx86 API */
-    softx86_make_simple_interrupt_call(&EmulatorContext, &Segment, &Offset);
-#else
-    /* Call the Soft386 API */
-    Soft386Interrupt(&EmulatorContext, Number);
-#endif
-}
+    CpuCleanup();
 
-VOID EmulatorExternalInterrupt(BYTE Number)
-{
-#ifndef NEW_EMULATOR
-    /* Call the softx86 API */
-    softx86_ext_hw_signal(&EmulatorContext, Number);
-#else
-    /* Call the Soft386 API */
-    Soft386Interrupt(&EmulatorContext, Number);
-#endif
+    /* Free the memory allocated for the 16-bit address space */
+    if (BaseAddress != NULL) HeapFree(GetProcessHeap(), 0, BaseAddress);
 }
 
-ULONG EmulatorGetRegister(ULONG Register)
-{
-#ifndef NEW_EMULATOR
-    if (Register < EMULATOR_REG_ES)
-    {
-        return EmulatorContext.state->general_reg[Register].val;
-    }
-    else
-    {
-        return EmulatorContext.state->segment_reg[Register - EMULATOR_REG_ES].val;
-    }
-#else
-    if (Register < EMULATOR_REG_ES)
-    {
-        return EmulatorContext.GeneralRegs[Register].Long;
-    }
-    else
-    {
-        return EmulatorContext.SegmentRegs[Register - EMULATOR_REG_ES].Selector;
-    }
-#endif
-}
 
-ULONG EmulatorGetProgramCounter(VOID)
-{
-#ifndef NEW_EMULATOR
-    return EmulatorContext.state->reg_ip;
-#else
-    return EmulatorContext.InstPtr.Long;
-#endif
-}
 
-VOID EmulatorSetRegister(ULONG Register, ULONG Value)
+VOID
+WINAPI
+VDDSimulate16(VOID)
 {
-#ifndef NEW_EMULATOR
-    if (Register < EMULATOR_REG_ES)
-    {
-        EmulatorContext.state->general_reg[Register].val = Value;
-    }
-    else
-    {
-        EmulatorContext.state->segment_reg[Register - EMULATOR_REG_ES].val = (USHORT)Value;
-    }
-#else
-    if (Register < EMULATOR_REG_ES)
-    {
-        EmulatorContext.GeneralRegs[Register].Long = Value;
-    }
-    else
-    {
-        Soft386SetSegment(&EmulatorContext, Register - EMULATOR_REG_ES, (USHORT)Value);
-    }
-#endif
+    CpuSimulate();
 }
 
-BOOLEAN EmulatorGetFlag(ULONG Flag)
+VOID
+WINAPI
+VDDTerminateVDM(VOID)
 {
-#ifndef NEW_EMULATOR
-    return (EmulatorContext.state->reg_flags.val & Flag) ? TRUE : FALSE;
-#else
-    return (EmulatorContext.Flags.Long & Flag) ? TRUE : FALSE;
-#endif
+    /* Stop the VDM */
+    EmulatorTerminate();
 }
 
-VOID EmulatorSetFlag(ULONG Flag)
+PBYTE
+WINAPI
+Sim32pGetVDMPointer(IN ULONG   Address,
+                    IN BOOLEAN ProtectedMode)
 {
-#ifndef NEW_EMULATOR
-    EmulatorContext.state->reg_flags.val |= Flag;
-#else
-    EmulatorContext.Flags.Long |= Flag;
-#endif
+    // 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)
 {
-#ifndef NEW_EMULATOR
-    EmulatorContext.state->reg_flags.val &= ~Flag;
-#else
-    EmulatorContext.Flags.Long &= ~Flag;
-#endif
+    UNREFERENCED_PARAMETER(Size);
+    return Sim32pGetVDMPointer(Address, ProtectedMode);
 }
 
-VOID EmulatorStep(VOID)
+PVOID
+WINAPI
+VdmMapFlat(IN USHORT   Segment,
+           IN ULONG    Offset,
+           IN VDM_MODE Mode)
 {
-#ifndef NEW_EMULATOR
-    LPWORD Instruction;
-
-    /* Print the current position - useful for debugging */
-    DPRINT("Executing at CS:IP = %04X:%04X\n",
-           EmulatorGetRegister(EMULATOR_REG_CS),
-           EmulatorContext.state->reg_ip);
-
-    Instruction = (LPWORD)((ULONG_PTR)BaseAddress
-                           + TO_LINEAR(EmulatorGetRegister(EMULATOR_REG_CS),
-                           EmulatorContext.state->reg_ip));
-
-    /* Check for the BIOS operation (BOP) sequence */
-    if (Instruction[0] == EMULATOR_BOP)
-    {
-        /* Skip the opcodes */
-        EmulatorContext.state->reg_ip += 4;
+    // FIXME
+    UNREFERENCED_PARAMETER(Mode);
 
-        // HACK: Refresh the display because the called function may wait.
-        VgaRefreshDisplay();
-
-        /* Call the BOP handler */
-        EmulatorBop(Instruction[1]);
-    }
-
-    /* Call the softx86 API */
-    if (!softx86_step(&EmulatorContext))
-    {
-        /* Invalid opcode */
-        EmulatorInterrupt(EMULATOR_EXCEPTION_INVALID_OPCODE);
-    }
-#else
-    /* Dump the state for debugging purposes */
-    // Soft386DumpState(&EmulatorContext);
-
-    /* Execute the next instruction */
-    Soft386StepInto(&EmulatorContext);
-#endif
+    return SEG_OFF_TO_PTR(Segment, Offset);
 }
 
-VOID EmulatorCleanup(VOID)
+BOOL
+WINAPI
+VdmFlushCache(IN USHORT   Segment,
+              IN ULONG    Offset,
+              IN ULONG    Size,
+              IN VDM_MODE Mode)
 {
-#ifndef NEW_EMULATOR
-    /* Free the softx86 CPU and FPU emulator */
-    softx87_free(&FpuEmulatorContext);
-    softx86_free(&EmulatorContext);
-#endif
-
-    /* Free the memory allocated for the 16-bit address space */
-    if (BaseAddress != NULL) HeapFree(GetProcessHeap(), 0, BaseAddress);
+    // FIXME
+    UNIMPLEMENTED;
+    return TRUE;
 }
 
-VOID EmulatorSetA20(BOOLEAN Enabled)
+BOOL
+WINAPI
+VdmUnmapFlat(IN USHORT   Segment,
+             IN ULONG    Offset,
+             IN PVOID    Buffer,
+             IN VDM_MODE Mode)
 {
-    A20Line = Enabled;
+    // FIXME
+    UNIMPLEMENTED;
+    return TRUE;
 }
 
 /* EOF */