[NTVDM]
[reactos.git] / subsystems / ntvdm / ntvdm.c
index 4c0df14..91bccf7 100644 (file)
 
 #include "ntvdm.h"
 #include "emulator.h"
-#include "cmos.h"
-#include "bios.h"
-#include "speaker.h"
-#include "vga.h"
-#include "dos.h"
-#include "timer.h"
-#include "pic.h"
-#include "ps2.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"
 
 /*
  * Activate this line if you want to be able to test NTVDM with:
  */
 #define TESTING
 
+/*
+ * Activate IPS_DISPLAY if you want to display the
+ * number of instructions per second, as well as
+ * the computed number of ticks for the PIT.
+ */
+// #define IPS_DISPLAY
+
+/*
+ * Activate WORKING_TIMER when the PIT timing problem is fixed.
+ */
+// #define WORKING_TIMER
+
 /* PUBLIC VARIABLES ***********************************************************/
 
-BOOLEAN VdmRunning = TRUE;
-LPVOID BaseAddress = NULL;
+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;
 
 /* PUBLIC FUNCTIONS ***********************************************************/
 
@@ -53,7 +67,7 @@ BOOL WINAPI ConsoleCtrlHandler(DWORD ControlType)
         case CTRL_C_EVENT:
         case CTRL_BREAK_EVENT:
         {
-            /* Perform interrupt 0x23 */
+            /* Call INT 23h */
             EmulatorInterrupt(0x23);
             break;
         }
@@ -66,6 +80,97 @@ BOOL WINAPI ConsoleCtrlHandler(DWORD ControlType)
     return TRUE;
 }
 
+BOOL ConsoleInit(VOID)
+{
+    /* 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;
+    }
+
+    /* 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;
+    }
+
+    /* 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;
+    }
+
+    /* 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 TRUE;
+}
+
+VOID ConsoleCleanup(VOID)
+{
+    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);
+}
+
 INT wmain(INT argc, WCHAR *argv[])
 {
     INT i;
@@ -76,13 +181,12 @@ INT wmain(INT argc, WCHAR *argv[])
     DWORD StartTickCount, CurrentTickCount;
     DWORD LastClockUpdate;
     DWORD LastVerticalRefresh;
+#ifdef IPS_DISPLAY
     DWORD LastCyclePrintout;
     DWORD Cycles = 0;
+#endif
     INT KeyboardIntCounter = 0;
 
-    /* Set the handler routine */
-    SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE);
-
 #ifndef TESTING
     UNREFERENCED_PARAMETER(argc);
     UNREFERENCED_PARAMETER(argv);
@@ -104,53 +208,36 @@ INT wmain(INT argc, WCHAR *argv[])
 
     DPRINT1("\n\n\nNTVDM - Starting '%s'...\n\n\n", CommandLine);
 
-    /* Initialize the emulator */
-    if (!EmulatorInitialize())
-    {
-        wprintf(L"FATAL: Failed to initialize the CPU emulator\n");
-        goto Cleanup;
-    }
-
-    /* Initialize the performance counter (needed for hardware timers) */
-    if (!QueryPerformanceFrequency(&Frequency))
+    /* Initialize the console */
+    if (!ConsoleInit())
     {
-        wprintf(L"FATAL: Performance counter not available\n");
+        wprintf(L"FATAL: A problem occurred when trying to initialize the console\n");
         goto Cleanup;
     }
 
-    /* Initialize the PIC */
-    if (!PicInitialize())
-    {
-        wprintf(L"FATAL: Failed to initialize the PIC.\n");
-        goto Cleanup;
-    }
-
-    /* Initialize the PIT */
-    if (!PitInitialize())
+    /* Initialize the emulator */
+    if (!EmulatorInitialize(ConsoleInput, ConsoleOutput))
     {
-        wprintf(L"FATAL: Failed to initialize the PIT.\n");
+        wprintf(L"FATAL: Failed to initialize the emulator\n");
         goto Cleanup;
     }
 
