[NTVDM]: Add debug print for timer ticks to try to find why the emulator sometimes...
[reactos.git] / subsystems / ntvdm / ntvdm.c
index 29cf573..004c42e 100644 (file)
 /*
- * COPYRIGHT:       See COPYING in the top level directory
- * PROJECT:         ReactOS kernel
- * FILE:            subsys/ntvdm/ntvdm->c
+ * COPYRIGHT:       GPL - See COPYING in the top level directory
+ * PROJECT:         ReactOS Virtual DOS Machine
+ * FILE:            ntvdm.c
  * PURPOSE:         Virtual DOS Machine
- * PROGRAMMER:      Robert Dickenson (robd@mok.lvcm.com)
- * UPDATE HISTORY:
- *                  Created 23/10/2002
+ * PROGRAMMERS:     Aleksandar Andrejevic <theflash AT sdf DOT lonestar DOT org>
  */
 
-/* INCLUDES *****************************************************************/
+/* INCLUDES *******************************************************************/
 
-#include <stdarg.h>
-#define WIN32_NO_STATUS
-#include <windef.h>
-#include <winbase.h>
-#include <wincon.h>
-#include <winuser.h>
-#include <stdio.h>
+#define NDEBUG
 
-#include "resource.h"
+#include "ntvdm.h"
+#include "emulator.h"
 
-#define NDEBUG
-#include <debug.h>
+#include "bios/bios.h"
+#include "dos/dem.h"
+#include "hardware/cmos.h"
+#include "hardware/ps2.h"
+#include "hardware/timer.h"
+#include "hardware/vga.h"
 
-/* GLOBALS ******************************************************************/
+/*
+ * Activate this line if you want to be able to test NTVDM with:
+ * ntvdm.exe <program>
+ */
+#define TESTING
 
+#define IPS_DISPLAY
 
-/* FUNCTIONS *****************************************************************/
+/* PUBLIC VARIABLES ***********************************************************/
 
