42b5f19c8d4175c2d2a02c287bd5656a7e7b45ec
[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 SpeakerChange = 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 // SpeakerChange = TRUE;
275 }
276
277 PitSetGate(2, !!(Port61hState & 0x01));
278
279 if ((OldPort61hState ^ Port61hState) & 0x02)
280 {
281 /* There were some change for the speaker... */
282 DPRINT("Speaker %s\n", Port61hState & 0x02 ? "on" : "off");
283 // SpeakerChange = TRUE;
284 }
285 // if (SpeakerChange) SpeakerChange();
286 SpeakerChange();
287 }
288
289 static VOID WINAPI PitChan0Out(LPVOID Param, BOOLEAN State)
290 {
291 if (State)
292 {
293 DPRINT("PicInterruptRequest\n");
294 PicInterruptRequest(0); // Raise IRQ 0
295 }
296 // else < Lower IRQ 0 >
297 }
298
299 static VOID WINAPI PitChan1Out(LPVOID Param, BOOLEAN State)
300 {
301 #if 0
302 if (State)
303 {
304 /* Set bit 4 of Port 61h */
305 Port61hState |= 1 << 4;
306 }
307 else
308 {
309 /* Clear bit 4 of Port 61h */
310 Port61hState &= ~(1 << 4);
311 }
312 #else
313 Port61hState = (Port61hState & 0xEF) | (State << 4);
314 #endif
315 }
316
317 static VOID WINAPI PitChan2Out(LPVOID Param, BOOLEAN State)
318 {
319 // BYTE OldPort61hState = Port61hState;
320
321 #if 0
322 if (State)
323 {
324 /* Set bit 5 of Port 61h */
325 Port61hState |= 1 << 5;
326 }
327 else
328 {
329 /* Clear bit 5 of Port 61h */
330 Port61hState &= ~(1 << 5);
331 }
332 #else
333 Port61hState = (Port61hState & 0xDF) | (State << 5);
334 #endif
335 DPRINT("Speaker PIT out\n");
336 // if ((OldPort61hState ^ Port61hState) & 0x20)
337 // SpeakerChange();
338 }
339
340
341 static DWORD
342 WINAPI
343 PumpConsoleInput(LPVOID Parameter)
344 {
345 HANDLE ConsoleInput = (HANDLE)Parameter;
346 INPUT_RECORD InputRecord;
347 DWORD Count;
348
349 while (VdmRunning)
350 {
351 /* Make sure the task event is signaled */
352 WaitForSingleObject(VdmTaskEvent, INFINITE);
353
354 /* Wait for an input record */
355 if (!ReadConsoleInput(ConsoleInput, &InputRecord, 1, &Count))
356 {
357 DWORD LastError = GetLastError();
358 DPRINT1("Error reading console input (0x%p, %lu) - Error %lu\n", ConsoleInput, Count, LastError);
359 return LastError;
360 }
361
362 ASSERT(Count != 0);
363
364 /* Check the event type */
365 switch (InputRecord.EventType)
366 {
367 /*
368 * Hardware events
369 */
370 case KEY_EVENT:
371 KeyboardEventHandler(&InputRecord.Event.KeyEvent);
372 break;
373
374 case MOUSE_EVENT:
375 MouseEventHandler(&InputRecord.Event.MouseEvent);
376 break;
377
378 case WINDOW_BUFFER_SIZE_EVENT:
379 ScreenEventHandler(&InputRecord.Event.WindowBufferSizeEvent);
380 break;
381
382 /*
383 * Interface events
384 */
385 case MENU_EVENT:
386 MenuEventHandler(&InputRecord.Event.MenuEvent);
387 break;
388
389 case FOCUS_EVENT:
390 FocusEventHandler(&InputRecord.Event.FocusEvent);
391 break;
392
393 default:
394 break;
395 }
396 }
397
398 return 0;
399 }
400
401 static VOID EnableExtraHardware(HANDLE ConsoleInput)
402 {
403 DWORD ConInMode;
404
405 if (GetConsoleMode(ConsoleInput, &ConInMode))
406 {
407 #if 0
408 // GetNumberOfConsoleMouseButtons();
409 // GetSystemMetrics(SM_CMOUSEBUTTONS);
410 // GetSystemMetrics(SM_MOUSEPRESENT);
411 if (MousePresent)
412 {
413 #endif
414 /* Support mouse input events if there is a mouse on the system */
415 ConInMode |= ENABLE_MOUSE_INPUT;
416 #if 0
417 }
418 else
419 {
420 /* Do not support mouse input events if there is no mouse on the system */
421 ConInMode &= ~ENABLE_MOUSE_INPUT;
422 }
423 #endif
424
425 SetConsoleMode(ConsoleInput, ConInMode);
426 }
427 }
428
429 /* PUBLIC FUNCTIONS ***********************************************************/
430
431 VOID DumpMemory(VOID)
432 {
433 static ULONG DumpNumber = 0;
434
435 HANDLE hFile;
436 WCHAR FileName[MAX_PATH];
437
438 #define LINE_SIZE 75 + 2
439 ULONG i;
440 PBYTE Ptr1, Ptr2;
441 CHAR LineBuffer[LINE_SIZE];
442 PCHAR Line;
443 SIZE_T LineSize;
444
445 /* Build a suitable file name */
446 _snwprintf(FileName, MAX_PATH, L"memdump%lu.txt", DumpNumber);
447 ++DumpNumber;
448
449 DPRINT1("Creating memory dump file '%S'...\n", FileName);
450
451 /* Always create the dump file */
452 hFile = CreateFileW(FileName,
453 GENERIC_WRITE,
454 0,
455 NULL,
456 CREATE_ALWAYS,
457 FILE_ATTRIBUTE_NORMAL,
458 NULL);
459
460 if (hFile == INVALID_HANDLE_VALUE)
461 {
462 DPRINT1("Error when creating '%S' for memory dumping, GetLastError() = %u\n",
463 FileName, GetLastError());
464 return;
465 }
466
467 /* Dump the VM memory */
468 SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
469 Ptr1 = Ptr2 = REAL_TO_PHYS(NULL);
470 while (MAX_ADDRESS - (ULONG_PTR)PHYS_TO_REAL(Ptr1) > 0)
471 {
472 Ptr1 = Ptr2;
473 Line = LineBuffer;
474
475 /* Print the address */
476 Line += snprintf(Line, LINE_SIZE + LineBuffer - Line, "%08x ", PHYS_TO_REAL(Ptr1));
477
478 /* Print up to 16 bytes... */
479
480 /* ... in hexadecimal form first... */
481 i = 0;
482 while (i++ <= 0x0F && (MAX_ADDRESS - (ULONG_PTR)PHYS_TO_REAL(Ptr1) > 0))
483 {
484 Line += snprintf(Line, LINE_SIZE + LineBuffer - Line, " %02x", *Ptr1);
485 ++Ptr1;
486 }
487
488 /* ... align with spaces if needed... */
489 RtlFillMemory(Line, 0x0F + 4 - i, ' ');
490 Line += 0x0F + 4 - i;
491
492 /* ... then in character form. */
493 i = 0;
494 while (i++ <= 0x0F && (MAX_ADDRESS - (ULONG_PTR)PHYS_TO_REAL(Ptr2) > 0))
495 {
496 *Line++ = ((*Ptr2 >= 0x20 && *Ptr2 <= 0x7E) || (*Ptr2 >= 0x80 && *Ptr2 < 0xFF) ? *Ptr2 : '.');
497 ++Ptr2;
498 }
499
500 /* Newline */
501 *Line++ = '\r';
502 *Line++ = '\n';
503
504 /* Finally write the line to the file */
505 LineSize = Line - LineBuffer;
506 WriteFile(hFile, LineBuffer, LineSize, &LineSize, NULL);
507 }
508
509 /* Close the file */
510 CloseHandle(hFile);
511
512 DPRINT1("Memory dump done\n");
513 }
514
515 BOOLEAN EmulatorInitialize(HANDLE ConsoleInput, HANDLE ConsoleOutput)
516 {
517 /* Allocate memory for the 16-bit address space */
518 BaseAddress = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_ADDRESS);
519 if (BaseAddress == NULL)
520 {
521 wprintf(L"FATAL: Failed to allocate VDM memory.\n");
522 return FALSE;
523 }
524
525 /* Initialize I/O ports */
526 /* Initialize RAM */
527
528 /* Initialize the internal clock */
529 if (!ClockInitialize())
530 {
531 wprintf(L"FATAL: Failed to initialize the clock\n");
532 return FALSE;
533 }
534
535 /* Initialize the CPU */
536 Fast486Initialize(&EmulatorContext,
537 EmulatorReadMemory,
538 EmulatorWriteMemory,
539 EmulatorReadIo,
540 EmulatorWriteIo,
541 NULL,
542 EmulatorBiosOperation,
543 EmulatorIntAcknowledge,
544 NULL /* TODO: Use a TLB */);
545
546 /* Initialize DMA */
547
548 /* Initialize the PIC, the PIT, the CMOS and the PC Speaker */
549 PicInitialize();
550 PitInitialize();
551 CmosInitialize();
552 SpeakerInitialize();
553
554 /* Set output functions */
555 PitSetOutFunction(0, NULL, PitChan0Out);
556 PitSetOutFunction(1, NULL, PitChan1Out);
557 PitSetOutFunction(2, NULL, PitChan2Out);
558
559 /* Register the I/O Ports */
560 RegisterIoPort(CONTROL_SYSTEM_PORT61H, Port61hRead, Port61hWrite);
561
562 /* Set the console input mode */
563 // FIXME: Activate ENABLE_WINDOW_INPUT when we will want to perform actions
564 // upon console window events (screen buffer resize, ...).
565 SetConsoleMode(ConsoleInput, ENABLE_PROCESSED_INPUT /* | ENABLE_WINDOW_INPUT */);
566 // SetConsoleMode(ConsoleOutput, ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
567
568 /**/EnableExtraHardware(ConsoleInput);/**/
569
570 /* Initialize the PS/2 port */
571 PS2Initialize();
572
573 /* Initialize the keyboard and mouse and connect them to their PS/2 ports */
574 KeyboardInit(0);
575 MouseInit(1);
576
577 /**************** ATTACH INPUT WITH CONSOLE *****************/
578 /* Start the input thread */
579 InputThread = CreateThread(NULL, 0, &PumpConsoleInput, ConsoleInput, 0, NULL);
580 if (InputThread == NULL)
581 {
582 DisplayMessage(L"Failed to create the console input thread.");
583 return FALSE;
584 }
585 /************************************************************/
586
587 /* Initialize the VGA */
588 if (!VgaInitialize(ConsoleOutput))
589 {
590 DisplayMessage(L"Failed to initialize VGA support.");
591 return FALSE;
592 }
593
594 /* Initialize the software callback system and register the emulator BOPs */
595 InitializeCallbacks();
596 RegisterBop(BOP_DEBUGGER , EmulatorDebugBreakBop);
597 RegisterBop(BOP_UNSIMULATE, EmulatorUnsimulateBop);
598
599 /* Initialize VDD support */
600 VDDSupInitialize();
601
602 return TRUE;
603 }
604
605 VOID EmulatorCleanup(VOID)
606 {
607 VgaCleanup();
608
609 /* Close the input thread handle */
610 if (InputThread != NULL) CloseHandle(InputThread);
611 InputThread = NULL;
612
613 PS2Cleanup();
614
615 SpeakerCleanup();
616 CmosCleanup();
617 // PitCleanup();
618 // PicCleanup();
619
620 // Fast486Cleanup();
621
622 /* Free the memory allocated for the 16-bit address space */
623 if (BaseAddress != NULL) HeapFree(GetProcessHeap(), 0, BaseAddress);
624 }
625
626
627
628 VOID
629 WINAPI
630 VDDSimulate16(VOID)
631 {
632 EmulatorSimulate();
633 }
634
635 VOID
636 WINAPI
637 VDDTerminateVDM(VOID)
638 {
639 /* Stop the VDM */
640 EmulatorTerminate();
641 }
642
643 PBYTE
644 WINAPI
645 Sim32pGetVDMPointer(IN ULONG Address,
646 IN BOOLEAN ProtectedMode)
647 {
648 // FIXME
649 UNREFERENCED_PARAMETER(ProtectedMode);
650
651 /*
652 * HIWORD(Address) == Segment (if ProtectedMode == FALSE)
653 * or Selector (if ProtectedMode == TRUE )
654 * LOWORD(Address) == Offset
655 */
656 return (PBYTE)FAR_POINTER(Address);
657 }
658
659 PBYTE
660 WINAPI
661 MGetVdmPointer(IN ULONG Address,
662 IN ULONG Size,
663 IN BOOLEAN ProtectedMode)
664 {
665 UNREFERENCED_PARAMETER(Size);
666 return Sim32pGetVDMPointer(Address, ProtectedMode);
667 }
668
669 PVOID
670 WINAPI
671 VdmMapFlat(IN USHORT Segment,
672 IN ULONG Offset,
673 IN VDM_MODE Mode)
674 {
675 // FIXME
676 UNREFERENCED_PARAMETER(Mode);
677
678 return SEG_OFF_TO_PTR(Segment, Offset);
679 }
680
681 BOOL
682 WINAPI
683 VdmFlushCache(IN USHORT Segment,
684 IN ULONG Offset,
685 IN ULONG Size,
686 IN VDM_MODE Mode)
687 {
688 // FIXME
689 UNIMPLEMENTED;
690 return TRUE;
691 }
692
693 BOOL
694 WINAPI
695 VdmUnmapFlat(IN USHORT Segment,
696 IN ULONG Offset,
697 IN PVOID Buffer,
698 IN VDM_MODE Mode)
699 {
700 // FIXME
701 UNIMPLEMENTED;
702 return TRUE;
703 }
704
705 /* EOF */