WM_PAINT(wParam) might be a valid HDC.
[wine/wine64.git] / dlls / winedos / dosvm.c
blob064c4f704a089a5682f40d8d69fa5f851b00a55a
1 /*
2 * DOS Virtual Machine
4 * Copyright 1998 Ove Kåven
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * Note: This code hasn't been completely cleaned up yet.
23 #include "config.h"
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34 #ifdef HAVE_SYS_TIME_H
35 # include <sys/time.h>
36 #endif
37 #include <sys/types.h>
39 #include "wine/winbase16.h"
40 #include "wine/exception.h"
41 #include "windef.h"
42 #include "winbase.h"
43 #include "wingdi.h"
44 #include "winuser.h"
45 #include "winnt.h"
46 #include "wincon.h"
48 #include "msdos.h"
49 #include "file.h"
50 #include "miscemu.h"
51 #include "dosexe.h"
52 #include "dosvm.h"
53 #include "stackframe.h"
54 #include "wine/debug.h"
55 #include "excpt.h"
57 WINE_DEFAULT_DEBUG_CHANNEL(int);
58 WINE_DECLARE_DEBUG_CHANNEL(module);
59 WINE_DECLARE_DEBUG_CHANNEL(relay);
61 WORD DOSVM_psp = 0;
62 WORD DOSVM_retval = 0;
64 #ifdef HAVE_SYS_VM86_H
65 # include <sys/vm86.h>
66 #endif
67 #ifdef HAVE_SYS_MMAN_H
68 # include <sys/mman.h>
69 #endif
72 typedef struct _DOSEVENT {
73 int irq,priority;
74 DOSRELAY relay;
75 void *data;
76 struct _DOSEVENT *next;
77 } DOSEVENT, *LPDOSEVENT;
79 static CRITICAL_SECTION qcrit = CRITICAL_SECTION_INIT("DOSVM");
80 static struct _DOSEVENT *pending_event, *current_event;
81 static HANDLE event_notifier;
84 /***********************************************************************
85 * DOSVM_HasPendingEvents
87 * Return true if there are pending events that are not
88 * blocked by currently active event.
90 static BOOL DOSVM_HasPendingEvents( void )
92 if (!pending_event)
93 return FALSE;
95 if (!current_event)
96 return TRUE;
98 if (pending_event->priority < current_event->priority)
99 return TRUE;
101 return FALSE;
105 /***********************************************************************
106 * DOSVM_SendOneEvent
108 * Process single pending event.
110 * This function should be called with queue critical section locked.
111 * The function temporarily releases the critical section if it is
112 * possible that internal interrupt handler or user procedure will
113 * be called. This is because we may otherwise get a deadlock if
114 * another thread is waiting for the same critical section.
116 static void DOSVM_SendOneEvent( CONTEXT86 *context )
118 LPDOSEVENT event = pending_event;
120 /* Remove from pending events list. */
121 pending_event = event->next;
123 /* Process active event. */
124 if (event->irq >= 0)
126 BYTE intnum = (event->irq < 8) ?
127 (event->irq + 8) : (event->irq - 8 + 0x70);
129 /* Event is an IRQ, move it to current events list. */
130 event->next = current_event;
131 current_event = event;
133 TRACE( "Dispatching IRQ %d.\n", event->irq );
135 if (ISV86(context))
138 * Note that if DOSVM_HardwareInterruptRM calls an internal
139 * interrupt directly, current_event might be cleared
140 * (and event freed) in this call.
142 LeaveCriticalSection(&qcrit);
143 DOSVM_HardwareInterruptRM( context, intnum );
144 EnterCriticalSection(&qcrit);
146 else
149 * This routine only modifies current context so it is
150 * not necessary to release critical section.
152 DOSVM_HardwareInterruptPM( context, intnum );
155 else
157 /* Callback event. */
158 TRACE( "Dispatching callback event.\n" );
160 if (ISV86(context))
163 * Call relay immediately in real mode.
165 LeaveCriticalSection(&qcrit);
166 (*event->relay)( context, event->data );
167 EnterCriticalSection(&qcrit);
169 else
172 * Force return to relay code. We do not want to
173 * call relay directly because we may be inside a signal handler.
175 DOSVM_BuildCallFrame( context, event->relay, event->data );
178 free(event);
183 /***********************************************************************
184 * DOSVM_SendQueuedEvents
186 * As long as context instruction pointer stays unmodified,
187 * process all pending events that are not blocked by currently
188 * active event.
190 * This routine assumes that caller has already cleared TEB.vm86_pending
191 * and checked that interrupts are enabled.
193 void DOSVM_SendQueuedEvents( CONTEXT86 *context )
195 DWORD old_cs = context->SegCs;
196 DWORD old_ip = context->Eip;
198 EnterCriticalSection(&qcrit);
200 TRACE( "Called in %s mode %s events pending (time=%ld)\n",
201 ISV86(context) ? "real" : "protected",
202 DOSVM_HasPendingEvents() ? "with" : "without",
203 GetTickCount() );
204 TRACE( "cs:ip=%04lx:%08lx, ss:sp=%04lx:%08lx\n",
205 context->SegCs, context->Eip, context->SegSs, context->Esp);
207 while (context->SegCs == old_cs &&
208 context->Eip == old_ip &&
209 DOSVM_HasPendingEvents())
211 DOSVM_SendOneEvent(context);
214 * Event handling may have turned pending events flag on.
215 * We disable it here because this prevents some
216 * unnecessary calls to this function.
218 NtCurrentTeb()->vm86_pending = 0;
221 #ifdef MZ_SUPPORTED
223 if (!ISV86(context) && context->SegCs == old_cs && context->Eip == old_ip)
226 * Routine was called from DPMI but there was nothing to do.
227 * We force a dummy relay call here so that we don't get a race
228 * if signals are unblocked when we return to DPMI application.
230 TRACE( "Called but there was nothing to do, calling NULL relay.\n" );
231 DOSVM_BuildCallFrame( context, NULL, NULL );
234 if (DOSVM_HasPendingEvents())
237 * Interrupts disabled, but there are still
238 * pending events, make sure that pending flag is turned on.
240 TRACE( "Another event is pending, setting VIP flag.\n" );
241 NtCurrentTeb()->vm86_pending |= VIP_MASK;
244 #else
246 FIXME("No DOS .exe file support on this platform (yet)\n");
248 #endif /* MZ_SUPPORTED */
250 LeaveCriticalSection(&qcrit);
254 #ifdef MZ_SUPPORTED
255 /***********************************************************************
256 * QueueEvent (WINEDOS.@)
258 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
260 LPDOSEVENT event, cur, prev;
261 BOOL old_pending;
263 if (MZ_Current()) {
264 event = malloc(sizeof(DOSEVENT));
265 if (!event) {
266 ERR("out of memory allocating event entry\n");
267 return;
269 event->irq = irq; event->priority = priority;
270 event->relay = relay; event->data = data;
272 EnterCriticalSection(&qcrit);
273 old_pending = DOSVM_HasPendingEvents();
275 /* insert event into linked list, in order *after*
276 * all earlier events of higher or equal priority */
277 cur = pending_event; prev = NULL;
278 while (cur && cur->priority<=priority) {
279 prev = cur;
280 cur = cur->next;
282 event->next = cur;
283 if (prev) prev->next = event;
284 else pending_event = event;
286 if (!old_pending && DOSVM_HasPendingEvents()) {
287 TRACE("new event queued, signalling (time=%ld)\n", GetTickCount());
289 /* Alert VM86 thread about the new event. */
290 kill(dosvm_pid,SIGUSR2);
292 /* Wake up DOSVM_Wait so that it can serve pending events. */
293 SetEvent(event_notifier);
294 } else {
295 TRACE("new event queued (time=%ld)\n", GetTickCount());
298 LeaveCriticalSection(&qcrit);
299 } else {
300 /* DOS subsystem not running */
301 /* (this probably means that we're running a win16 app
302 * which uses DPMI to thunk down to DOS services) */
303 if (irq<0) {
304 /* callback event, perform it with dummy context */
305 CONTEXT86 context;
306 memset(&context,0,sizeof(context));
307 (*relay)(&context,data);
308 } else {
309 ERR("IRQ without DOS task: should not happen\n");
314 static void DOSVM_ProcessConsole(void)
316 INPUT_RECORD msg;
317 DWORD res;
318 BYTE scan, ascii;
320 if (ReadConsoleInputA(GetStdHandle(STD_INPUT_HANDLE),&msg,1,&res)) {
321 switch (msg.EventType) {
322 case KEY_EVENT:
323 scan = msg.Event.KeyEvent.wVirtualScanCode;
324 ascii = msg.Event.KeyEvent.uChar.AsciiChar;
325 TRACE("scan %02x, ascii %02x\n", scan, ascii);
327 /* set the "break" (release) flag if key released */
328 if (!msg.Event.KeyEvent.bKeyDown) scan |= 0x80;
330 /* check whether extended bit is set,
331 * and if so, queue the extension prefix */
332 if (msg.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY) {
333 DOSVM_Int09SendScan(0xE0,0);
335 DOSVM_Int09SendScan(scan, ascii);
336 break;
337 case MOUSE_EVENT:
338 DOSVM_Int33Console(&msg.Event.MouseEvent);
339 break;
340 case WINDOW_BUFFER_SIZE_EVENT:
341 FIXME("unhandled WINDOW_BUFFER_SIZE_EVENT.\n");
342 break;
343 case MENU_EVENT:
344 FIXME("unhandled MENU_EVENT.\n");
345 break;
346 case FOCUS_EVENT:
347 FIXME("unhandled FOCUS_EVENT.\n");
348 break;
349 default:
350 FIXME("unknown console event: %d\n", msg.EventType);
355 static void DOSVM_ProcessMessage(MSG *msg)
357 BYTE scan = 0;
359 TRACE("got message %04x, wparam=%08x, lparam=%08lx\n",msg->message,msg->wParam,msg->lParam);
360 if ((msg->message>=WM_MOUSEFIRST)&&
361 (msg->message<=WM_MOUSELAST)) {
362 DOSVM_Int33Message(msg->message,msg->wParam,msg->lParam);
363 } else {
364 switch (msg->message) {
365 case WM_KEYUP:
366 scan = 0x80;
367 case WM_KEYDOWN:
368 scan |= (msg->lParam >> 16) & 0x7f;
370 /* check whether extended bit is set,
371 * and if so, queue the extension prefix */
372 if (msg->lParam & 0x1000000) {
373 /* FIXME: some keys (function keys) have
374 * extended bit set even when they shouldn't,
375 * should check for them */
376 DOSVM_Int09SendScan(0xE0,0);
378 DOSVM_Int09SendScan(scan,0);
379 break;
385 /***********************************************************************
386 * DOSVM_Wait
388 * Wait for asynchronous events. This routine temporarily enables
389 * interrupts and waits until some asynchronous event has been
390 * processed.
392 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx )
394 if (DOSVM_HasPendingEvents())
396 CONTEXT86 context = *waitctx;
399 * If DOSVM_Wait is called from protected mode we emulate
400 * interrupt reflection and convert context into real mode context.
401 * This is actually the correct thing to do as long as DOSVM_Wait
402 * is only called from those interrupt functions that DPMI reflects
403 * to real mode.
405 * FIXME: Need to think about where to place real mode stack.
406 * FIXME: If DOSVM_Wait calls are nested stack gets corrupted.
407 * Can this really happen?
409 if (!ISV86(&context))
411 context.EFlags |= 0x00020000;
412 context.SegSs = 0xffff;
413 context.Esp = 0;
416 context.EFlags |= VIF_MASK;
417 context.SegCs = 0;
418 context.Eip = 0;
420 DOSVM_SendQueuedEvents(&context);
422 if(context.SegCs || context.Eip)
423 DPMI_CallRMProc( &context, NULL, 0, TRUE );
425 else
427 HANDLE objs[2];
428 int objc = DOSVM_IsWin16() ? 2 : 1;
429 DWORD waitret;
431 objs[0] = event_notifier;
432 objs[1] = GetStdHandle(STD_INPUT_HANDLE);
434 waitret = MsgWaitForMultipleObjects( objc, objs, FALSE,
435 INFINITE, QS_ALLINPUT );
437 if (waitret == WAIT_OBJECT_0)
440 * New pending event has been queued, we ignore it
441 * here because it will be processed on next call to
442 * DOSVM_Wait.
445 else if (objc == 2 && waitret == WAIT_OBJECT_0 + 1)
447 DOSVM_ProcessConsole();
449 else if (waitret == WAIT_OBJECT_0 + objc)
451 MSG msg;
452 while (PeekMessageA(&msg,0,0,0,PM_REMOVE|PM_NOYIELD))
454 /* got a message */
455 DOSVM_ProcessMessage(&msg);
456 /* we don't need a TranslateMessage here */
457 DispatchMessageA(&msg);
460 else
462 ERR_(module)( "dosvm wait error=%ld\n", GetLastError() );
468 DWORD WINAPI DOSVM_Loop( HANDLE hThread )
470 HANDLE objs[2];
471 MSG msg;
472 DWORD waitret;
474 objs[0] = GetStdHandle(STD_INPUT_HANDLE);
475 objs[1] = hThread;
477 for(;;) {
478 TRACE_(int)("waiting for action\n");
479 waitret = MsgWaitForMultipleObjects(2, objs, FALSE, INFINITE, QS_ALLINPUT);
480 if (waitret == WAIT_OBJECT_0) {
481 DOSVM_ProcessConsole();
483 else if (waitret == WAIT_OBJECT_0 + 1) {
484 DWORD rv;
485 if(!GetExitCodeThread(hThread, &rv)) {
486 ERR("Failed to get thread exit code!\n");
487 rv = 0;
489 return rv;
491 else if (waitret == WAIT_OBJECT_0 + 2) {
492 while (PeekMessageA(&msg,0,0,0,PM_REMOVE)) {
493 if (msg.hwnd) {
494 /* it's a window message */
495 DOSVM_ProcessMessage(&msg);
496 DispatchMessageA(&msg);
497 } else {
498 /* it's a thread message */
499 switch (msg.message) {
500 case WM_QUIT:
501 /* stop this madness!! */
502 return 0;
503 case WM_USER:
504 /* run passed procedure in this thread */
505 /* (sort of like APC, but we signal the completion) */
507 DOS_SPC *spc = (DOS_SPC *)msg.lParam;
508 TRACE_(int)("calling %p with arg %08lx\n", spc->proc, spc->arg);
509 (spc->proc)(spc->arg);
510 TRACE_(int)("done, signalling event %x\n", msg.wParam);
511 SetEvent( (HANDLE)msg.wParam );
513 break;
514 default:
515 DispatchMessageA(&msg);
520 else
522 ERR_(int)("MsgWaitForMultipleObjects returned unexpected value.\n");
523 return 0;
528 static WINE_EXCEPTION_FILTER(exception_handler)
530 EXCEPTION_RECORD *rec = GetExceptionInformation()->ExceptionRecord;
531 CONTEXT *context = GetExceptionInformation()->ContextRecord;
532 int arg = rec->ExceptionInformation[0];
533 BOOL ret;
535 switch(rec->ExceptionCode) {
536 case EXCEPTION_VM86_INTx:
537 if (TRACE_ON(relay)) {
538 DPRINTF("Call DOS int 0x%02x ret=%04lx:%04lx\n",
539 arg, context->SegCs, context->Eip );
540 DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
541 context->Eax, context->Ebx, context->Ecx, context->Edx,
542 context->Esi, context->Edi );
543 DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
544 context->Ebp, context->Esp, context->SegDs, context->SegEs,
545 context->SegFs, context->SegGs, context->EFlags );
547 ret = DOSVM_EmulateInterruptRM( context, arg );
548 if (TRACE_ON(relay)) {
549 DPRINTF("Ret DOS int 0x%02x ret=%04lx:%04lx\n",
550 arg, context->SegCs, context->Eip );
551 DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
552 context->Eax, context->Ebx, context->Ecx, context->Edx,
553 context->Esi, context->Edi );
554 DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
555 context->Ebp, context->Esp, context->SegDs, context->SegEs,
556 context->SegFs, context->SegGs, context->EFlags );
558 return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
560 case EXCEPTION_VM86_STI:
561 /* case EXCEPTION_VM86_PICRETURN: */
562 if (!ISV86(context))
563 ERR( "Protected mode STI caught by real mode handler!\n" );
565 context->EFlags |= VIF_MASK;
566 context->EFlags &= ~VIP_MASK;
567 DOSVM_SendQueuedEvents(context);
568 return EXCEPTION_CONTINUE_EXECUTION;
570 return EXCEPTION_CONTINUE_SEARCH;
573 int WINAPI DOSVM_Enter( CONTEXT86 *context )
575 /* Some callers forget to turn V86_FLAG on. */
576 context->EFlags |= V86_FLAG;
578 __TRY
580 __wine_enter_vm86( context );
581 TRACE_(module)( "vm86 returned: %s\n", strerror(errno) );
583 __EXCEPT(exception_handler)
585 TRACE_(module)( "leaving vm86 mode\n" );
587 __ENDTRY
589 return 0;
592 /***********************************************************************
593 * OutPIC (WINEDOS.@)
595 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val)
597 LPDOSEVENT event;
599 if ((port==0x20) && (val==0x20)) {
600 EnterCriticalSection(&qcrit);
601 if (current_event) {
602 /* EOI (End Of Interrupt) */
603 TRACE("received EOI for current IRQ, clearing\n");
604 event = current_event;
605 current_event = event->next;
606 if (event->relay)
607 (*event->relay)(NULL,event->data);
608 free(event);
610 if (DOSVM_HasPendingEvents()) {
611 /* another event is pending, which we should probably
612 * be able to process now */
613 TRACE("another event pending, setting flag\n");
614 NtCurrentTeb()->vm86_pending |= VIP_MASK;
616 } else {
617 WARN("EOI without active IRQ\n");
619 LeaveCriticalSection(&qcrit);
620 } else {
621 FIXME("unrecognized PIC command %02x\n",val);
625 #else /* !MZ_SUPPORTED */
627 /***********************************************************************
628 * Enter (WINEDOS.@)
630 INT WINAPI DOSVM_Enter( CONTEXT86 *context )
632 ERR_(module)("DOS realmode not supported on this architecture!\n");
633 return -1;
636 /***********************************************************************
637 * Wait (WINEDOS.@)
639 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx ) { }
641 /***********************************************************************
642 * OutPIC (WINEDOS.@)
644 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val) {}
646 /***********************************************************************
647 * QueueEvent (WINEDOS.@)
649 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
651 if (irq<0) {
652 /* callback event, perform it with dummy context */
653 CONTEXT86 context;
654 memset(&context,0,sizeof(context));
655 (*relay)(&context,data);
656 } else {
657 ERR("IRQ without DOS task: should not happen\n");
661 #endif /* MZ_SUPPORTED */
664 /**********************************************************************
665 * DOSVM_AcknowledgeIRQ
667 * This routine should be called by all internal IRQ handlers.
669 void WINAPI DOSVM_AcknowledgeIRQ( CONTEXT86 *context )
672 * Send EOI to PIC.
674 DOSVM_PIC_ioport_out( 0x20, 0x20 );
677 * Protected mode IRQ handlers are supposed
678 * to turn VIF flag on before they return.
680 if (!ISV86(context))
681 NtCurrentTeb()->dpmi_vif = 1;
685 /**********************************************************************
686 * DllMain (DOSVM.Init)
688 BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
690 TRACE_(module)("(%p,%ld,%p)\n", hinstDLL, fdwReason, lpvReserved);
692 if (fdwReason == DLL_PROCESS_ATTACH)
694 DisableThreadLibraryCalls(hinstDLL);
695 DOSVM_InitSegments();
697 event_notifier = CreateEventA(NULL, FALSE, FALSE, NULL);
698 if(!event_notifier)
699 ERR("Failed to create event object!\n");
701 return TRUE;