-void PrintString(char* fmt,...)
-{
-   char buffer[512];
-   va_list ap;
+static HANDLE ConsoleInput  = INVALID_HANDLE_VALUE;
+static HANDLE ConsoleOutput = INVALID_HANDLE_VALUE;
+static DWORD  OrgConsoleInputMode, OrgConsoleOutputMode;
+static CONSOLE_CURSOR_INFO         OrgConsoleCursorInfo;
+static CONSOLE_SCREEN_BUFFER_INFO  OrgConsoleBufferInfo;
 
-   va_start(ap, fmt);
-   vsprintf(buffer, fmt, ap);
-   va_end(ap);
+/* PUBLIC FUNCTIONS ***********************************************************/
 
-   OutputDebugStringA(buffer);
+VOID DisplayMessage(LPCWSTR Format, ...)
+{
+    WCHAR Buffer[256];
+    va_list Parameters;
+
+    va_start(Parameters, Format);
+    _vsnwprintf(Buffer, 256, Format, Parameters);
+    DPRINT1("\n\nNTVDM Subsystem\n%S\n\n", Buffer);
+    MessageBoxW(NULL, Buffer, L"NTVDM Subsystem", MB_OK);
+    va_end(Parameters);
 }
 
-/*
-GetVersion
-GetVolumeInformationW
-GetWindowsDirectoryA
-GlobalMemoryStatus
-HeapAlloc
-HeapCreate
-HeapDestroy
-HeapFree
-HeapReAlloc
-
-GetNextVDMCommand
-ExitVDM
-RegisterConsoleVDM
-SetVDMCurrentDirectories
-VDMConsoleOperation
-WriteConsoleInputVDMW
-
-NtSetLdtEntries
-NtTerminateProcess
-
-NtMapViewOfSection
-NtUnmapViewOfSection
-
-NtVdmControl
- */
-typedef struct tag_VDM_CONFIG {
-    int dos_options;
-    int files;
-    int buffers;
-    WCHAR** device_list;
-//dos=high, umb
-//device=%SystemRoot%\system32\himem.sys
-//files=40
-} VDM_CONFIG, *PVDM_CONFIG;
-
-typedef struct tag_VDM_AUTOEXEC {
-    WCHAR** load_list;
-//lh %SystemRoot%\system32\mscdexnt.exe
-//lh %SystemRoot%\system32\redir
-//lh %SystemRoot%\system32\dosx
-} VDM_AUTOEXEC, *PVDM_AUTOEXEC;
-
-typedef struct tag_VDM_CONTROL_BLOCK {
-    HANDLE hHeap;
-    PVOID ImageMem;
-    VDM_CONFIG vdmConfig;
-    VDM_AUTOEXEC vdmAutoexec;
-    PROCESS_INFORMATION ProcessInformation;
-    CHAR CommandLine[MAX_PATH];
-    CHAR CurrentDirectory[MAX_PATH];
-
-} VDM_CONTROL_BLOCK, *PVDM_CONTROL_BLOCK;
-
-
-BOOL
-StartVDM(PVDM_CONTROL_BLOCK vdm)
+BOOL WINAPI ConsoleCtrlHandler(DWORD ControlType)
 {
-   BOOL Result;
-   STARTUPINFOA StartupInfo;
-
-   StartupInfo.cb = sizeof(StartupInfo);
-   StartupInfo.lpReserved = NULL;
-   StartupInfo.lpDesktop = NULL;
-   StartupInfo.lpTitle = NULL;
-   StartupInfo.dwFlags = 0;
-   StartupInfo.cbReserved2 = 0;
-   StartupInfo.lpReserved2 = 0;
-
-   Result = CreateProcessA(vdm->CommandLine,
-                          NULL,
-                          NULL,
-                          NULL,
-                          FALSE,
-                          DETACHED_PROCESS,
-                          NULL,
-                          NULL,
-                          &StartupInfo,
-                          &vdm->ProcessInformation);
-    if (!Result) {
-        PrintString("VDM: Failed to execute target process\n");
-        return FALSE;
+    switch (ControlType)
+    {
+        case CTRL_C_EVENT:
+        case CTRL_BREAK_EVENT:
+        {
+            /* Call INT 23h */
+            EmulatorInterrupt(0x23);
+            break;
+        }
+        default:
+        {
+            /* Stop the VDM if the user logs out or closes the console */
+            VdmRunning = FALSE;
+        }
     }
-    WaitForSingleObject(vdm->ProcessInformation.hProcess, INFINITE);
-    CloseHandle(vdm->ProcessInformation.hProcess);
-    CloseHandle(vdm->ProcessInformation.hThread);
     return TRUE;
 }
 
-BOOL
-ShutdownVDM(PVDM_CONTROL_BLOCK vdm)
+BOOL ConsoleInit(VOID)
 {
-    BOOL result = TRUE;
+    /* Set the handler routine */
+    SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
+
+    /* Get the input handle to the real console, and check for success */
+    ConsoleInput = CreateFileW(L"CONIN$",
+                               GENERIC_READ | GENERIC_WRITE,
+                               FILE_SHARE_READ | FILE_SHARE_WRITE,
+                               NULL,
+                               OPEN_EXISTING,
+                               0,
+                               NULL);
+    if (ConsoleInput == INVALID_HANDLE_VALUE)
+    {
+        wprintf(L"FATAL: Cannot retrieve a handle to the console input\n");
+        return FALSE;
+    }
 
-    return result;
-}
+    /* Get the output handle to the real console, and check for success */
+    ConsoleOutput = CreateFileW(L"CONOUT$",
+                                GENERIC_READ | GENERIC_WRITE,
+                                FILE_SHARE_READ | FILE_SHARE_WRITE,
+                                NULL,
+                                OPEN_EXISTING,
+                                0,
+                                NULL);
+    if (ConsoleOutput == INVALID_HANDLE_VALUE)
+    {
+        CloseHandle(ConsoleInput);
+        wprintf(L"FATAL: Cannot retrieve a handle to the console output\n");
+        return FALSE;
+    }
 
-BOOL ReadConfigForVDM(PVDM_CONTROL_BLOCK vdm)
-{
-    BOOL result = TRUE;
-    DWORD dwError;
-    HANDLE hFile;
-
-    hFile = CreateFileW(L"\\system32\\config.nt",
-                        GENERIC_READ,
-                        FILE_SHARE_READ,
-                        NULL,
-                        OPEN_ALWAYS /*OPEN_EXISTING*/,
-                        FILE_ATTRIBUTE_NORMAL,
-                        0);
-    dwError = GetLastError();
-    if (hFile == INVALID_HANDLE_VALUE) {
-        // error with file path or system problem?
-    } else {
-        if (dwError == 0L) {
-            // we just created a new file, perhaps we should set/write some defaults?
-        }
-        if (dwError == ERROR_ALREADY_EXISTS) {
-            // read the line entries and cache in some struct...
-        }
-        CloseHandle(hFile);
+    /* Save the original input and output console modes */
+    if (!GetConsoleMode(ConsoleInput , &OrgConsoleInputMode ) ||
+        !GetConsoleMode(ConsoleOutput, &OrgConsoleOutputMode))
+    {
+        CloseHandle(ConsoleOutput);
+        CloseHandle(ConsoleInput);
+        wprintf(L"FATAL: Cannot save console in/out modes\n");
+        return FALSE;
     }
 
-    hFile = CreateFileW(L"\\system32\\autoexec.nt",
-                        GENERIC_READ,
-                        FILE_SHARE_READ,
-                        NULL,
-                        OPEN_ALWAYS,
-                        FILE_ATTRIBUTE_NORMAL,
-                        0);
-    dwError = GetLastError();
-    if (hFile == INVALID_HANDLE_VALUE) {
-        // error with file path or system problem?
-    } else {
-        if (dwError == 0L) {
-            // we just created a new file, perhaps we should set/write some defaults?
-        }
-        if (dwError == ERROR_ALREADY_EXISTS) {
-            // read the line entries and cache in some struct...
-        }
-        CloseHandle(hFile);
+    /* Save the original cursor and console screen buffer information */
+    if (!GetConsoleCursorInfo(ConsoleOutput, &OrgConsoleCursorInfo) ||
+        !GetConsoleScreenBufferInfo(ConsoleOutput, &OrgConsoleBufferInfo))
+    {
+        CloseHandle(ConsoleOutput);
+        CloseHandle(ConsoleInput);
+        wprintf(L"FATAL: Cannot save console cursor/screen-buffer info\n");
+        return FALSE;
     }
 
-       return result;
+    return TRUE;
 }
 
-BOOL
-LoadConfigDriversForVDM(PVDM_CONFIG vdmConfig)
+VOID ConsoleCleanup(VOID)
 {
-    BOOL result = TRUE;
-
-       return result;
+    SMALL_RECT ConRect;
+    CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;
+
+    /* Restore the old screen buffer */
+    SetConsoleActiveScreenBuffer(ConsoleOutput);
+
+    /* Restore the original console size */
+    GetConsoleScreenBufferInfo(ConsoleOutput, &ConsoleInfo);
+    ConRect.Left = 0; // OrgConsoleBufferInfo.srWindow.Left;
+    // ConRect.Top  = ConsoleInfo.dwCursorPosition.Y / (OrgConsoleBufferInfo.srWindow.Bottom - OrgConsoleBufferInfo.srWindow.Top + 1);
+    // ConRect.Top *= (OrgConsoleBufferInfo.srWindow.Bottom - OrgConsoleBufferInfo.srWindow.Top + 1);
+    ConRect.Top    = ConsoleInfo.dwCursorPosition.Y;
+    ConRect.Right  = ConRect.Left + OrgConsoleBufferInfo.srWindow.Right  - OrgConsoleBufferInfo.srWindow.Left;
+    ConRect.Bottom = ConRect.Top  + OrgConsoleBufferInfo.srWindow.Bottom - OrgConsoleBufferInfo.srWindow.Top ;
+    /* See the following trick explanation in vga.c:VgaEnterTextMode() */
+    SetConsoleScreenBufferSize(ConsoleOutput, OrgConsoleBufferInfo.dwSize);
+    SetConsoleWindowInfo(ConsoleOutput, TRUE, &ConRect);
+    // SetConsoleWindowInfo(ConsoleOutput, TRUE, &OrgConsoleBufferInfo.srWindow);
+    SetConsoleScreenBufferSize(ConsoleOutput, OrgConsoleBufferInfo.dwSize);
+
+    /* Restore the original cursor shape */
+    SetConsoleCursorInfo(ConsoleOutput, &OrgConsoleCursorInfo);
+
+    /* Restore the original input and output console modes */
+    SetConsoleMode(ConsoleOutput, OrgConsoleOutputMode);
+    SetConsoleMode(ConsoleInput , OrgConsoleInputMode );
+
+    /* Close the console handles */
+    if (ConsoleOutput != INVALID_HANDLE_VALUE) CloseHandle(ConsoleOutput);
+    if (ConsoleInput  != INVALID_HANDLE_VALUE) CloseHandle(ConsoleInput);
 }
 
-BOOL
-SetConfigOptionsForVDM(PVDM_AUTOEXEC vdmAutoexec)
+INT wmain(INT argc, WCHAR *argv[])
 {
-    BOOL result = TRUE;
-
-       return result;
-}
+    INT i;
+    CHAR CommandLine[DOS_CMDLINE_LENGTH];
+    LARGE_INTEGER StartPerfCount;
+    LARGE_INTEGER Frequency, LastTimerTick, LastRtcTick, Counter;
+    LONGLONG TimerTicks;
+    DWORD StartTickCount, CurrentTickCount;
+    DWORD LastClockUpdate;
+    DWORD LastVerticalRefresh;
+#ifdef IPS_DISPLAY
+    DWORD LastCyclePrintout;
+    DWORD Cycles = 0;
+#endif
+    INT KeyboardIntCounter = 0;
+
+#ifndef TESTING
+    UNREFERENCED_PARAMETER(argc);
+    UNREFERENCED_PARAMETER(argv);
+
+    /* The DOS command line must be ASCII */
+    WideCharToMultiByte(CP_ACP, 0, GetCommandLine(), -1, CommandLine, sizeof(CommandLine), NULL, NULL);
+#else
+    if (argc == 2 && argv[1] != NULL)
+    {
+        WideCharToMultiByte(CP_ACP, 0, argv[1], -1, CommandLine, sizeof(CommandLine), NULL, NULL);
+    }
+    else
+    {
+        wprintf(L"\nReactOS Virtual DOS Machine\n\n"
+                L"Usage: NTVDM <executable>\n");
+        return 0;
+    }
+#endif
 
-BOOL
-CreateVDM(PVDM_CONTROL_BLOCK vdm)
-{
-//    BOOL result = TRUE;
-    SYSTEM_INFO inf;
-    MEMORYSTATUS stat;
-
-
-    GlobalMemoryStatus(&stat);
-    if (stat.dwLength != sizeof(MEMORYSTATUS)) {
-        printf("WARNING: GlobalMemoryStatus() returned unknown structure version, size %ld, expected %d.\n", stat.dwLength, sizeof(stat));
-    } else {
-        printf("Memory Load: %ld percent in use.\n", stat.dwMemoryLoad);
-        printf("\t%ld total bytes physical memory.\n", stat.dwTotalPhys);
-        printf("\t%ld available physical memory.\n", stat.dwAvailPhys);
-        printf("\t%ld total bytes paging file.\n", stat.dwTotalPageFile);
-        printf("\t%ld available paging file.\n", stat.dwAvailPageFile);
-        printf("\t%lx total bytes virtual memory.\n", stat.dwTotalVirtual);
-        printf("\t%lx available bytes virtual memory.\n", stat.dwAvailVirtual);
-
-#define OUT_OF_HEADROOM 90
-        if (stat.dwMemoryLoad > OUT_OF_HEADROOM) {
-            DPRINT("VDM: system resources deemed to low to start VDM.\n");
-            //SetLastError();
-            return FALSE;
-        }
+    DPRINT1("\n\n\nNTVDM - Starting '%s'...\n\n\n", CommandLine);
 
+    /* Initialize the console */
+    if (!ConsoleInit())
+    {
+        wprintf(L"FATAL: A problem occurred when trying to initialize the console\n");
+        goto Cleanup;
     }
 
-    GetSystemInfo(&inf);
-    vdm->hHeap = HeapCreate(0, inf.dwAllocationGranularity, 0);
-    if (vdm->hHeap == NULL) {
-        DPRINT("VDM: failed to create heap.\n");
-        return FALSE;
+    /* Initialize the emulator */
+    if (!EmulatorInitialize(ConsoleInput, ConsoleOutput))
+    {
+        wprintf(L"FATAL: Failed to initialize the emulator\n");
+        goto Cleanup;
     }
 
-#define DEFAULT_VDM_IMAGE_SIZE 2000000
-    vdm->ImageMem = HeapAlloc(vdm->hHeap, 0, DEFAULT_VDM_IMAGE_SIZE);
-    if (vdm->ImageMem == NULL) {
-        DPRINT("VDM: failed to allocate image memory from heap %x.\n", vdm->hHeap);
-        HeapDestroy(vdm->hHeap);
-        vdm->hHeap = NULL;
-        return FALSE;
+    /* Initialize the performance counter (needed for hardware timers) */
+    if (!QueryPerformanceFrequency(&Frequency))
+    {
+        wprintf(L"FATAL: Performance counter not available\n");
+        goto Cleanup;
     }
-    return TRUE;
-}
 
-BOOL
-DestroyVDM(PVDM_CONTROL_BLOCK vdm)
-{
-    BOOL result = TRUE;
+    /* Initialize the system BIOS */
+    if (!BiosInitialize(ConsoleInput, ConsoleOutput))
+    {
+        wprintf(L"FATAL: Failed to initialize the VDM BIOS.\n");
+        goto Cleanup;
+    }
 
-    if (vdm->ImageMem != NULL) {
-        if (HeapFree(vdm->hHeap, 0, vdm->ImageMem) != FALSE) {
-            DPRINT("VDM: failed to free memory from heap %x.\n", vdm->hHeap);
-            result = FALSE;
-        }
-        vdm->ImageMem = NULL;
+    /* Initialize the VDM DOS kernel */
+    if (!DosInitialize(NULL))
+    {
+        wprintf(L"FATAL: Failed to initialize the VDM DOS kernel.\n");
+        goto Cleanup;
     }
-    if (vdm->hHeap != NULL) {
-        if (!HeapDestroy(vdm->hHeap)) {
-            DPRINT("VDM: failed to destroy heap %x.\n", vdm->hHeap);
-            result = FALSE;
-        }
-        vdm->hHeap = NULL;
+
+    /* Start the process from the command line */
+    if (!DosCreateProcess(CommandLine, 0))
+    {
+        DisplayMessage(L"Could not start program: %S", CommandLine);
+        goto Cleanup;
     }
-    return result;
-}
 
-int WINAPI
-WinMain(HINSTANCE hInstance,  HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
-{
-    VDM_CONTROL_BLOCK VdmCB;
-    DWORD Result;
-    ULONG i;
-    BOOL vdmStarted = FALSE;
+    /* Find the starting performance and tick count */
+    StartTickCount = GetTickCount();
+    QueryPerformanceCounter(&StartPerfCount);
+
+    /* Set the different last counts to the starting count */
+    LastClockUpdate = LastVerticalRefresh =
+#ifdef IPS_DISPLAY
+    LastCyclePrintout =
+#endif
+    StartTickCount;
+
+    /* Set the last timer ticks to the current time */
+    LastTimerTick = LastRtcTick = StartPerfCount;
+
+    /* Main loop */
+    while (VdmRunning)
+    {
+        DWORD PitResolution = PitGetResolution();
+        DWORD RtcFrequency = RtcGetTicksPerSecond();
+
+        /* Get the current number of ticks */
+        CurrentTickCount = GetTickCount();
+
+        if ((PitResolution <= 1000) && (RtcFrequency <= 1000))
+        {
+            /* Calculate the approximate performance counter value instead */
+            Counter.QuadPart = StartPerfCount.QuadPart
+                               + (CurrentTickCount - StartTickCount)
+                               * (Frequency.QuadPart / 1000);
+        }
+        else
+        {
+            /* Get the current performance counter value */
+            QueryPerformanceCounter(&Counter);
+        }
 
-    WCHAR WelcomeMsg[RC_STRING_MAX_SIZE];
-    WCHAR PromptMsg[RC_STRING_MAX_SIZE];
-    CHAR InputBuffer[255];
+        /* Get the number of PIT ticks that have passed */
+        TimerTicks = ((Counter.QuadPart - LastTimerTick.QuadPart)
+                     * PIT_BASE_FREQUENCY) / Frequency.QuadPart;
 
-    LoadStringW( GetModuleHandle(NULL), STRING_WelcomeMsg, WelcomeMsg,sizeof(WelcomeMsg) / sizeof(WelcomeMsg[0]));
-    LoadStringW( GetModuleHandle(NULL), STRING_PromptMsg, PromptMsg ,sizeof(PromptMsg) / sizeof(PromptMsg[0]));
+        /* Update the PIT */
+        if (TimerTicks > 0)
+        {
+            PitClock(TimerTicks);
+            LastTimerTick = Counter;
+        }
 
-    AllocConsole();
-    SetConsoleTitleW(L"ntvdm");
+        /* Check for RTC update */
+        if ((CurrentTickCount - LastClockUpdate) >= 1000)
+        {
+            RtcTimeUpdate();
+            LastClockUpdate = CurrentTickCount;
+        }
 
-    WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),
-                 WelcomeMsg, lstrlenW(WelcomeMsg),  // wcslen(WelcomeMsg),
-                 &Result, NULL);
+        /* Check for RTC periodic tick */
+        if ((Counter.QuadPart - LastRtcTick.QuadPart)
+            >= (Frequency.QuadPart / (LONGLONG)RtcFrequency))
+        {
+            RtcPeriodicTick();
+            LastRtcTick = Counter;
+        }
 
-    if (!CreateVDM(&VdmCB)) {
-        DPRINT("VDM: failed to create VDM.\n");
-        //SetLastError();
-        return 2;
-    }
+        /* Check for vertical retrace */
+        if ((CurrentTickCount - LastVerticalRefresh) >= 15)
+        {
+            VgaRefreshDisplay();
+            LastVerticalRefresh = CurrentTickCount;
+        }
 
-       ReadConfigForVDM(&VdmCB);
+        KeyboardIntCounter++;
+        if (KeyboardIntCounter == KBD_INT_CYCLES)
+        {
+            GenerateKeyboardInterrupts();
+            KeyboardIntCounter = 0;
+        }
 
-    if (!LoadConfigDriversForVDM(&(VdmCB.vdmConfig))) {
-        DPRINT("VDM: failed to load configuration drivers.\n");
-        //SetLastError();
-        return 2;
-    }
-    if (!SetConfigOptionsForVDM(&(VdmCB.vdmAutoexec))) {
-        DPRINT("VDM: failed to set configuration options.\n");
-        //SetLastError();
-        return 3;
-    }
+        /* Horizontal retrace occurs as fast as possible */
+        VgaHorizontalRetrace();
 
-    GetSystemDirectoryA(VdmCB.CommandLine, MAX_PATH);
-    strcat(VdmCB.CommandLine, "\\hello.exe");
-    GetWindowsDirectoryA(VdmCB.CurrentDirectory, MAX_PATH);
-
-    for (;;) {
-        WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),
-                     PromptMsg, lstrlenW(PromptMsg),  // wcslen(PromptMsg),
-                     &Result, NULL);
-        i = 0;
-        do {
-            ReadConsoleA(GetStdHandle(STD_INPUT_HANDLE),
-                        &InputBuffer[i], 1,
-                        &Result, NULL);
-            if (++i >= (sizeof(InputBuffer) - 1)) {
-                break;
-            }
-        } while (InputBuffer[i - 1] != '\n');
-        InputBuffer[i - 1] = '\0';
-
-        if (InputBuffer[0] == 'r' || InputBuffer[0] == 'R') {
-            if (!vdmStarted) {
-                if (StartVDM(&VdmCB)) {
-                    vdmStarted = TRUE;
-                } else {
-                    DPRINT("VDM: failed to start.\n");
-                }
-            } else {
-                DPRINT("VDM: already started.\n");
-            }
+        /* Continue CPU emulation */
+        for (i = 0; (i < STEPS_PER_CYCLE) && VdmRunning; i++)
+        {
+            EmulatorStep();
+#ifdef IPS_DISPLAY
+            Cycles++;
+#endif
         }
-        if (InputBuffer[0] == 's' || InputBuffer[0] == 'S') {
-            if (vdmStarted) {
-                if (ShutdownVDM(&VdmCB)) {
-                    vdmStarted = FALSE;
-                } else {
-                    DPRINT("VDM: failed to shutdown.\n");
-                }
-            } else {
-                DPRINT("VDM: not started.\n");
-            }
-        }
-        if (InputBuffer[0] == 'q' || InputBuffer[0] == 'Q') {
-            break;
+
+#ifdef IPS_DISPLAY
+        if ((CurrentTickCount - LastCyclePrintout) >= 1000)
+        {
+            DPRINT1("NTVDM: %lu Instructions Per Second; TimerTicks = %lu\n", Cycles, TimerTicks);
+            LastCyclePrintout = CurrentTickCount;
+            Cycles = 0;
         }
+#endif
     }
 
-    if (!ShutdownVDM(&VdmCB)) {
-        DPRINT("VDM: failed to cleanly shutdown VDM.\n");
-        //SetLastError();
-        return 5;
-    }
+    /* Perform another screen refresh */
+    VgaRefreshDisplay();
 
-    if (!DestroyVDM(&VdmCB)) {
-        DPRINT("VDM: failed to cleanly destroy VDM.\n");
-        //SetLastError();
-        return 6;
-    }
+Cleanup:
+    BiosCleanup();
+    EmulatorCleanup();
+    ConsoleCleanup();
+
+    DPRINT1("\n\n\nNTVDM - Exiting...\n\n\n");
 
-    ExitProcess(0);
     return 0;
 }
+
+/* EOF */