Implement dispatch variant marshalling.
[wine/multimedia.git] / dlls / winedos / dosvm.c
blob6f0ebfe79676615a04f33dcf83b301069f943b51
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 <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #ifdef HAVE_UNISTD_H
33 # include <unistd.h>
34 #endif
35 #ifdef HAVE_SYS_TIME_H
36 # include <sys/time.h>
37 #endif
38 #include <sys/types.h>
40 #include "wine/winbase16.h"
41 #include "wine/exception.h"
42 #include "windef.h"
43 #include "winbase.h"
44 #include "wingdi.h"
45 #include "winuser.h"
46 #include "winnt.h"
47 #include "wincon.h"
49 #include "thread.h"
50 #include "msdos.h"
51 #include "file.h"
52 #include "miscemu.h"
53 #include "dosexe.h"
54 #include "dosvm.h"
55 #include "wine/debug.h"
56 #include "excpt.h"
58 WINE_DEFAULT_DEBUG_CHANNEL(int);
59 WINE_DECLARE_DEBUG_CHANNEL(module);
60 WINE_DECLARE_DEBUG_CHANNEL(relay);
62 WORD DOSVM_psp = 0;
63 WORD DOSVM_retval = 0;
65 #ifdef HAVE_SYS_MMAN_H
66 # include <sys/mman.h>
67 #endif
70 typedef struct _DOSEVENT {
71 int irq,priority;
72 DOSRELAY relay;
73 void *data;
74 struct _DOSEVENT *next;
75 } DOSEVENT, *LPDOSEVENT;
77 static struct _DOSEVENT *pending_event, *current_event;
78 static HANDLE event_notifier;
80 static CRITICAL_SECTION qcrit;
81 static CRITICAL_SECTION_DEBUG critsect_debug =
83 0, 0, &qcrit,
84 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
85 0, 0, { 0, (DWORD)(__FILE__ ": qcrit") }
87 static CRITICAL_SECTION qcrit = { &critsect_debug, -1, 0, 0, 0, 0 };
90 /***********************************************************************
91 * DOSVM_HasPendingEvents
93 * Return true if there are pending events that are not
94 * blocked by currently active event.
96 static BOOL DOSVM_HasPendingEvents( void )
98 if (!pending_event)
99 return FALSE;
101 if (!current_event)
102 return TRUE;
104 if (pending_event->priority < current_event->priority)
105 return TRUE;
107 return FALSE;
111 /***********************************************************************
112 * DOSVM_SendOneEvent
114 * Process single pending event.
116 * This function should be called with queue critical section locked.
117 * The function temporarily releases the critical section if it is
118 * possible that internal interrupt handler or user procedure will
119 * be called. This is because we may otherwise get a deadlock if
120 * another thread is waiting for the same critical section.
122 static void DOSVM_SendOneEvent( CONTEXT86 *context )
124 LPDOSEVENT event = pending_event;
126 /* Remove from pending events list. */
127 pending_event = event->next;
129 /* Process active event. */
130 if (event->irq >= 0)
132 BYTE intnum = (event->irq < 8) ?
133 (event->irq + 8) : (event->irq - 8 + 0x70);
135 /* Event is an IRQ, move it to current events list. */
136 event->next = current_event;
137 current_event = event;
139 TRACE( "Dispatching IRQ %d.\n", event->irq );
141 if (ISV86(context))
144 * Note that if DOSVM_HardwareInterruptRM calls an internal
145 * interrupt directly, current_event might be cleared
146 * (and event freed) in this call.
148 LeaveCriticalSection(&qcrit);
149 DOSVM_HardwareInterruptRM( context, intnum );
150 EnterCriticalSection(&qcrit);
152 else
155 * This routine only modifies current context so it is
156 * not necessary to release critical section.
158 DOSVM_HardwareInterruptPM( context, intnum );
161 else
163 /* Callback event. */
164 TRACE( "Dispatching callback event.\n" );
166 if (ISV86(context))
169 * Call relay immediately in real mode.
171 LeaveCriticalSection(&qcrit);
172 (*event->relay)( context, event->data );
173 EnterCriticalSection(&qcrit);
175 else
178 * Force return to relay code. We do not want to
179 * call relay directly because we may be inside a signal handler.
181 DOSVM_BuildCallFrame( context, event->relay, event->data );
184 free(event);
189 /***********************************************************************
190 * DOSVM_SendQueuedEvents
192 * As long as context instruction pointer stays unmodified,
193 * process all pending events that are not blocked by currently
194 * active event.
196 * This routine assumes that caller has already cleared TEB.vm86_pending
197 * and checked that interrupts are enabled.
199 void DOSVM_SendQueuedEvents( CONTEXT86 *context )
201 DWORD old_cs = context->SegCs;
202 DWORD old_ip = context->Eip;
204 EnterCriticalSection(&qcrit);
206 TRACE( "Called in %s mode %s events pending (time=%ld)\n",
207 ISV86(context) ? "real" : "protected",
208 DOSVM_HasPendingEvents() ? "with" : "without",
209 GetTickCount() );
210 TRACE( "cs:ip=%04lx:%08lx, ss:sp=%04lx:%08lx\n",
211 context->SegCs, context->Eip, context->SegSs, context->Esp);
213 while (context->SegCs == old_cs &&
214 context->Eip == old_ip &&
215 DOSVM_HasPendingEvents())
217 DOSVM_SendOneEvent(context);
220 * Event handling may have turned pending events flag on.
221 * We disable it here because this prevents some
222 * unnecessary calls to this function.
224 NtCurrentTeb()->vm86_pending = 0;
227 #ifdef MZ_SUPPORTED
229 if (!ISV86(context) && context->SegCs == old_cs && context->Eip == old_ip)
232 * Routine was called from DPMI but there was nothing to do.
233 * We force a dummy relay call here so that we don't get a race
234 * if signals are unblocked when we return to DPMI application.
236 TRACE( "Called but there was nothing to do, calling NULL relay.\n" );
237 DOSVM_BuildCallFrame( context, NULL, NULL );
240 if (DOSVM_HasPendingEvents())
243 * Interrupts disabled, but there are still
244 * pending events, make sure that pending flag is turned on.
246 TRACE( "Another event is pending, setting VIP flag.\n" );
247 NtCurrentTeb()->vm86_pending |= VIP_MASK;
250 #else
252 FIXME("No DOS .exe file support on this platform (yet)\n");
254 #endif /* MZ_SUPPORTED */
256 LeaveCriticalSection(&qcrit);
260 #ifdef MZ_SUPPORTED
261 /***********************************************************************
262 * QueueEvent (WINEDOS.@)
264 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
266 LPDOSEVENT event, cur, prev;
267 BOOL old_pending;
269 if (MZ_Current()) {
270 event = malloc(sizeof(DOSEVENT));
271 if (!event) {
272 ERR("out of memory allocating event entry\n");
273 return;
275 event->irq = irq; event->priority = priority;
276 event->relay = relay; event->data = data;
278 EnterCriticalSection(&qcrit);
279 old_pending = DOSVM_HasPendingEvents();
281 /* insert event into linked list, in order *after*
282 * all earlier events of higher or equal priority */
283 cur = pending_event; prev = NULL;
284 while (cur && cur->priority<=priority) {
285 prev = cur;
286 cur = cur->next;
288 event->next = cur;
289 if (prev) prev->next = event;
290 else pending_event = event;
292 if (!old_pending && DOSVM_HasPendingEvents()) {
293 TRACE("new event queued, signalling (time=%ld)\n", GetTickCount());
295 /* Alert VM86 thread about the new event. */
296 kill(dosvm_pid,SIGUSR2);
298 /* Wake up DOSVM_Wait so that it can serve pending events. */
299 SetEvent(event_notifier);
300 } else {
301 TRACE("new event queued (time=%ld)\n", GetTickCount());
304 LeaveCriticalSection(&qcrit);
305 } else {
306 /* DOS subsystem not running */
307 /* (this probably means that we're running a win16 app
308 * which uses DPMI to thunk down to DOS services) */
309 if (irq<0) {
310 /* callback event, perform it with dummy context */
311 CONTEXT86 context;
312 memset(&context,0,sizeof(context));
313 (*relay)(&context,data);
314 } else {
315 ERR("IRQ without DOS task: should not happen\n");
320 static void DOSVM_ProcessConsole(void)
322 INPUT_RECORD msg;
323 DWORD res;
324 BYTE scan, ascii;
326 if (ReadConsoleInputA(GetStdHandle(STD_INPUT_HANDLE),&msg,1,&res)) {
327 switch (msg.EventType) {
328 case KEY_EVENT:
329 scan = msg.Event.KeyEvent.wVirtualScanCode;
330 ascii = msg.Event.KeyEvent.uChar.AsciiChar;
331 TRACE("scan %02x, ascii %02x\n", scan, ascii);
333 /* set the "break" (release) flag if key released */
334 if (!msg.Event.KeyEvent.bKeyDown) scan |= 0x80;
336 /* check whether extended bit is set,
337 * and if so, queue the extension prefix */
338 if (msg.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY) {
339 DOSVM_Int09SendScan(0xE0,0);
341 DOSVM_Int09SendScan(scan, ascii);
342 break;
343 case MOUSE_EVENT:
344 DOSVM_Int33Console(&msg.Event.MouseEvent);
345 break;
346 case WINDOW_BUFFER_SIZE_EVENT:
347 FIXME("unhandled WINDOW_BUFFER_SIZE_EVENT.\n");
348 break;
349 case MENU_EVENT:
350 FIXME("unhandled MENU_EVENT.\n");
351 break;
352 case FOCUS_EVENT:
353 FIXME("unhandled FOCUS_EVENT.\n");
354 break;
355 default:
356 FIXME("unknown console event: %d\n", msg.EventType);
361 static void DOSVM_ProcessMessage(MSG *msg)
363 BYTE scan = 0;
365 TRACE("got message %04x, wparam=%08x, lparam=%08lx\n",msg->message,msg->wParam,msg->lParam);
366 if ((msg->message>=WM_MOUSEFIRST)&&
367 (msg->message<=WM_MOUSELAST)) {
368 DOSVM_Int33Message(msg->message,msg->wParam,msg->lParam);
369 } else {
370 switch (msg->message) {
371 case WM_KEYUP:
372 scan = 0x80;
373 case WM_KEYDOWN:
374 scan |= (msg->lParam >> 16) & 0x7f;
376 /* check whether extended bit is set,
377 * and if so, queue the extension prefix */
378 if (msg->lParam & 0x1000000) {
379 /* FIXME: some keys (function keys) have
380 * extended bit set even when they shouldn't,
381 * should check for them */
382 DOSVM_Int09SendScan(0xE0,0);
384 DOSVM_Int09SendScan(scan,0);
385 break;
391 /***********************************************************************
392 * DOSVM_Wait
394 * Wait for asynchronous events. This routine temporarily enables
395 * interrupts and waits until some asynchronous event has been
396 * processed.
398 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx )
400 if (DOSVM_HasPendingEvents())
402 CONTEXT86 context = *waitctx;
405 * If DOSVM_Wait is called from protected mode we emulate
406 * interrupt reflection and convert context into real mode context.
407 * This is actually the correct thing to do as long as DOSVM_Wait
408 * is only called from those interrupt functions that DPMI reflects
409 * to real mode.
411 * FIXME: Need to think about where to place real mode stack.
412 * FIXME: If DOSVM_Wait calls are nested stack gets corrupted.
413 * Can this really happen?
415 if (!ISV86(&context))
417 context.EFlags |= V86_FLAG;
418 context.SegSs = 0xffff;
419 context.Esp = 0;
422 context.EFlags |= VIF_MASK;
423 context.SegCs = 0;
424 context.Eip = 0;
426 DOSVM_SendQueuedEvents(&context);
428 if(context.SegCs || context.Eip)
429 DPMI_CallRMProc( &context, NULL, 0, TRUE );
431 else
433 HANDLE objs[2];
434 int objc = DOSVM_IsWin16() ? 2 : 1;
435 DWORD waitret;
437 objs[0] = event_notifier;
438 objs[1] = GetStdHandle(STD_INPUT_HANDLE);
440 waitret = MsgWaitForMultipleObjects( objc, objs, FALSE,
441 INFINITE, QS_ALLINPUT );
443 if (waitret == WAIT_OBJECT_0)
446 * New pending event has been queued, we ignore it
447 * here because it will be processed on next call to
448 * DOSVM_Wait.
451 else if (objc == 2 && waitret == WAIT_OBJECT_0 + 1)
453 DOSVM_ProcessConsole();
455 else if (waitret == WAIT_OBJECT_0 + objc)
457 MSG msg;
458 while (PeekMessageA(&msg,0,0,0,PM_REMOVE|PM_NOYIELD))
460 /* got a message */
461 DOSVM_ProcessMessage(&msg);
462 /* we don't need a TranslateMessage here */
463 DispatchMessageA(&msg);
466 else
468 ERR_(module)( "dosvm wait error=%ld\n", GetLastError() );
474 DWORD WINAPI DOSVM_Loop( HANDLE hThread )
476 HANDLE objs[2];
477 MSG msg;
478 DWORD waitret;
480 objs[0] = GetStdHandle(STD_INPUT_HANDLE);
481 objs[1] = hThread;
483 for(;;) {
484 TRACE_(int)("waiting for action\n");
485 waitret = MsgWaitForMultipleObjects(2, objs, FALSE, INFINITE, QS_ALLINPUT);
486 if (waitret == WAIT_OBJECT_0) {
487 DOSVM_ProcessConsole();
489 else if (waitret == WAIT_OBJECT_0 + 1) {
490 DWORD rv;
491 if(!GetExitCodeThread(hThread, &rv)) {
492 ERR("Failed to get thread exit code!\n");
493 rv = 0;
495 return rv;
497 else if (waitret == WAIT_OBJECT_0 + 2) {
498 while (PeekMessageA(&msg,0,0,0,PM_REMOVE)) {
499 if (msg.hwnd) {
500 /* it's a window message */
501 DOSVM_ProcessMessage(&msg);
502 DispatchMessageA(&msg);
503 } else {
504 /* it's a thread message */
505 switch (msg.message) {
506 case WM_QUIT:
507 /* stop this madness!! */
508 return 0;
509 case WM_USER:
510 /* run passed procedure in this thread */
511 /* (sort of like APC, but we signal the completion) */
513 DOS_SPC *spc = (DOS_SPC *)msg.lParam;
514 TRACE_(int)("calling %p with arg %08lx\n", spc->proc, spc->arg);
515 (spc->proc)(spc->arg);
516 TRACE_(int)("done, signalling event %x\n", msg.wParam);
517 SetEvent( (HANDLE)msg.wParam );
519 break;
520 default:
521 DispatchMessageA(&msg);
526 else
528 ERR_(int)("MsgWaitForMultipleObjects returned unexpected value.\n");
529 return 0;
534 static WINE_EXCEPTION_FILTER(exception_handler)
536 EXCEPTION_RECORD *rec = GetExceptionInformation()->ExceptionRecord;
537 CONTEXT *context = GetExceptionInformation()->ContextRecord;
538 int arg = rec->ExceptionInformation[0];
539 BOOL ret;
541 switch(rec->ExceptionCode) {
542 case EXCEPTION_VM86_INTx:
543 if (TRACE_ON(relay)) {
544 DPRINTF("Call DOS int 0x%02x ret=%04lx:%04lx\n",
545 arg, context->SegCs, context->Eip );
546 DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
547 context->Eax, context->Ebx, context->Ecx, context->Edx,
548 context->Esi, context->Edi );
549 DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
550 context->Ebp, context->Esp, context->SegDs, context->SegEs,
551 context->SegFs, context->SegGs, context->EFlags );
553 ret = DOSVM_EmulateInterruptRM( context, arg );
554 if (TRACE_ON(relay)) {
555 DPRINTF("Ret DOS int 0x%02x ret=%04lx:%04lx\n",
556 arg, context->SegCs, context->Eip );
557 DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
558 context->Eax, context->Ebx, context->Ecx, context->Edx,
559 context->Esi, context->Edi );
560 DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
561 context->Ebp, context->Esp, context->SegDs, context->SegEs,
562 context->SegFs, context->SegGs, context->EFlags );
564 return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
566 case EXCEPTION_VM86_STI:
567 /* case EXCEPTION_VM86_PICRETURN: */
568 if (!ISV86(context))
569 ERR( "Protected mode STI caught by real mode handler!\n" );
571 context->EFlags |= VIF_MASK;
572 context->EFlags &= ~VIP_MASK;
573 DOSVM_SendQueuedEvents(context);
574 return EXCEPTION_CONTINUE_EXECUTION;
576 return EXCEPTION_CONTINUE_SEARCH;
579 int WINAPI DOSVM_Enter( CONTEXT86 *context )
581 if (!ISV86(context))
582 ERR( "Called with protected mode context!\n" );
584 __TRY
586 __wine_enter_vm86( context );
587 TRACE_(module)( "vm86 returned: %s\n", strerror(errno) );
589 __EXCEPT(exception_handler)
591 TRACE_(module)( "leaving vm86 mode\n" );
593 __ENDTRY
595 return 0;
598 /***********************************************************************
599 * OutPIC (WINEDOS.@)
601 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val)
603 if (port != 0x20)
605 FIXME( "Unsupported PIC port %04x\n", port );
607 else if (val == 0x20 || (val >= 0x60 && val <= 0x67))
609 EnterCriticalSection(&qcrit);
611 if (!current_event)
613 WARN( "%s without active IRQ\n",
614 val == 0x20 ? "EOI" : "Specific EOI" );
616 else if (val != 0x20 && val - 0x60 != current_event->irq)
618 WARN( "Specific EOI but current IRQ %d is not %d\n",
619 current_event->irq, val - 0x60 );
621 else
623 LPDOSEVENT event = current_event;
625 TRACE( "Received %s for current IRQ %d, clearing event\n",
626 val == 0x20 ? "EOI" : "Specific EOI", event->irq );
628 current_event = event->next;
629 if (event->relay)
630 (*event->relay)(NULL,event->data);
631 free(event);
633 if (DOSVM_HasPendingEvents())
635 TRACE( "Another event pending, setting pending flag\n" );
636 NtCurrentTeb()->vm86_pending |= VIP_MASK;
640 LeaveCriticalSection(&qcrit);
642 else
644 FIXME( "Unrecognized PIC command %02x\n", val );
648 #else /* !MZ_SUPPORTED */
650 /***********************************************************************
651 * Enter (WINEDOS.@)
653 INT WINAPI DOSVM_Enter( CONTEXT86 *context )
655 ERR_(module)("DOS realmode not supported on this architecture!\n");
656 return -1;
659 /***********************************************************************
660 * Wait (WINEDOS.@)
662 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx ) { }
664 /***********************************************************************
665 * OutPIC (WINEDOS.@)
667 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val) {}
669 /***********************************************************************
670 * QueueEvent (WINEDOS.@)
672 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
674 if (irq<0) {
675 /* callback event, perform it with dummy context */
676 CONTEXT86 context;
677 memset(&context,0,sizeof(context));
678 (*relay)(&context,data);
679 } else {
680 ERR("IRQ without DOS task: should not happen\n");
684 #endif /* MZ_SUPPORTED */
687 /**********************************************************************
688 * DOSVM_AcknowledgeIRQ
690 * This routine should be called by all internal IRQ handlers.
692 void WINAPI DOSVM_AcknowledgeIRQ( CONTEXT86 *context )
695 * Send EOI to PIC.
697 DOSVM_PIC_ioport_out( 0x20, 0x20 );
700 * Protected mode IRQ handlers are supposed
701 * to turn VIF flag on before they return.
703 if (!ISV86(context))
704 NtCurrentTeb()->dpmi_vif = 1;
708 /**********************************************************************
709 * DllMain (DOSVM.Init)
711 BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
713 TRACE_(module)("(%p,%ld,%p)\n", hinstDLL, fdwReason, lpvReserved);
715 if (fdwReason == DLL_PROCESS_ATTACH)
717 DisableThreadLibraryCalls(hinstDLL);
718 DOSVM_InitSegments();
720 event_notifier = CreateEventA(NULL, FALSE, FALSE, NULL);
721 if(!event_notifier)
722 ERR("Failed to create event object!\n");
724 return TRUE;