Use CreateEventW in preference to CreateEventA for unnamed events.
[wine/multimedia.git] / dlls / winedos / dosvm.c
blobb4046b25088099600b17327bdfc441383f8f3a11
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"
24 #include "wine/port.h"
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <signal.h>
33 #ifdef HAVE_UNISTD_H
34 # include <unistd.h>
35 #endif
36 #ifdef HAVE_SYS_TIME_H
37 # include <sys/time.h>
38 #endif
39 #include <sys/types.h>
41 #include "wine/winbase16.h"
42 #include "wine/exception.h"
43 #include "windef.h"
44 #include "winbase.h"
45 #include "wingdi.h"
46 #include "winuser.h"
47 #include "wownt32.h"
48 #include "winnt.h"
49 #include "wincon.h"
51 #include "thread.h"
52 #include "dosexe.h"
53 #include "dosvm.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_MMAN_H
65 # include <sys/mman.h>
66 #endif
69 typedef struct _DOSEVENT {
70 int irq,priority;
71 DOSRELAY relay;
72 void *data;
73 struct _DOSEVENT *next;
74 } DOSEVENT, *LPDOSEVENT;
76 static struct _DOSEVENT *pending_event, *current_event;
77 static HANDLE event_notifier;
79 static CRITICAL_SECTION qcrit;
80 static CRITICAL_SECTION_DEBUG critsect_debug =
82 0, 0, &qcrit,
83 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
84 0, 0, { 0, (DWORD)(__FILE__ ": qcrit") }
86 static CRITICAL_SECTION qcrit = { &critsect_debug, -1, 0, 0, 0, 0 };
89 /***********************************************************************
90 * DOSVM_HasPendingEvents
92 * Return true if there are pending events that are not
93 * blocked by currently active event.
95 static BOOL DOSVM_HasPendingEvents( void )
97 if (!pending_event)
98 return FALSE;
100 if (!current_event)
101 return TRUE;
103 if (pending_event->priority < current_event->priority)
104 return TRUE;
106 return FALSE;
110 /***********************************************************************
111 * DOSVM_SendOneEvent
113 * Process single pending event.
115 * This function should be called with queue critical section locked.
116 * The function temporarily releases the critical section if it is
117 * possible that internal interrupt handler or user procedure will
118 * be called. This is because we may otherwise get a deadlock if
119 * another thread is waiting for the same critical section.
121 static void DOSVM_SendOneEvent( CONTEXT86 *context )
123 LPDOSEVENT event = pending_event;
125 /* Remove from pending events list. */
126 pending_event = event->next;
128 /* Process active event. */
129 if (event->irq >= 0)
131 BYTE intnum = (event->irq < 8) ?
132 (event->irq + 8) : (event->irq - 8 + 0x70);
134 /* Event is an IRQ, move it to current events list. */
135 event->next = current_event;
136 current_event = event;
138 TRACE( "Dispatching IRQ %d.\n", event->irq );
140 if (ISV86(context))
143 * Note that if DOSVM_HardwareInterruptRM calls an internal
144 * interrupt directly, current_event might be cleared
145 * (and event freed) in this call.
147 LeaveCriticalSection(&qcrit);
148 DOSVM_HardwareInterruptRM( context, intnum );
149 EnterCriticalSection(&qcrit);
151 else
154 * This routine only modifies current context so it is
155 * not necessary to release critical section.
157 DOSVM_HardwareInterruptPM( context, intnum );
160 else
162 /* Callback event. */
163 TRACE( "Dispatching callback event.\n" );
165 if (ISV86(context))
168 * Call relay immediately in real mode.
170 LeaveCriticalSection(&qcrit);
171 (*event->relay)( context, event->data );
172 EnterCriticalSection(&qcrit);
174 else
177 * Force return to relay code. We do not want to
178 * call relay directly because we may be inside a signal handler.
180 DOSVM_BuildCallFrame( context, event->relay, event->data );
183 free(event);
188 /***********************************************************************
189 * DOSVM_SendQueuedEvents
191 * As long as context instruction pointer stays unmodified,
192 * process all pending events that are not blocked by currently
193 * active event.
195 * This routine assumes that caller has already cleared TEB.vm86_pending
196 * and checked that interrupts are enabled.
198 void DOSVM_SendQueuedEvents( CONTEXT86 *context )
200 DWORD old_cs = context->SegCs;
201 DWORD old_ip = context->Eip;
203 EnterCriticalSection(&qcrit);
205 TRACE( "Called in %s mode %s events pending (time=%ld)\n",
206 ISV86(context) ? "real" : "protected",
207 DOSVM_HasPendingEvents() ? "with" : "without",
208 GetTickCount() );
209 TRACE( "cs:ip=%04lx:%08lx, ss:sp=%04lx:%08lx\n",
210 context->SegCs, context->Eip, context->SegSs, context->Esp);
212 while (context->SegCs == old_cs &&
213 context->Eip == old_ip &&
214 DOSVM_HasPendingEvents())
216 DOSVM_SendOneEvent(context);
219 * Event handling may have turned pending events flag on.
220 * We disable it here because this prevents some
221 * unnecessary calls to this function.
223 NtCurrentTeb()->vm86_pending = 0;
226 #ifdef MZ_SUPPORTED
228 if (DOSVM_HasPendingEvents())
231 * Interrupts disabled, but there are still
232 * pending events, make sure that pending flag is turned on.
234 TRACE( "Another event is pending, setting VIP flag.\n" );
235 NtCurrentTeb()->vm86_pending |= VIP_MASK;
238 #else
240 FIXME("No DOS .exe file support on this platform (yet)\n");
242 #endif /* MZ_SUPPORTED */
244 LeaveCriticalSection(&qcrit);
248 #ifdef MZ_SUPPORTED
249 /***********************************************************************
250 * QueueEvent (WINEDOS.@)
252 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
254 LPDOSEVENT event, cur, prev;
255 BOOL old_pending;
257 if (MZ_Current()) {
258 event = malloc(sizeof(DOSEVENT));
259 if (!event) {
260 ERR("out of memory allocating event entry\n");
261 return;
263 event->irq = irq; event->priority = priority;
264 event->relay = relay; event->data = data;
266 EnterCriticalSection(&qcrit);
267 old_pending = DOSVM_HasPendingEvents();
269 /* insert event into linked list, in order *after*
270 * all earlier events of higher or equal priority */
271 cur = pending_event; prev = NULL;
272 while (cur && cur->priority<=priority) {
273 prev = cur;
274 cur = cur->next;
276 event->next = cur;
277 if (prev) prev->next = event;
278 else pending_event = event;
280 if (!old_pending && DOSVM_HasPendingEvents()) {
281 TRACE("new event queued, signalling (time=%ld)\n", GetTickCount());
283 /* Alert VM86 thread about the new event. */
284 kill(dosvm_pid,SIGUSR2);
286 /* Wake up DOSVM_Wait so that it can serve pending events. */
287 SetEvent(event_notifier);
288 } else {
289 TRACE("new event queued (time=%ld)\n", GetTickCount());
292 LeaveCriticalSection(&qcrit);
293 } else {
294 /* DOS subsystem not running */
295 /* (this probably means that we're running a win16 app
296 * which uses DPMI to thunk down to DOS services) */
297 if (irq<0) {
298 /* callback event, perform it with dummy context */
299 CONTEXT86 context;
300 memset(&context,0,sizeof(context));
301 (*relay)(&context,data);
302 } else {
303 ERR("IRQ without DOS task: should not happen\n");
308 static void DOSVM_ProcessConsole(void)
310 INPUT_RECORD msg;
311 DWORD res;
312 BYTE scan, ascii;
314 if (ReadConsoleInputA(GetStdHandle(STD_INPUT_HANDLE),&msg,1,&res)) {
315 switch (msg.EventType) {
316 case KEY_EVENT:
317 scan = msg.Event.KeyEvent.wVirtualScanCode;
318 ascii = msg.Event.KeyEvent.uChar.AsciiChar;
319 TRACE("scan %02x, ascii %02x\n", scan, ascii);
321 /* set the "break" (release) flag if key released */
322 if (!msg.Event.KeyEvent.bKeyDown) scan |= 0x80;
324 /* check whether extended bit is set,
325 * and if so, queue the extension prefix */
326 if (msg.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY) {
327 DOSVM_Int09SendScan(0xE0,0);
329 DOSVM_Int09SendScan(scan, ascii);
330 break;
331 case MOUSE_EVENT:
332 DOSVM_Int33Console(&msg.Event.MouseEvent);
333 break;
334 case WINDOW_BUFFER_SIZE_EVENT:
335 FIXME("unhandled WINDOW_BUFFER_SIZE_EVENT.\n");
336 break;
337 case MENU_EVENT:
338 FIXME("unhandled MENU_EVENT.\n");
339 break;
340 case FOCUS_EVENT:
341 FIXME("unhandled FOCUS_EVENT.\n");
342 break;
343 default:
344 FIXME("unknown console event: %d\n", msg.EventType);
349 static void DOSVM_ProcessMessage(MSG *msg)
351 BYTE scan = 0;
353 TRACE("got message %04x, wparam=%08x, lparam=%08lx\n",msg->message,msg->wParam,msg->lParam);
354 if ((msg->message>=WM_MOUSEFIRST)&&
355 (msg->message<=WM_MOUSELAST)) {
356 DOSVM_Int33Message(msg->message,msg->wParam,msg->lParam);
357 } else {
358 switch (msg->message) {
359 case WM_KEYUP:
360 scan = 0x80;
361 case WM_KEYDOWN:
362 scan |= (msg->lParam >> 16) & 0x7f;
364 /* check whether extended bit is set,
365 * and if so, queue the extension prefix */
366 if (msg->lParam & 0x1000000) {
367 /* FIXME: some keys (function keys) have
368 * extended bit set even when they shouldn't,
369 * should check for them */
370 DOSVM_Int09SendScan(0xE0,0);
372 DOSVM_Int09SendScan(scan,0);
373 break;
379 /***********************************************************************
380 * DOSVM_Wait
382 * Wait for asynchronous events. This routine temporarily enables
383 * interrupts and waits until some asynchronous event has been
384 * processed.
386 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx )
388 if (DOSVM_HasPendingEvents())
390 CONTEXT86 context = *waitctx;
393 * If DOSVM_Wait is called from protected mode we emulate
394 * interrupt reflection and convert context into real mode context.
395 * This is actually the correct thing to do as long as DOSVM_Wait
396 * is only called from those interrupt functions that DPMI reflects
397 * to real mode.
399 * FIXME: Need to think about where to place real mode stack.
400 * FIXME: If DOSVM_Wait calls are nested stack gets corrupted.
401 * Can this really happen?
403 if (!ISV86(&context))
405 context.EFlags |= V86_FLAG;
406 context.SegSs = 0xffff;
407 context.Esp = 0;
410 context.EFlags |= VIF_MASK;
411 context.SegCs = 0;
412 context.Eip = 0;
414 DOSVM_SendQueuedEvents(&context);
416 if(context.SegCs || context.Eip)
417 DPMI_CallRMProc( &context, NULL, 0, TRUE );
419 else
421 HANDLE objs[2];
422 int objc = DOSVM_IsWin16() ? 2 : 1;
423 DWORD waitret;
425 objs[0] = event_notifier;
426 objs[1] = GetStdHandle(STD_INPUT_HANDLE);
428 waitret = MsgWaitForMultipleObjects( objc, objs, FALSE,
429 INFINITE, QS_ALLINPUT );
431 if (waitret == WAIT_OBJECT_0)
434 * New pending event has been queued, we ignore it
435 * here because it will be processed on next call to
436 * DOSVM_Wait.
439 else if (objc == 2 && waitret == WAIT_OBJECT_0 + 1)
441 DOSVM_ProcessConsole();
443 else if (waitret == WAIT_OBJECT_0 + objc)
445 MSG msg;
446 while (PeekMessageA(&msg,0,0,0,PM_REMOVE|PM_NOYIELD))
448 /* got a message */
449 DOSVM_ProcessMessage(&msg);
450 /* we don't need a TranslateMessage here */
451 DispatchMessageA(&msg);
454 else
456 ERR_(module)( "dosvm wait error=%ld\n", GetLastError() );
462 DWORD WINAPI DOSVM_Loop( HANDLE hThread )
464 HANDLE objs[2];
465 MSG msg;
466 DWORD waitret;
468 objs[0] = GetStdHandle(STD_INPUT_HANDLE);
469 objs[1] = hThread;
471 for(;;) {
472 TRACE_(int)("waiting for action\n");
473 waitret = MsgWaitForMultipleObjects(2, objs, FALSE, INFINITE, QS_ALLINPUT);
474 if (waitret == WAIT_OBJECT_0) {
475 DOSVM_ProcessConsole();
477 else if (waitret == WAIT_OBJECT_0 + 1) {
478 DWORD rv;
479 if(!GetExitCodeThread(hThread, &rv)) {
480 ERR("Failed to get thread exit code!\n");
481 rv = 0;
483 return rv;
485 else if (waitret == WAIT_OBJECT_0 + 2) {
486 while (PeekMessageA(&msg,0,0,0,PM_REMOVE)) {
487 if (msg.hwnd) {
488 /* it's a window message */
489 DOSVM_ProcessMessage(&msg);
490 DispatchMessageA(&msg);
491 } else {
492 /* it's a thread message */
493 switch (msg.message) {
494 case WM_QUIT:
495 /* stop this madness!! */
496 return 0;
497 case WM_USER:
498 /* run passed procedure in this thread */
499 /* (sort of like APC, but we signal the completion) */
501 DOS_SPC *spc = (DOS_SPC *)msg.lParam;
502 TRACE_(int)("calling %p with arg %08lx\n", spc->proc, spc->arg);
503 (spc->proc)(spc->arg);
504 TRACE_(int)("done, signalling event %x\n", msg.wParam);
505 SetEvent( (HANDLE)msg.wParam );
507 break;
508 default:
509 DispatchMessageA(&msg);
514 else
516 ERR_(int)("MsgWaitForMultipleObjects returned unexpected value.\n");
517 return 0;
522 static WINE_EXCEPTION_FILTER(exception_handler)
524 EXCEPTION_RECORD *rec = GetExceptionInformation()->ExceptionRecord;
525 CONTEXT *context = GetExceptionInformation()->ContextRecord;
526 int arg = rec->ExceptionInformation[0];
527 BOOL ret;
529 switch(rec->ExceptionCode) {
530 case EXCEPTION_VM86_INTx:
531 TRACE_(relay)("Call DOS int 0x%02x ret=%04lx:%04lx\n"
532 " eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n"
533 " ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
534 arg, context->SegCs, context->Eip,
535 context->Eax, context->Ebx, context->Ecx, context->Edx, context->Esi, context->Edi,
536 context->Ebp, context->Esp, context->SegDs, context->SegEs, context->SegFs, context->SegGs,
537 context->EFlags );
538 ret = DOSVM_EmulateInterruptRM( context, arg );
539 TRACE_(relay)("Ret DOS int 0x%02x ret=%04lx:%04lx\n"
540 " eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n"
541 " ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
542 arg, context->SegCs, context->Eip,
543 context->Eax, context->Ebx, context->Ecx, context->Edx, context->Esi, context->Edi,
544 context->Ebp, context->Esp, context->SegDs, context->SegEs,
545 context->SegFs, context->SegGs, context->EFlags );
546 return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
548 case EXCEPTION_VM86_STI:
549 /* case EXCEPTION_VM86_PICRETURN: */
550 if (!ISV86(context))
551 ERR( "Protected mode STI caught by real mode handler!\n" );
552 DOSVM_SendQueuedEvents(context);
553 return EXCEPTION_CONTINUE_EXECUTION;
555 case EXCEPTION_SINGLE_STEP:
556 ret = DOSVM_EmulateInterruptRM( context, 1 );
557 return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
559 case EXCEPTION_BREAKPOINT:
560 ret = DOSVM_EmulateInterruptRM( context, 3 );
561 return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
564 return EXCEPTION_CONTINUE_SEARCH;
567 int WINAPI DOSVM_Enter( CONTEXT86 *context )
569 if (!ISV86(context))
570 ERR( "Called with protected mode context!\n" );
572 __TRY
574 WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)context );
575 TRACE_(module)( "vm86 returned: %s\n", strerror(errno) );
577 __EXCEPT(exception_handler)
579 TRACE_(module)( "leaving vm86 mode\n" );
581 __ENDTRY
583 return 0;
586 /***********************************************************************
587 * OutPIC (WINEDOS.@)
589 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val)
591 if (port != 0x20)
593 FIXME( "Unsupported PIC port %04x\n", port );
595 else if (val == 0x20 || (val >= 0x60 && val <= 0x67))
597 EnterCriticalSection(&qcrit);
599 if (!current_event)
601 WARN( "%s without active IRQ\n",
602 val == 0x20 ? "EOI" : "Specific EOI" );
604 else if (val != 0x20 && val - 0x60 != current_event->irq)
606 WARN( "Specific EOI but current IRQ %d is not %d\n",
607 current_event->irq, val - 0x60 );
609 else
611 LPDOSEVENT event = current_event;
613 TRACE( "Received %s for current IRQ %d, clearing event\n",
614 val == 0x20 ? "EOI" : "Specific EOI", event->irq );
616 current_event = event->next;
617 if (event->relay)
618 (*event->relay)(NULL,event->data);
619 free(event);
621 if (DOSVM_HasPendingEvents())
623 TRACE( "Another event pending, setting pending flag\n" );
624 NtCurrentTeb()->vm86_pending |= VIP_MASK;
628 LeaveCriticalSection(&qcrit);
630 else
632 FIXME( "Unrecognized PIC command %02x\n", val );
636 #else /* !MZ_SUPPORTED */
638 /***********************************************************************
639 * Enter (WINEDOS.@)
641 INT WINAPI DOSVM_Enter( CONTEXT86 *context )
643 ERR_(module)("DOS realmode not supported on this architecture!\n");
644 return -1;
647 /***********************************************************************
648 * Wait (WINEDOS.@)
650 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx ) { }
652 /***********************************************************************
653 * OutPIC (WINEDOS.@)
655 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val) {}
657 /***********************************************************************
658 * QueueEvent (WINEDOS.@)
660 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
662 if (irq<0) {
663 /* callback event, perform it with dummy context */
664 CONTEXT86 context;
665 memset(&context,0,sizeof(context));
666 (*relay)(&context,data);
667 } else {
668 ERR("IRQ without DOS task: should not happen\n");
672 #endif /* MZ_SUPPORTED */
675 /**********************************************************************
676 * DOSVM_AcknowledgeIRQ
678 * This routine should be called by all internal IRQ handlers.
680 void WINAPI DOSVM_AcknowledgeIRQ( CONTEXT86 *context )
683 * Send EOI to PIC.
685 DOSVM_PIC_ioport_out( 0x20, 0x20 );
688 * Protected mode IRQ handlers are supposed
689 * to turn VIF flag on before they return.
691 if (!ISV86(context))
692 NtCurrentTeb()->dpmi_vif = 1;
696 /**********************************************************************
697 * DOSVM_BiosData
699 * Get pointer to BIOS data area. This is not at fixed location
700 * because those Win16 programs that do not use any real mode code have
701 * protected NULL pointer catching block at low linear memory and
702 * BIOS data has been moved to another location.
704 BIOSDATA *DOSVM_BiosData( void )
706 LDT_ENTRY entry;
707 FARPROC16 proc;
709 proc = GetProcAddress16( GetModuleHandle16( "KERNEL" ),
710 (LPCSTR)(ULONG_PTR)193 );
711 wine_ldt_get_entry( LOWORD(proc), &entry );
712 return (BIOSDATA *)wine_ldt_get_base( &entry );
716 /**********************************************************************
717 * DllMain (DOSVM.0)
719 BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
721 TRACE_(module)("(%p,%ld,%p)\n", hinstDLL, fdwReason, lpvReserved);
723 if (fdwReason == DLL_PROCESS_ATTACH)
725 DisableThreadLibraryCalls(hinstDLL);
726 DOSVM_InitSegments();
728 event_notifier = CreateEventW(NULL, FALSE, FALSE, NULL);
729 if(!event_notifier)
730 ERR("Failed to create event object!\n");
732 return TRUE;