-    /* Initialize the CMOS */
-    if (!CmosInitialize())
+    /* Initialize the performance counter (needed for hardware timers) */
+    if (!QueryPerformanceFrequency(&Frequency))
     {
-        wprintf(L"FATAL: Failed to initialize the VDM CMOS.\n");
+        wprintf(L"FATAL: Performance counter not available\n");
         goto Cleanup;
     }
 
-    /* Initialize the PC Speaker */
-    SpeakerInitialize();
-
     /* Initialize the system BIOS */
-    if (!BiosInitialize())
+    if (!BiosInitialize(ConsoleInput, ConsoleOutput))
     {
         wprintf(L"FATAL: Failed to initialize the VDM BIOS.\n");
         goto Cleanup;
     }
 
     /* Initialize the VDM DOS kernel */
-    if (!DosInitialize())
+    if (!DosInitialize(NULL))
     {
         wprintf(L"FATAL: Failed to initialize the VDM DOS kernel.\n");
         goto Cleanup;
@@ -168,7 +255,11 @@ INT wmain(INT argc, WCHAR *argv[])
     QueryPerformanceCounter(&StartPerfCount);
 
     /* Set the different last counts to the starting count */
-    LastClockUpdate = LastVerticalRefresh = LastCyclePrintout = StartTickCount;
+    LastClockUpdate = LastVerticalRefresh =
+#ifdef IPS_DISPLAY
+    LastCyclePrintout =
+#endif
+    StartTickCount;
 
     /* Set the last timer ticks to the current time */
     LastTimerTick = LastRtcTick = StartPerfCount;
@@ -176,12 +267,15 @@ INT wmain(INT argc, WCHAR *argv[])
     /* Main loop */
     while (VdmRunning)
     {
+#ifdef WORKING_TIMER
         DWORD PitResolution = PitGetResolution();
+#endif
         DWORD RtcFrequency = RtcGetTicksPerSecond();
 
         /* Get the current number of ticks */
         CurrentTickCount = GetTickCount();
 
+#ifdef WORKING_TIMER
         if ((PitResolution <= 1000) && (RtcFrequency <= 1000))
         {
             /* Calculate the approximate performance counter value instead */
@@ -190,6 +284,7 @@ INT wmain(INT argc, WCHAR *argv[])
                                * (Frequency.QuadPart / 1000);
         }
         else
+#endif
         {
             /* Get the current performance counter value */
             QueryPerformanceCounter(&Counter);
@@ -202,7 +297,7 @@ INT wmain(INT argc, WCHAR *argv[])
         /* Update the PIT */
         if (TimerTicks > 0)
         {
-            PitDecrementCount(TimerTicks);
+            PitClock(TimerTicks);
             LastTimerTick = Counter;
         }
 
@@ -242,25 +337,28 @@ INT wmain(INT argc, WCHAR *argv[])
         for (i = 0; (i < STEPS_PER_CYCLE) && VdmRunning; i++)
         {
             EmulatorStep();
+#ifdef IPS_DISPLAY
             Cycles++;
+#endif
         }
 
+#ifdef IPS_DISPLAY
         if ((CurrentTickCount - LastCyclePrintout) >= 1000)
         {
-            DPRINT1("NTVDM: %lu Instructions Per Second\n", Cycles);
+            DPRINT1("NTVDM: %lu Instructions Per Second; TimerTicks = %I64d\n", Cycles, TimerTicks);
             LastCyclePrintout = CurrentTickCount;
             Cycles = 0;
         }
+#endif
     }
 
     /* Perform another screen refresh */
     VgaRefreshDisplay();
 
 Cleanup:
-    SpeakerCleanup();
     BiosCleanup();
-    CmosCleanup();
     EmulatorCleanup();
+    ConsoleCleanup();
 
     DPRINT1("\n\n\nNTVDM - Exiting...\n\n\n");