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.
34 #ifdef HAVE_SYS_TIME_H
35 # include <sys/time.h>
37 #include <sys/types.h>
39 #include "wine/winbase16.h"
40 #include "wine/exception.h"
54 #include "wine/debug.h"
57 WINE_DEFAULT_DEBUG_CHANNEL(int);
58 WINE_DECLARE_DEBUG_CHANNEL(module);
59 WINE_DECLARE_DEBUG_CHANNEL(relay);
62 WORD DOSVM_retval = 0;
64 #ifdef HAVE_SYS_MMAN_H
65 # include <sys/mman.h>
69 typedef struct _DOSEVENT {
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 =
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 )
103 if (pending_event->priority < current_event->priority)
110 /***********************************************************************
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. */
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 );
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);
154 * This routine only modifies current context so it is
155 * not necessary to release critical section.
157 DOSVM_HardwareInterruptPM( context, intnum );
162 /* Callback event. */
163 TRACE( "Dispatching callback event.\n" );
168 * Call relay immediately in real mode.
170 LeaveCriticalSection(&qcrit);
171 (*event->relay)( context, event->data );
172 EnterCriticalSection(&qcrit);
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 );
188 /***********************************************************************
189 * DOSVM_SendQueuedEvents
191 * As long as context instruction pointer stays unmodified,
192 * process all pending events that are not blocked by currently
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",
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;
228 if (!ISV86(context) && context->SegCs == old_cs && context->Eip == old_ip)
231 * Routine was called from DPMI but there was nothing to do.
232 * We force a dummy relay call here so that we don't get a race
233 * if signals are unblocked when we return to DPMI application.
235 TRACE( "Called but there was nothing to do, calling NULL relay.\n" );
236 DOSVM_BuildCallFrame( context, NULL, NULL );
239 if (DOSVM_HasPendingEvents())
242 * Interrupts disabled, but there are still
243 * pending events, make sure that pending flag is turned on.
245 TRACE( "Another event is pending, setting VIP flag.\n" );
246 NtCurrentTeb()->vm86_pending |= VIP_MASK;
251 FIXME("No DOS .exe file support on this platform (yet)\n");
253 #endif /* MZ_SUPPORTED */
255 LeaveCriticalSection(&qcrit);
260 /***********************************************************************
261 * QueueEvent (WINEDOS.@)
263 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
265 LPDOSEVENT event, cur, prev;
269 event = malloc(sizeof(DOSEVENT));
271 ERR("out of memory allocating event entry\n");
274 event->irq = irq; event->priority = priority;
275 event->relay = relay; event->data = data;
277 EnterCriticalSection(&qcrit);
278 old_pending = DOSVM_HasPendingEvents();
280 /* insert event into linked list, in order *after*
281 * all earlier events of higher or equal priority */
282 cur = pending_event; prev = NULL;
283 while (cur && cur->priority<=priority) {
288 if (prev) prev->next = event;
289 else pending_event = event;
291 if (!old_pending && DOSVM_HasPendingEvents()) {
292 TRACE("new event queued, signalling (time=%ld)\n", GetTickCount());
294 /* Alert VM86 thread about the new event. */
295 kill(dosvm_pid,SIGUSR2);
297 /* Wake up DOSVM_Wait so that it can serve pending events. */
298 SetEvent(event_notifier);
300 TRACE("new event queued (time=%ld)\n", GetTickCount());
303 LeaveCriticalSection(&qcrit);
305 /* DOS subsystem not running */
306 /* (this probably means that we're running a win16 app
307 * which uses DPMI to thunk down to DOS services) */
309 /* callback event, perform it with dummy context */
311 memset(&context,0,sizeof(context));
312 (*relay)(&context,data);
314 ERR("IRQ without DOS task: should not happen\n");
319 static void DOSVM_ProcessConsole(void)
325 if (ReadConsoleInputA(GetStdHandle(STD_INPUT_HANDLE),&msg,1,&res)) {
326 switch (msg.EventType) {
328 scan = msg.Event.KeyEvent.wVirtualScanCode;
329 ascii = msg.Event.KeyEvent.uChar.AsciiChar;
330 TRACE("scan %02x, ascii %02x\n", scan, ascii);
332 /* set the "break" (release) flag if key released */
333 if (!msg.Event.KeyEvent.bKeyDown) scan |= 0x80;
335 /* check whether extended bit is set,
336 * and if so, queue the extension prefix */
337 if (msg.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY) {
338 DOSVM_Int09SendScan(0xE0,0);
340 DOSVM_Int09SendScan(scan, ascii);
343 DOSVM_Int33Console(&msg.Event.MouseEvent);
345 case WINDOW_BUFFER_SIZE_EVENT:
346 FIXME("unhandled WINDOW_BUFFER_SIZE_EVENT.\n");
349 FIXME("unhandled MENU_EVENT.\n");
352 FIXME("unhandled FOCUS_EVENT.\n");
355 FIXME("unknown console event: %d\n", msg.EventType);
360 static void DOSVM_ProcessMessage(MSG *msg)
364 TRACE("got message %04x, wparam=%08x, lparam=%08lx\n",msg->message,msg->wParam,msg->lParam);
365 if ((msg->message>=WM_MOUSEFIRST)&&
366 (msg->message<=WM_MOUSELAST)) {
367 DOSVM_Int33Message(msg->message,msg->wParam,msg->lParam);
369 switch (msg->message) {
373 scan |= (msg->lParam >> 16) & 0x7f;
375 /* check whether extended bit is set,
376 * and if so, queue the extension prefix */
377 if (msg->lParam & 0x1000000) {
378 /* FIXME: some keys (function keys) have
379 * extended bit set even when they shouldn't,
380 * should check for them */
381 DOSVM_Int09SendScan(0xE0,0);
383 DOSVM_Int09SendScan(scan,0);
390 /***********************************************************************
393 * Wait for asynchronous events. This routine temporarily enables
394 * interrupts and waits until some asynchronous event has been
397 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx )
399 if (DOSVM_HasPendingEvents())
401 CONTEXT86 context = *waitctx;
404 * If DOSVM_Wait is called from protected mode we emulate
405 * interrupt reflection and convert context into real mode context.
406 * This is actually the correct thing to do as long as DOSVM_Wait
407 * is only called from those interrupt functions that DPMI reflects
410 * FIXME: Need to think about where to place real mode stack.
411 * FIXME: If DOSVM_Wait calls are nested stack gets corrupted.
412 * Can this really happen?
414 if (!ISV86(&context))
416 context.EFlags |= V86_FLAG;
417 context.SegSs = 0xffff;
421 context.EFlags |= VIF_MASK;
425 DOSVM_SendQueuedEvents(&context);
427 if(context.SegCs || context.Eip)
428 DPMI_CallRMProc( &context, NULL, 0, TRUE );
433 int objc = DOSVM_IsWin16() ? 2 : 1;
436 objs[0] = event_notifier;
437 objs[1] = GetStdHandle(STD_INPUT_HANDLE);
439 waitret = MsgWaitForMultipleObjects( objc, objs, FALSE,
440 INFINITE, QS_ALLINPUT );
442 if (waitret == WAIT_OBJECT_0)
445 * New pending event has been queued, we ignore it
446 * here because it will be processed on next call to
450 else if (objc == 2 && waitret == WAIT_OBJECT_0 + 1)
452 DOSVM_ProcessConsole();
454 else if (waitret == WAIT_OBJECT_0 + objc)
457 while (PeekMessageA(&msg,0,0,0,PM_REMOVE|PM_NOYIELD))
460 DOSVM_ProcessMessage(&msg);
461 /* we don't need a TranslateMessage here */
462 DispatchMessageA(&msg);
467 ERR_(module)( "dosvm wait error=%ld\n", GetLastError() );
473 DWORD WINAPI DOSVM_Loop( HANDLE hThread )
479 objs[0] = GetStdHandle(STD_INPUT_HANDLE);
483 TRACE_(int)("waiting for action\n");
484 waitret = MsgWaitForMultipleObjects(2, objs, FALSE, INFINITE, QS_ALLINPUT);
485 if (waitret == WAIT_OBJECT_0) {
486 DOSVM_ProcessConsole();
488 else if (waitret == WAIT_OBJECT_0 + 1) {
490 if(!GetExitCodeThread(hThread, &rv)) {
491 ERR("Failed to get thread exit code!\n");
496 else if (waitret == WAIT_OBJECT_0 + 2) {
497 while (PeekMessageA(&msg,0,0,0,PM_REMOVE)) {
499 /* it's a window message */
500 DOSVM_ProcessMessage(&msg);
501 DispatchMessageA(&msg);
503 /* it's a thread message */
504 switch (msg.message) {
506 /* stop this madness!! */
509 /* run passed procedure in this thread */
510 /* (sort of like APC, but we signal the completion) */
512 DOS_SPC *spc = (DOS_SPC *)msg.lParam;
513 TRACE_(int)("calling %p with arg %08lx\n", spc->proc, spc->arg);
514 (spc->proc)(spc->arg);
515 TRACE_(int)("done, signalling event %x\n", msg.wParam);
516 SetEvent( (HANDLE)msg.wParam );
520 DispatchMessageA(&msg);
527 ERR_(int)("MsgWaitForMultipleObjects returned unexpected value.\n");
533 static WINE_EXCEPTION_FILTER(exception_handler)
535 EXCEPTION_RECORD *rec = GetExceptionInformation()->ExceptionRecord;
536 CONTEXT *context = GetExceptionInformation()->ContextRecord;
537 int arg = rec->ExceptionInformation[0];
540 switch(rec->ExceptionCode) {
541 case EXCEPTION_VM86_INTx:
542 if (TRACE_ON(relay)) {
543 DPRINTF("Call DOS int 0x%02x ret=%04lx:%04lx\n",
544 arg, context->SegCs, context->Eip );
545 DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
546 context->Eax, context->Ebx, context->Ecx, context->Edx,
547 context->Esi, context->Edi );
548 DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
549 context->Ebp, context->Esp, context->SegDs, context->SegEs,
550 context->SegFs, context->SegGs, context->EFlags );
552 ret = DOSVM_EmulateInterruptRM( context, arg );
553 if (TRACE_ON(relay)) {
554 DPRINTF("Ret DOS int 0x%02x ret=%04lx:%04lx\n",
555 arg, context->SegCs, context->Eip );
556 DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
557 context->Eax, context->Ebx, context->Ecx, context->Edx,
558 context->Esi, context->Edi );
559 DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
560 context->Ebp, context->Esp, context->SegDs, context->SegEs,
561 context->SegFs, context->SegGs, context->EFlags );
563 return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
565 case EXCEPTION_VM86_STI:
566 /* case EXCEPTION_VM86_PICRETURN: */
568 ERR( "Protected mode STI caught by real mode handler!\n" );
570 context->EFlags |= VIF_MASK;
571 context->EFlags &= ~VIP_MASK;
572 DOSVM_SendQueuedEvents(context);
573 return EXCEPTION_CONTINUE_EXECUTION;
575 return EXCEPTION_CONTINUE_SEARCH;
578 int WINAPI DOSVM_Enter( CONTEXT86 *context )
581 ERR( "Called with protected mode context!\n" );
585 __wine_enter_vm86( context );
586 TRACE_(module)( "vm86 returned: %s\n", strerror(errno) );
588 __EXCEPT(exception_handler)
590 TRACE_(module)( "leaving vm86 mode\n" );
597 /***********************************************************************
600 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val)
604 if ((port==0x20) && (val==0x20)) {
605 EnterCriticalSection(&qcrit);
607 /* EOI (End Of Interrupt) */
608 TRACE("received EOI for current IRQ, clearing\n");
609 event = current_event;
610 current_event = event->next;
612 (*event->relay)(NULL,event->data);
615 if (DOSVM_HasPendingEvents()) {
616 /* another event is pending, which we should probably
617 * be able to process now */
618 TRACE("another event pending, setting flag\n");
619 NtCurrentTeb()->vm86_pending |= VIP_MASK;
622 WARN("EOI without active IRQ\n");
624 LeaveCriticalSection(&qcrit);
626 FIXME("unrecognized PIC command %02x\n",val);
630 #else /* !MZ_SUPPORTED */
632 /***********************************************************************
635 INT WINAPI DOSVM_Enter( CONTEXT86 *context )
637 ERR_(module)("DOS realmode not supported on this architecture!\n");
641 /***********************************************************************
644 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx ) { }
646 /***********************************************************************
649 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val) {}
651 /***********************************************************************
652 * QueueEvent (WINEDOS.@)
654 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
657 /* callback event, perform it with dummy context */
659 memset(&context,0,sizeof(context));
660 (*relay)(&context,data);
662 ERR("IRQ without DOS task: should not happen\n");
666 #endif /* MZ_SUPPORTED */
669 /**********************************************************************
670 * DOSVM_AcknowledgeIRQ
672 * This routine should be called by all internal IRQ handlers.
674 void WINAPI DOSVM_AcknowledgeIRQ( CONTEXT86 *context )
679 DOSVM_PIC_ioport_out( 0x20, 0x20 );
682 * Protected mode IRQ handlers are supposed
683 * to turn VIF flag on before they return.
686 NtCurrentTeb()->dpmi_vif = 1;
690 /**********************************************************************
691 * DllMain (DOSVM.Init)
693 BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
695 TRACE_(module)("(%p,%ld,%p)\n", hinstDLL, fdwReason, lpvReserved);
697 if (fdwReason == DLL_PROCESS_ATTACH)
699 DisableThreadLibraryCalls(hinstDLL);
700 DOSVM_InitSegments();
702 event_notifier = CreateEventA(NULL, FALSE, FALSE, NULL);
704 ERR("Failed to create event object!\n");