[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 VOID DumpMemory(VOID)
434 {
435 static ULONG DumpNumber = 0;
436
437 HANDLE hFile;
438 WCHAR FileName[MAX_PATH];
439
440 #define LINE_SIZE 75 + 2
441 ULONG i;
442 PBYTE Ptr1, Ptr2;
443 CHAR LineBuffer[LINE_SIZE];
444 PCHAR Line;
445 SIZE_T LineSize;
446
447 /* Build a suitable file name */
448 _snwprintf(FileName, MAX_PATH, L"memdump%lu.txt", DumpNumber);
449 ++DumpNumber;
450
451 DPRINT1("Creating memory dump file '%S'...\n", FileName);
452
453 /* Always create the dump file */
454 hFile = CreateFileW(FileName,
455 GENERIC_WRITE,
456 0,
457 NULL,
458 CREATE_ALWAYS,
459 FILE_ATTRIBUTE_NORMAL,
460 NULL);
461
462 if (hFile == INVALID_HANDLE_VALUE)
463 {
464 DPRINT1("Error when creating '%S' for memory dumping, GetLastError() = %u\n",
465 FileName, GetLastError());
466 return;
467 }
468
469 /* Dump the VM memory */
470 SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
471 Ptr1 = Ptr2 = REAL_TO_PHYS(NULL);
472 while (MAX_ADDRESS - (ULONG_PTR)PHYS_TO_REAL(Ptr1) > 0)
473 {
474 Ptr1 = Ptr2;
475 Line = LineBuffer;
476
477 /* Print the address */
478 Line += snprintf(Line, LINE_SIZE + LineBuffer - Line, "%08x ", PHYS_TO_REAL(Ptr1));
479
480 /* Print up to 16 bytes... */
481
482 /* ... in hexadecimal form first... */
483 i = 0;
484 while (i++ <= 0x0F && (MAX_ADDRESS - (ULONG_PTR)PHYS_TO_REAL(Ptr1) > 0))
485 {
486 Line += snprintf(Line, LINE_SIZE + LineBuffer - Line, " %02x", *Ptr1);
487 ++Ptr1;
488 }
489
490 /* ... align with spaces if needed... */
491 RtlFillMemory(Line, 0x0F + 4 - i, ' ');
492 Line += 0x0F + 4 - i;
493
494 /* ... then in character form. */
495 i = 0;
496 while (i++ <= 0x0F && (MAX_ADDRESS - (ULONG_PTR)PHYS_TO_REAL(Ptr2) > 0))
497 {
498 *Line++ = ((*Ptr2 >= 0x20 && *Ptr2 <= 0x7E) || (*Ptr2 >= 0x80 && *Ptr2 < 0xFF) ? *Ptr2 : '.');
499 ++Ptr2;
500 }
501
502 /* Newline */
503 *Line++ = '\r';
504 *Line++ = '\n';
505
506 /* Finally write the line to the file */
507 LineSize = Line - LineBuffer;
508 WriteFile(hFile, LineBuffer, LineSize, &LineSize, NULL);
509 }
510
511 /* Close the file */
512 CloseHandle(hFile);
513
514 DPRINT1("Memory dump done\n");
515 }
516
517 BOOLEAN EmulatorInitialize(HANDLE ConsoleInput, HANDLE ConsoleOutput)
518 {
519 /* Allocate memory for the 16-bit address space */
520 BaseAddress = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_ADDRESS);
521 if (BaseAddress == NULL)
522 {
523 wprintf(L"FATAL: Failed to allocate VDM memory.\n");
524 return FALSE;
525 }
526
527 /* Initialize I/O ports */
528 /* Initialize RAM */
529
530 /* Initialize the internal clock */
531 if (!ClockInitialize())
532 {
533 wprintf(L"FATAL: Failed to initialize the clock\n");
534 return FALSE;
535 }
536
537 /* Initialize the CPU */
538 Fast486Initialize(&EmulatorContext,
539 EmulatorReadMemory,
540 EmulatorWriteMemory,
541 EmulatorReadIo,
542 EmulatorWriteIo,
543 NULL,
544 EmulatorBiosOperation,
545 EmulatorIntAcknowledge,
546 NULL /* TODO: Use a TLB */);
547
548 /* Initialize DMA */
549
550 /* Initialize the PIC, the PIT, the CMOS and the PC Speaker */
551 PicInitialize();
552 PitInitialize();
553 CmosInitialize();
554 SpeakerInitialize();
555
556 /* Set output functions */
557 PitSetOutFunction(0, NULL, PitChan0Out);
558 PitSetOutFunction(1, NULL, PitChan1Out);
559 PitSetOutFunction(2, NULL, PitChan2Out);
560
561 /* Register the I/O Ports */
562 RegisterIoPort(CONTROL_SYSTEM_PORT61H, Port61hRead, Port61hWrite);
563
564 /* Set the console input mode */
565 // FIXME: Activate ENABLE_WINDOW_INPUT when we will want to perform actions
566 // upon console window events (screen buffer resize, ...).
567 SetConsoleMode(ConsoleInput, ENABLE_PROCESSED_INPUT /* | ENABLE_WINDOW_INPUT */);
568 // SetConsoleMode(ConsoleOutput, ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
569
570 /**/EnableExtraHardware(ConsoleInput);/**/
571
572 /* Initialize the PS/2 port */
573 PS2Initialize();
574
575 /* Initialize the keyboard and mouse and connect them to their PS/2 ports */
576 KeyboardInit(0);
577 MouseInit(1);
578
579 /**************** ATTACH INPUT WITH CONSOLE *****************/
580 /* Start the input thread */
581 InputThread = CreateThread(NULL, 0, &PumpConsoleInput, ConsoleInput, 0, NULL);
582 if (InputThread == NULL)
583 {
584 DisplayMessage(L"Failed to create the console input thread.");
585 return FALSE;
586 }
587 /************************************************************/
588
589 /* Initialize the VGA */
590 if (!VgaInitialize(ConsoleOutput))
591 {
592 DisplayMessage(L"Failed to initialize VGA support.");
593 return FALSE;
594 }
595
596 /* Initialize the software callback system and register the emulator BOPs */
597 InitializeCallbacks();
598 RegisterBop(BOP_DEBUGGER , EmulatorDebugBreakBop);
599 RegisterBop(BOP_UNSIMULATE, EmulatorUnsimulateBop);
600
601 /* Initialize VDD support */
602 VDDSupInitialize();
603
604 return TRUE;
605 }
606
607 VOID EmulatorCleanup(VOID)
608 {
609 VgaCleanup();
610
611 /* Close the input thread handle */
612 if (InputThread != NULL) CloseHandle(InputThread);
613 InputThread = NULL;
614
615 PS2Cleanup();
616
617 SpeakerCleanup();
618 CmosCleanup();
619 // PitCleanup();
620 // PicCleanup();
621
622 // Fast486Cleanup();
623
624 /* Free the memory allocated for the 16-bit address space */
625 if (BaseAddress != NULL) HeapFree(GetProcessHeap(), 0, BaseAddress);
626 }
627
628
629
630 VOID
631 WINAPI
632 VDDSimulate16(VOID)
633 {
634 EmulatorSimulate();
635 }
636
637 VOID
638 WINAPI
639 VDDTerminateVDM(VOID)
640 {
641 /* Stop the VDM */
642 EmulatorTerminate();
643 }
644
645 PBYTE
646 WINAPI
647 Sim32pGetVDMPointer(IN ULONG Address,
648 IN BOOLEAN ProtectedMode)
649 {
650 // FIXME
651 UNREFERENCED_PARAMETER(ProtectedMode);
652
653 /*
654 * HIWORD(Address) == Segment (if ProtectedMode == FALSE)
655 * or Selector (if ProtectedMode == TRUE )
656 * LOWORD(Address) == Offset
657 */
658 return (PBYTE)FAR_POINTER(Address);
659 }
660
661 PBYTE
662 WINAPI
663 MGetVdmPointer(IN ULONG Address,
664 IN ULONG Size,
665 IN BOOLEAN ProtectedMode)
666 {
667 UNREFERENCED_PARAMETER(Size);
668 return Sim32pGetVDMPointer(Address, ProtectedMode);
669 }
670
671 PVOID
672 WINAPI
673 VdmMapFlat(IN USHORT Segment,
674 IN ULONG Offset,
675 IN VDM_MODE Mode)
676 {
677 // FIXME
678 UNREFERENCED_PARAMETER(Mode);
679
680 return SEG_OFF_TO_PTR(Segment, Offset);
681 }
682
683 BOOL
684 WINAPI
685 VdmFlushCache(IN USHORT Segment,
686 IN ULONG Offset,
687 IN ULONG Size,
688 IN VDM_MODE Mode)
689 {
690 // FIXME
691 UNIMPLEMENTED;
692 return TRUE;
693 }
694
695 BOOL
696 WINAPI
697 VdmUnmapFlat(IN USHORT Segment,
698 IN ULONG Offset,
699 IN PVOID Buffer,
700 IN VDM_MODE Mode)
701 {
702 // FIXME
703 UNIMPLEMENTED;
704 return TRUE;
705 }
706
707 /* EOF */