[NTVDM]
[reactos.git] / reactos / subsystems / ntvdm / emulator.c
1 /*
2 * COPYRIGHT: GPL - See COPYING in the top level directory
3 * PROJECT: ReactOS Virtual DOS Machine
4 * FILE: emulator.c
5 * PURPOSE: Minimal x86 machine emulator for the VDM
6 * PROGRAMMERS: Aleksandar Andrejevic <theflash AT sdf DOT lonestar DOT org>
7 */
8
9 /* INCLUDES *******************************************************************/
10
11 #define NDEBUG
12
13 #include "emulator.h"
14 #include "callback.h"
15
16 #include "clock.h"
17 #include "bios/rom.h"
18 #include "hardware/cmos.h"
19 #include "hardware/keyboard.h"
20 #include "hardware/mouse.h"
21 #include "hardware/pic.h"
22 #include "hardware/ps2.h"
23 #include "hardware/speaker.h"
24 #include "hardware/timer.h"
25 #include "hardware/vga.h"
26
27 #include "bop.h"
28 #include "vddsup.h"
29 #include "io.h"
30
31 #include <isvbop.h>
32
33 /* PRIVATE VARIABLES **********************************************************/
34
35 FAST486_STATE EmulatorContext;
36 BOOLEAN CpuSimulate = FALSE;
37
38 /* No more than 'MaxCpuCallLevel' recursive CPU calls are allowed */
39 static const INT MaxCpuCallLevel = 32;
40 static INT CpuCallLevel = 0;
41
42 LPVOID BaseAddress = NULL;
43 BOOLEAN VdmRunning = TRUE;
44
45 static BOOLEAN A20Line = FALSE;
46 static BYTE Port61hState = 0x00;
47
48 static HANDLE InputThread = NULL;
49
50 LPCWSTR ExceptionName[] =
51 {
52 L"Division By Zero",
53 L"Debug",
54 L"Unexpected Error",
55 L"Breakpoint",
56 L"Integer Overflow",
57 L"Bound Range Exceeded",
58 L"Invalid Opcode",
59 L"FPU Not Available"
60 };
61
62 /* BOP Identifiers */
63 #define BOP_DEBUGGER 0x56 // Break into the debugger from a 16-bit app
64
65 /* PRIVATE FUNCTIONS **********************************************************/
66
67 VOID WINAPI EmulatorReadMemory(PFAST486_STATE State, ULONG Address, PVOID Buffer, ULONG Size)
68 {
69 UNREFERENCED_PARAMETER(State);
70
71 // BIG HACK!!!! To make BIOS images working correctly,
72 // until Aleksander rewrites memory management!!
73 if (Address >= 0xFFFFFFF0) Address -= 0xFFF00000;
74
75 /* If the A20 line is disabled, mask bit 20 */
76 if (!A20Line) Address &= ~(1 << 20);
77
78 /* Make sure the requested address is valid */
79 if ((Address + Size) >= MAX_ADDRESS) return;
80
81 /*
82 * Check if we are going to read the VGA memory and
83 * copy it into the virtual address space if needed.
84 */
85 if (((Address + Size) >= VgaGetVideoBaseAddress())
86 && (Address < VgaGetVideoLimitAddress()))
87 {
88 DWORD VgaAddress = max(Address, VgaGetVideoBaseAddress());
89 DWORD ActualSize = min(Address + Size - 1, VgaGetVideoLimitAddress())
90 - VgaAddress + 1;
91 LPBYTE DestBuffer = (LPBYTE)REAL_TO_PHYS(VgaAddress);
92
93 /* Read from the VGA memory */
94 VgaReadMemory(VgaAddress, DestBuffer, ActualSize);
95 }
96
97 /* Read the data from the virtual address space and store it in the buffer */
98 RtlCopyMemory(Buffer, REAL_TO_PHYS(Address), Size);
99 }
100
101 VOID WINAPI EmulatorWriteMemory(PFAST486_STATE State, ULONG Address, PVOID Buffer, ULONG Size)
102 {
103 UNREFERENCED_PARAMETER(State);
104
105 // BIG HACK!!!! To make BIOS images working correctly,
106 // until Aleksander rewrites memory management!!
107 if (Address >= 0xFFFFFFF0) Address -= 0xFFF00000;
108
109 /* If the A20 line is disabled, mask bit 20 */
110 if (!A20Line) Address &= ~(1 << 20);
111
112 /* Make sure the requested address is valid */
113 if ((Address + Size) >= MAX_ADDRESS) return;
114
115 /* Make sure we don't write to the ROM area */
116 if ((Address + Size) >= ROM_AREA_START && (Address < ROM_AREA_END)) return;
117
118 /* Read the data from the buffer and store it in the virtual address space */
119 RtlCopyMemory(REAL_TO_PHYS(Address), Buffer, Size);
120
121 /*
122 * Check if we modified the VGA memory.
123 */
124 if (((Address + Size) >= VgaGetVideoBaseAddress())
125 && (Address < VgaGetVideoLimitAddress()))
126 {
127 DWORD VgaAddress = max(Address, VgaGetVideoBaseAddress());
128 DWORD ActualSize = min(Address + Size - 1, VgaGetVideoLimitAddress())
129 - VgaAddress + 1;
130 LPBYTE SrcBuffer = (LPBYTE)REAL_TO_PHYS(VgaAddress);
131
132 /* Write to the VGA memory */
133 VgaWriteMemory(VgaAddress, SrcBuffer, ActualSize);
134 }
135 }
136
137 UCHAR WINAPI EmulatorIntAcknowledge(PFAST486_STATE State)
138 {
139 UNREFERENCED_PARAMETER(State);
140
141 /* Get the interrupt number from the PIC */
142 return PicGetInterrupt();
143 }
144
145 VOID EmulatorException(BYTE ExceptionNumber, LPWORD Stack)
146 {
147 WORD CodeSegment, InstructionPointer;
148 PBYTE Opcode;
149
150 ASSERT(ExceptionNumber < 8);
151
152 /* Get the CS:IP */
153 InstructionPointer = Stack[STACK_IP];
154 CodeSegment = Stack[STACK_CS];
155 Opcode = (PBYTE)SEG_OFF_TO_PTR(CodeSegment, InstructionPointer);
156
157 /* Display a message to the user */
158 DisplayMessage(L"Exception: %s occured at %04X:%04X\n"
159 L"Opcode: %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X",
160 ExceptionName[ExceptionNumber],
161 CodeSegment,
162 InstructionPointer,
163 Opcode[0],
164 Opcode[1],
165 Opcode[2],
166 Opcode[3],
167 Opcode[4],
168 Opcode[5],
169 Opcode[6],
170 Opcode[7],
171 Opcode[8],
172 Opcode[9]);
173
174 /* Stop the VDM */
175 EmulatorTerminate();
176 return;
177 }
178
179 // FIXME: This function assumes 16-bit mode!!!
180 VOID EmulatorExecute(WORD Segment, WORD Offset)
181 {
182 /* Tell Fast486 to move the instruction pointer */
183 Fast486ExecuteAt(&EmulatorContext, Segment, Offset);
184 }
185
186 VOID EmulatorStep(VOID)
187 {
188 /* Dump the state for debugging purposes */
189 // Fast486DumpState(&EmulatorContext);
190
191 /* Execute the next instruction */
192 Fast486StepInto(&EmulatorContext);
193 }
194
195 VOID EmulatorSimulate(VOID)
196 {
197 if (CpuCallLevel > MaxCpuCallLevel)
198 {
199 DisplayMessage(L"Too many CPU levels of recursion (%d, expected maximum %d)",
200 CpuCallLevel, MaxCpuCallLevel);
201
202 /* Stop the VDM */
203 EmulatorTerminate();
204 return;
205 }
206 CpuCallLevel++;
207
208 CpuSimulate = TRUE;
209 while (VdmRunning && CpuSimulate) ClockUpdate();
210
211 CpuCallLevel--;
212 if (CpuCallLevel < 0) CpuCallLevel = 0;
213
214 /* This takes into account for reentrance */
215 CpuSimulate = TRUE;
216 }
217
218 VOID EmulatorUnsimulate(VOID)
219 {
220 /* Stop simulation */
221 CpuSimulate = FALSE;
222 }
223
224 VOID EmulatorTerminate(VOID)
225 {
226 /* Stop the VDM */
227 VdmRunning = FALSE;
228 }
229
230 VOID EmulatorInterrupt(BYTE Number)
231 {
232 /* Call the Fast486 API */
233 Fast486Interrupt(&EmulatorContext, Number);
234 }
235
236 VOID EmulatorInterruptSignal(VOID)
237 {
238 /* Call the Fast486 API */
239 Fast486InterruptSignal(&EmulatorContext);
240 }
241
242 VOID EmulatorSetA20(BOOLEAN Enabled)
243 {
244 A20Line = Enabled;
245 }
246
247 static VOID WINAPI EmulatorDebugBreakBop(LPWORD Stack)
248 {
249 DPRINT1("NTVDM: BOP_DEBUGGER\n");
250 DebugBreak();
251 }
252
253 static VOID WINAPI EmulatorUnsimulateBop(LPWORD Stack)
254 {
255 EmulatorUnsimulate();
256 }
257
258 static BYTE WINAPI Port61hRead(ULONG Port)
259 {
260 return Port61hState;
261 }
262
263 static VOID WINAPI Port61hWrite(ULONG Port, BYTE Data)
264 {
265 // BOOLEAN SpeakerStateChange = FALSE;
266 BYTE OldPort61hState = Port61hState;
267
268 /* Only the four lowest bytes can be written */
269 Port61hState = (Port61hState & 0xF0) | (Data & 0x0F);
270
271 if ((OldPort61hState ^ Port61hState) & 0x01)
272 {
273 DPRINT("PIT 2 Gate %s\n", Port61hState & 0x01 ? "on" : "off");
274 PitSetGate(2, !!(Port61hState & 0x01));
275 // SpeakerStateChange = TRUE;
276 }
277
278 if ((OldPort61hState ^ Port61hState) & 0x02)
279 {
280 /* There were some change for the speaker... */
281 DPRINT("Speaker %s\n", Port61hState & 0x02 ? "on" : "off");
282 // SpeakerStateChange = TRUE;
283 }
284 // if (SpeakerStateChange) SpeakerChange();
285 SpeakerChange();
286 }
287
288 static VOID WINAPI PitChan0Out(LPVOID Param, BOOLEAN State)
289 {
290 if (State)
291 {
292 DPRINT("PicInterruptRequest\n");
293 PicInterruptRequest(0); // Raise IRQ 0
294 }
295 // else < Lower IRQ 0 >
296 }
297
298 static VOID WINAPI PitChan1Out(LPVOID Param, BOOLEAN State)
299 {
300 #if 0
301 if (State)
302 {
303 /* Set bit 4 of Port 61h */
304 Port61hState |= 1 << 4;
305 }
306 else
307 {
308 /* Clear bit 4 of Port 61h */
309 Port61hState &= ~(1 << 4);
310 }
311 #else
312 Port61hState = (Port61hState & 0xEF) | (State << 4);
313 #endif
314 }
315
316 static VOID WINAPI PitChan2Out(LPVOID Param, BOOLEAN State)
317 {
318 BYTE OldPort61hState = Port61hState;
319
320 #if 0
321 if (State)
322 {
323 /* Set bit 5 of Port 61h */
324 Port61hState |= 1 << 5;
325 }
326 else
327 {
328 /* Clear bit 5 of Port 61h */
329 Port61hState &= ~(1 << 5);
330 }
331 #else
332 Port61hState = (Port61hState & 0xDF) | (State << 5);
333 #endif
334
335 if ((OldPort61hState ^ Port61hState) & 0x20)
336 {
337 DPRINT("PitChan2Out -- Port61hState changed\n");
338 SpeakerChange();
339 }
340 }
341
342
343 static DWORD
344 WINAPI
345 PumpConsoleInput(LPVOID Parameter)
346 {
347 HANDLE ConsoleInput = (HANDLE)Parameter;
348 INPUT_RECORD InputRecord;
349 DWORD Count;
350
351 while (VdmRunning)
352 {
353 /* Make sure the task event is signaled */
354 WaitForSingleObject(VdmTaskEvent, INFINITE);
355
356 /* Wait for an input record */
357 if (!ReadConsoleInput(ConsoleInput, &InputRecord, 1, &Count))
358 {
359 DWORD LastError = GetLastError();
360 DPRINT1("Error reading console input (0x%p, %lu) - Error %lu\n", ConsoleInput, Count, LastError);
361 return LastError;
362 }
363
364 ASSERT(Count != 0);
365
366 /* Check the event type */
367 switch (InputRecord.EventType)
368 {
369 /*
370 * Hardware events
371 */
372 case KEY_EVENT:
373 KeyboardEventHandler(&InputRecord.Event.KeyEvent);
374 break;
375
376 case MOUSE_EVENT:
377 MouseEventHandler(&InputRecord.Event.MouseEvent);
378 break;
379
380 case WINDOW_BUFFER_SIZE_EVENT:
381 ScreenEventHandler(&InputRecord.Event.WindowBufferSizeEvent);
382 break;
383
384 /*
385 * Interface events
386 */
387 case MENU_EVENT:
388 MenuEventHandler(&InputRecord.Event.MenuEvent);
389 break;
390
391 case FOCUS_EVENT:
392 FocusEventHandler(&InputRecord.Event.FocusEvent);
393 break;
394
395 default:
396 break;
397 }
398 }
399
400 return 0;
401 }
402
403 static VOID EnableExtraHardware(HANDLE ConsoleInput)
404 {
405 DWORD ConInMode;
406
407 if (GetConsoleMode(ConsoleInput, &ConInMode))
408 {
409 #if 0
410 // GetNumberOfConsoleMouseButtons();
411 // GetSystemMetrics(SM_CMOUSEBUTTONS);
412 // GetSystemMetrics(SM_MOUSEPRESENT);
413 if (MousePresent)
414 {
415 #endif
416 /* Support mouse input events if there is a mouse on the system */
417 ConInMode |= ENABLE_MOUSE_INPUT;
418 #if 0
419 }
420 else
421 {
422 /* Do not support mouse input events if there is no mouse on the system */
423 ConInMode &= ~ENABLE_MOUSE_INPUT;
424 }
425 #endif
426
427 SetConsoleMode(ConsoleInput, ConInMode);
428 }
429 }
430
431 /* PUBLIC FUNCTIONS ***********************************************************/
432
433 static VOID
434 DumpMemoryRaw(HANDLE hFile)
435 {
436 PVOID Buffer;
437 SIZE_T Size;
438
439 /* Dump the VM memory */
440 SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
441 Buffer = REAL_TO_PHYS(NULL);
442 Size = MAX_ADDRESS - (ULONG_PTR)(NULL);
443 WriteFile(hFile, Buffer, Size, &Size, NULL);
444 }
445
446 static VOID
447 DumpMemoryTxt(HANDLE hFile)
448 {
449 #define LINE_SIZE 75 + 2
450 ULONG i;
451 PBYTE Ptr1, Ptr2;
452 CHAR LineBuffer[LINE_SIZE];
453 PCHAR Line;
454 SIZE_T LineSize;
455
456 /* Dump the VM memory */
457 SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
458 Ptr1 = Ptr2 = REAL_TO_PHYS(NULL);
459 while (MAX_ADDRESS - (ULONG_PTR)PHYS_TO_REAL(Ptr1) > 0)
460 {
461 Ptr1 = Ptr2;
462 Line = LineBuffer;
463
464 /* Print the address */
465 Line += snprintf(Line, LINE_SIZE + LineBuffer - Line, "%08x ", PHYS_TO_REAL(Ptr1));
466
467 /* Print up to 16 bytes... */
468
469 /* ... in hexadecimal form first... */
470 i = 0;
471 while (i++ <= 0x0F && (MAX_ADDRESS - (ULONG_PTR)PHYS_TO_REAL(Ptr1) > 0))
472 {
473 Line += snprintf(Line, LINE_SIZE + LineBuffer - Line, " %02x", *Ptr1);
474 ++Ptr1;
475 }
476
477 /* ... align with spaces if needed... */
478 RtlFillMemory(Line, 0x0F + 4 - i, ' ');
479 Line += 0x0F + 4 - i;
480
481 /* ... then in character form. */
482 i = 0;
483 while (i++ <= 0x0F && (MAX_ADDRESS - (ULONG_PTR)PHYS_TO_REAL(Ptr2) > 0))
484 {
485 *Line++ = ((*Ptr2 >= 0x20 && *Ptr2 <= 0x7E) || (*Ptr2 >= 0x80 && *Ptr2 < 0xFF) ? *Ptr2 : '.');
486 ++Ptr2;
487 }
488
489 /* Newline */
490 *Line++ = '\r';
491 *Line++ = '\n';
492
493 /* Finally write the line to the file */
494 LineSize = Line - LineBuffer;
495 WriteFile(hFile, LineBuffer, LineSize, &LineSize, NULL);
496 }
497 }
498
499 VOID DumpMemory(BOOLEAN TextFormat)
500 {
501 static ULONG DumpNumber = 0;
502
503 HANDLE hFile;
504 WCHAR FileName[MAX_PATH];
505
506 /* Build a suitable file name */
507 _snwprintf(FileName, MAX_PATH,
508 L"memdump%lu.%s",
509 DumpNumber,
510 TextFormat ? L"txt" : L"dat");
511 ++DumpNumber;
512
513 DPRINT1("Creating memory dump file '%S'...\n", FileName);
514
515 /* Always create the dump file */
516 hFile = CreateFileW(FileName,
517 GENERIC_WRITE,
518 0,
519 NULL,
520 CREATE_ALWAYS,
521 FILE_ATTRIBUTE_NORMAL,
522 NULL);
523
524 if (hFile == INVALID_HANDLE_VALUE)
525 {
526 DPRINT1("Error when creating '%S' for memory dumping, GetLastError() = %u\n",
527 FileName, GetLastError());
528 return;
529 }
530
531 /* Dump the VM memory in the chosen format */
532 if (TextFormat)
533 DumpMemoryTxt(hFile);
534 else
535 DumpMemoryRaw(hFile);
536
537 /* Close the file */
538 CloseHandle(hFile);
539
540 DPRINT1("Memory dump done\n");
541 }
542
543 BOOLEAN EmulatorInitialize(HANDLE ConsoleInput, HANDLE ConsoleOutput)
544 {
545 /* Allocate memory for the 16-bit address space */
546 BaseAddress = HeapAlloc(GetProcessHeap(), /*HEAP_ZERO_MEMORY*/ 0, MAX_ADDRESS);
547 if (BaseAddress == NULL)
548 {
549 wprintf(L"FATAL: Failed to allocate VDM memory.\n");
550 return FALSE;
551 }
552 // For diagnostics purposes!!
553 FillMemory(BaseAddress, MAX_ADDRESS, 0xFF);
554
555 /* Initialize I/O ports */
556 /* Initialize RAM */
557
558 /* Initialize the internal clock */
559 if (!ClockInitialize())
560 {
561 wprintf(L"FATAL: Failed to initialize the clock\n");
562 return FALSE;
563 }
564
565 /* Initialize the CPU */
566 Fast486Initialize(&EmulatorContext,
567 EmulatorReadMemory,
568 EmulatorWriteMemory,
569 EmulatorReadIo,
570 EmulatorWriteIo,
571 NULL,
572 EmulatorBiosOperation,
573 EmulatorIntAcknowledge,
574 NULL /* TODO: Use a TLB */);
575
576 /* Initialize DMA */
577
578 /* Initialize the PIC, the PIT, the CMOS and the PC Speaker */
579 PicInitialize();
580 PitInitialize();
581 CmosInitialize();
582 SpeakerInitialize();
583
584 /* Set output functions */
585 PitSetOutFunction(0, NULL, PitChan0Out);
586 PitSetOutFunction(1, NULL, PitChan1Out);
587 PitSetOutFunction(2, NULL, PitChan2Out);
588
589 /* Register the I/O Ports */
590 RegisterIoPort(CONTROL_SYSTEM_PORT61H, Port61hRead, Port61hWrite);
591
592 /* Set the console input mode */
593 // FIXME: Activate ENABLE_WINDOW_INPUT when we will want to perform actions
594 // upon console window events (screen buffer resize, ...).
595 SetConsoleMode(ConsoleInput, ENABLE_PROCESSED_INPUT /* | ENABLE_WINDOW_INPUT */);
596 // SetConsoleMode(ConsoleOutput, ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
597
598 /**/EnableExtraHardware(ConsoleInput);/**/
599
600 /* Initialize the PS/2 port */
601 PS2Initialize();
602
603 /* Initialize the keyboard and mouse and connect them to their PS/2 ports */
604 KeyboardInit(0);
605 MouseInit(1);
606
607 /**************** ATTACH INPUT WITH CONSOLE *****************/
608 /* Start the input thread */
609 InputThread = CreateThread(NULL, 0, &PumpConsoleInput, ConsoleInput, 0, NULL);
610 if (InputThread == NULL)
611 {
612 DisplayMessage(L"Failed to create the console input thread.");
613 return FALSE;
614 }
615 /************************************************************/
616
617 /* Initialize the VGA */
618 if (!VgaInitialize(ConsoleOutput))
619 {
620 DisplayMessage(L"Failed to initialize VGA support.");
621 return FALSE;
622 }
623
624 /* Initialize the software callback system and register the emulator BOPs */
625 InitializeCallbacks();
626 RegisterBop(BOP_DEBUGGER , EmulatorDebugBreakBop);
627 RegisterBop(BOP_UNSIMULATE, EmulatorUnsimulateBop);
628
629 /* Initialize VDD support */
630 VDDSupInitialize();
631
632 return TRUE;
633 }
634
635 VOID EmulatorCleanup(VOID)
636 {
637 VgaCleanup();
638
639 /* Close the input thread handle */
640 if (InputThread != NULL) CloseHandle(InputThread);
641 InputThread = NULL;
642
643 PS2Cleanup();
644
645 SpeakerCleanup();
646 CmosCleanup();
647 // PitCleanup();
648 // PicCleanup();
649
650 // Fast486Cleanup();
651
652 /* Free the memory allocated for the 16-bit address space */
653 if (BaseAddress != NULL) HeapFree(GetProcessHeap(), 0, BaseAddress);
654 }
655
656
657
658 VOID
659 WINAPI
660 VDDSimulate16(VOID)
661 {
662 EmulatorSimulate();
663 }
664
665 VOID
666 WINAPI
667 VDDTerminateVDM(VOID)
668 {
669 /* Stop the VDM */
670 EmulatorTerminate();
671 }
672
673 PBYTE
674 WINAPI
675 Sim32pGetVDMPointer(IN ULONG Address,
676 IN BOOLEAN ProtectedMode)
677 {
678 // FIXME
679 UNREFERENCED_PARAMETER(ProtectedMode);
680
681 /*
682 * HIWORD(Address) == Segment (if ProtectedMode == FALSE)
683 * or Selector (if ProtectedMode == TRUE )
684 * LOWORD(Address) == Offset
685 */
686 return (PBYTE)FAR_POINTER(Address);
687 }
688
689 PBYTE
690 WINAPI
691 MGetVdmPointer(IN ULONG Address,
692 IN ULONG Size,
693 IN BOOLEAN ProtectedMode)
694 {
695 UNREFERENCED_PARAMETER(Size);
696 return Sim32pGetVDMPointer(Address, ProtectedMode);
697 }
698
699 PVOID
700 WINAPI
701 VdmMapFlat(IN USHORT Segment,
702 IN ULONG Offset,
703 IN VDM_MODE Mode)
704 {
705 // FIXME
706 UNREFERENCED_PARAMETER(Mode);
707
708 return SEG_OFF_TO_PTR(Segment, Offset);
709 }
710
711 BOOL
712 WINAPI
713 VdmFlushCache(IN USHORT Segment,
714 IN ULONG Offset,
715 IN ULONG Size,
716 IN VDM_MODE Mode)
717 {
718 // FIXME
719 UNIMPLEMENTED;
720 return TRUE;
721 }
722
723 BOOL
724 WINAPI
725 VdmUnmapFlat(IN USHORT Segment,
726 IN ULONG Offset,
727 IN PVOID Buffer,
728 IN VDM_MODE Mode)
729 {
730 // FIXME
731 UNIMPLEMENTED;
732 return TRUE;
733 }
734
735 /* EOF */