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.
35 #ifdef HAVE_SYS_TIME_H
36 # include <sys/time.h>
38 #include <sys/types.h>
40 #include "wine/winbase16.h"
41 #include "wine/exception.h"
53 #include "wine/debug.h"
56 WINE_DEFAULT_DEBUG_CHANNEL(int);
57 WINE_DECLARE_DEBUG_CHANNEL(module);
58 WINE_DECLARE_DEBUG_CHANNEL(relay);
61 WORD DOSVM_retval = 0;
63 #ifdef HAVE_SYS_MMAN_H
64 # include <sys/mman.h>
68 typedef struct _DOSEVENT {
72 struct _DOSEVENT *next;
73 } DOSEVENT, *LPDOSEVENT;
75 static struct _DOSEVENT *pending_event, *current_event;
76 static HANDLE event_notifier;
78 static CRITICAL_SECTION qcrit;
79 static CRITICAL_SECTION_DEBUG critsect_debug =
82 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
83 0, 0, { 0, (DWORD)(__FILE__ ": qcrit") }
85 static CRITICAL_SECTION qcrit = { &critsect_debug, -1, 0, 0, 0, 0 };
88 /***********************************************************************
89 * DOSVM_HasPendingEvents
91 * Return true if there are pending events that are not
92 * blocked by currently active event.
94 static BOOL DOSVM_HasPendingEvents( void )
102 if (pending_event->priority < current_event->priority)
109 /***********************************************************************
112 * Process single pending event.
114 * This function should be called with queue critical section locked.
115 * The function temporarily releases the critical section if it is
116 * possible that internal interrupt handler or user procedure will
117 * be called. This is because we may otherwise get a deadlock if
118 * another thread is waiting for the same critical section.
120 static void DOSVM_SendOneEvent( CONTEXT86 *context )
122 LPDOSEVENT event = pending_event;
124 /* Remove from pending events list. */
125 pending_event = event->next;
127 /* Process active event. */
130 BYTE intnum = (event->irq < 8) ?
131 (event->irq + 8) : (event->irq - 8 + 0x70);
133 /* Event is an IRQ, move it to current events list. */
134 event->next = current_event;
135 current_event = event;
137 TRACE( "Dispatching IRQ %d.\n", event->irq );
142 * Note that if DOSVM_HardwareInterruptRM calls an internal
143 * interrupt directly, current_event might be cleared
144 * (and event freed) in this call.
146 LeaveCriticalSection(&qcrit);
147 DOSVM_HardwareInterruptRM( context, intnum );
148 EnterCriticalSection(&qcrit);
153 * This routine only modifies current context so it is
154 * not necessary to release critical section.
156 DOSVM_HardwareInterruptPM( context, intnum );
161 /* Callback event. */
162 TRACE( "Dispatching callback event.\n" );
167 * Call relay immediately in real mode.
169 LeaveCriticalSection(&qcrit);
170 (*event->relay)( context, event->data );
171 EnterCriticalSection(&qcrit);
176 * Force return to relay code. We do not want to
177 * call relay directly because we may be inside a signal handler.
179 DOSVM_BuildCallFrame( context, event->relay, event->data );
187 /***********************************************************************
188 * DOSVM_SendQueuedEvents
190 * As long as context instruction pointer stays unmodified,
191 * process all pending events that are not blocked by currently
194 * This routine assumes that caller has already cleared TEB.vm86_pending
195 * and checked that interrupts are enabled.
197 void DOSVM_SendQueuedEvents( CONTEXT86 *context )
199 DWORD old_cs = context->SegCs;
200 DWORD old_ip = context->Eip;
202 EnterCriticalSection(&qcrit);
204 TRACE( "Called in %s mode %s events pending (time=%ld)\n",
205 ISV86(context) ? "real" : "protected",
206 DOSVM_HasPendingEvents() ? "with" : "without",
208 TRACE( "cs:ip=%04lx:%08lx, ss:sp=%04lx:%08lx\n",
209 context->SegCs, context->Eip, context->SegSs, context->Esp);
211 while (context->SegCs == old_cs &&
212 context->Eip == old_ip &&
213 DOSVM_HasPendingEvents())
215 DOSVM_SendOneEvent(context);
218 * Event handling may have turned pending events flag on.
219 * We disable it here because this prevents some
220 * unnecessary calls to this function.
222 NtCurrentTeb()->vm86_pending = 0;
227 if (DOSVM_HasPendingEvents())
230 * Interrupts disabled, but there are still
231 * pending events, make sure that pending flag is turned on.
233 TRACE( "Another event is pending, setting VIP flag.\n" );
234 NtCurrentTeb()->vm86_pending |= VIP_MASK;
239 FIXME("No DOS .exe file support on this platform (yet)\n");
241 #endif /* MZ_SUPPORTED */
243 LeaveCriticalSection(&qcrit);
248 /***********************************************************************
249 * QueueEvent (WINEDOS.@)
251 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
253 LPDOSEVENT event, cur, prev;
257 event = malloc(sizeof(DOSEVENT));
259 ERR("out of memory allocating event entry\n");
262 event->irq = irq; event->priority = priority;
263 event->relay = relay; event->data = data;
265 EnterCriticalSection(&qcrit);
266 old_pending = DOSVM_HasPendingEvents();
268 /* insert event into linked list, in order *after*
269 * all earlier events of higher or equal priority */
270 cur = pending_event; prev = NULL;
271 while (cur && cur->priority<=priority) {
276 if (prev) prev->next = event;
277 else pending_event = event;
279 if (!old_pending && DOSVM_HasPendingEvents()) {
280 TRACE("new event queued, signalling (time=%ld)\n", GetTickCount());
282 /* Alert VM86 thread about the new event. */
283 kill(dosvm_pid,SIGUSR2);
285 /* Wake up DOSVM_Wait so that it can serve pending events. */
286 SetEvent(event_notifier);
288 TRACE("new event queued (time=%ld)\n", GetTickCount());
291 LeaveCriticalSection(&qcrit);
293 /* DOS subsystem not running */
294 /* (this probably means that we're running a win16 app
295 * which uses DPMI to thunk down to DOS services) */
297 /* callback event, perform it with dummy context */
299 memset(&context,0,sizeof(context));
300 (*relay)(&context,data);
302 ERR("IRQ without DOS task: should not happen\n");
307 static void DOSVM_ProcessConsole(void)
313 if (ReadConsoleInputA(GetStdHandle(STD_INPUT_HANDLE),&msg,1,&res)) {
314 switch (msg.EventType) {
316 scan = msg.Event.KeyEvent.wVirtualScanCode;
317 ascii = msg.Event.KeyEvent.uChar.AsciiChar;
318 TRACE("scan %02x, ascii %02x\n", scan, ascii);
320 /* set the "break" (release) flag if key released */
321 if (!msg.Event.KeyEvent.bKeyDown) scan |= 0x80;
323 /* check whether extended bit is set,
324 * and if so, queue the extension prefix */
325 if (msg.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY) {
326 DOSVM_Int09SendScan(0xE0,0);
328 DOSVM_Int09SendScan(scan, ascii);
331 DOSVM_Int33Console(&msg.Event.MouseEvent);
333 case WINDOW_BUFFER_SIZE_EVENT:
334 FIXME("unhandled WINDOW_BUFFER_SIZE_EVENT.\n");
337 FIXME("unhandled MENU_EVENT.\n");
340 FIXME("unhandled FOCUS_EVENT.\n");
343 FIXME("unknown console event: %d\n", msg.EventType);
348 static void DOSVM_ProcessMessage(MSG *msg)
352 TRACE("got message %04x, wparam=%08x, lparam=%08lx\n",msg->message,msg->wParam,msg->lParam);
353 if ((msg->message>=WM_MOUSEFIRST)&&
354 (msg->message<=WM_MOUSELAST)) {
355 DOSVM_Int33Message(msg->message,msg->wParam,msg->lParam);
357 switch (msg->message) {
361 scan |= (msg->lParam >> 16) & 0x7f;
363 /* check whether extended bit is set,
364 * and if so, queue the extension prefix */
365 if (msg->lParam & 0x1000000) {
366 /* FIXME: some keys (function keys) have
367 * extended bit set even when they shouldn't,
368 * should check for them */
369 DOSVM_Int09SendScan(0xE0,0);
371 DOSVM_Int09SendScan(scan,0);
378 /***********************************************************************
381 * Wait for asynchronous events. This routine temporarily enables
382 * interrupts and waits until some asynchronous event has been
385 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx )
387 if (DOSVM_HasPendingEvents())
389 CONTEXT86 context = *waitctx;
392 * If DOSVM_Wait is called from protected mode we emulate
393 * interrupt reflection and convert context into real mode context.
394 * This is actually the correct thing to do as long as DOSVM_Wait
395 * is only called from those interrupt functions that DPMI reflects
398 * FIXME: Need to think about where to place real mode stack.
399 * FIXME: If DOSVM_Wait calls are nested stack gets corrupted.
400 * Can this really happen?
402 if (!ISV86(&context))
404 context.EFlags |= V86_FLAG;
405 context.SegSs = 0xffff;
409 context.EFlags |= VIF_MASK;
413 DOSVM_SendQueuedEvents(&context);
415 if(context.SegCs || context.Eip)
416 DPMI_CallRMProc( &context, NULL, 0, TRUE );
421 int objc = DOSVM_IsWin16() ? 2 : 1;
424 objs[0] = event_notifier;
425 objs[1] = GetStdHandle(STD_INPUT_HANDLE);
427 waitret = MsgWaitForMultipleObjects( objc, objs, FALSE,
428 INFINITE, QS_ALLINPUT );
430 if (waitret == WAIT_OBJECT_0)
433 * New pending event has been queued, we ignore it
434 * here because it will be processed on next call to
438 else if (objc == 2 && waitret == WAIT_OBJECT_0 + 1)
440 DOSVM_ProcessConsole();
442 else if (waitret == WAIT_OBJECT_0 + objc)
445 while (PeekMessageA(&msg,0,0,0,PM_REMOVE|PM_NOYIELD))
448 DOSVM_ProcessMessage(&msg);
449 /* we don't need a TranslateMessage here */
450 DispatchMessageA(&msg);
455 ERR_(module)( "dosvm wait error=%ld\n", GetLastError() );
461 DWORD WINAPI DOSVM_Loop( HANDLE hThread )
467 objs[0] = GetStdHandle(STD_INPUT_HANDLE);
471 TRACE_(int)("waiting for action\n");
472 waitret = MsgWaitForMultipleObjects(2, objs, FALSE, INFINITE, QS_ALLINPUT);
473 if (waitret == WAIT_OBJECT_0) {
474 DOSVM_ProcessConsole();
476 else if (waitret == WAIT_OBJECT_0 + 1) {
478 if(!GetExitCodeThread(hThread, &rv)) {
479 ERR("Failed to get thread exit code!\n");
484 else if (waitret == WAIT_OBJECT_0 + 2) {
485 while (PeekMessageA(&msg,0,0,0,PM_REMOVE)) {
487 /* it's a window message */
488 DOSVM_ProcessMessage(&msg);
489 DispatchMessageA(&msg);
491 /* it's a thread message */
492 switch (msg.message) {
494 /* stop this madness!! */
497 /* run passed procedure in this thread */
498 /* (sort of like APC, but we signal the completion) */
500 DOS_SPC *spc = (DOS_SPC *)msg.lParam;
501 TRACE_(int)("calling %p with arg %08lx\n", spc->proc, spc->arg);
502 (spc->proc)(spc->arg);
503 TRACE_(int)("done, signalling event %x\n", msg.wParam);
504 SetEvent( (HANDLE)msg.wParam );
508 DispatchMessageA(&msg);
515 ERR_(int)("MsgWaitForMultipleObjects returned unexpected value.\n");
521 static WINE_EXCEPTION_FILTER(exception_handler)
523 EXCEPTION_RECORD *rec = GetExceptionInformation()->ExceptionRecord;
524 CONTEXT *context = GetExceptionInformation()->ContextRecord;
525 int arg = rec->ExceptionInformation[0];
528 switch(rec->ExceptionCode) {
529 case EXCEPTION_VM86_INTx:
530 if (TRACE_ON(relay)) {
531 DPRINTF("Call DOS int 0x%02x ret=%04lx:%04lx\n",
532 arg, context->SegCs, context->Eip );
533 DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
534 context->Eax, context->Ebx, context->Ecx, context->Edx,
535 context->Esi, context->Edi );
536 DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
537 context->Ebp, context->Esp, context->SegDs, context->SegEs,
538 context->SegFs, context->SegGs, context->EFlags );
540 ret = DOSVM_EmulateInterruptRM( context, arg );
541 if (TRACE_ON(relay)) {
542 DPRINTF("Ret DOS int 0x%02x ret=%04lx:%04lx\n",
543 arg, context->SegCs, context->Eip );
544 DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
545 context->Eax, context->Ebx, context->Ecx, context->Edx,
546 context->Esi, context->Edi );
547 DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
548 context->Ebp, context->Esp, context->SegDs, context->SegEs,
549 context->SegFs, context->SegGs, context->EFlags );
551 return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
553 case EXCEPTION_VM86_STI:
554 /* case EXCEPTION_VM86_PICRETURN: */
556 ERR( "Protected mode STI caught by real mode handler!\n" );
557 DOSVM_SendQueuedEvents(context);
558 return EXCEPTION_CONTINUE_EXECUTION;
560 return EXCEPTION_CONTINUE_SEARCH;
563 int WINAPI DOSVM_Enter( CONTEXT86 *context )
566 ERR( "Called with protected mode context!\n" );
570 WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)context );
571 TRACE_(module)( "vm86 returned: %s\n", strerror(errno) );
573 __EXCEPT(exception_handler)
575 TRACE_(module)( "leaving vm86 mode\n" );
582 /***********************************************************************
585 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val)
589 FIXME( "Unsupported PIC port %04x\n", port );
591 else if (val == 0x20 || (val >= 0x60 && val <= 0x67))
593 EnterCriticalSection(&qcrit);
597 WARN( "%s without active IRQ\n",
598 val == 0x20 ? "EOI" : "Specific EOI" );
600 else if (val != 0x20 && val - 0x60 != current_event->irq)
602 WARN( "Specific EOI but current IRQ %d is not %d\n",
603 current_event->irq, val - 0x60 );
607 LPDOSEVENT event = current_event;
609 TRACE( "Received %s for current IRQ %d, clearing event\n",
610 val == 0x20 ? "EOI" : "Specific EOI", event->irq );
612 current_event = event->next;
614 (*event->relay)(NULL,event->data);
617 if (DOSVM_HasPendingEvents())
619 TRACE( "Another event pending, setting pending flag\n" );
620 NtCurrentTeb()->vm86_pending |= VIP_MASK;
624 LeaveCriticalSection(&qcrit);
628 FIXME( "Unrecognized PIC command %02x\n", val );
632 #else /* !MZ_SUPPORTED */
634 /***********************************************************************
637 INT WINAPI DOSVM_Enter( CONTEXT86 *context )
639 ERR_(module)("DOS realmode not supported on this architecture!\n");
643 /***********************************************************************
646 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx ) { }
648 /***********************************************************************
651 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val) {}
653 /***********************************************************************
654 * QueueEvent (WINEDOS.@)
656 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
659 /* callback event, perform it with dummy context */
661 memset(&context,0,sizeof(context));
662 (*relay)(&context,data);
664 ERR("IRQ without DOS task: should not happen\n");
668 #endif /* MZ_SUPPORTED */
671 /**********************************************************************
672 * DOSVM_AcknowledgeIRQ
674 * This routine should be called by all internal IRQ handlers.
676 void WINAPI DOSVM_AcknowledgeIRQ( CONTEXT86 *context )
681 DOSVM_PIC_ioport_out( 0x20, 0x20 );
684 * Protected mode IRQ handlers are supposed
685 * to turn VIF flag on before they return.
688 NtCurrentTeb()->dpmi_vif = 1;
692 /**********************************************************************
695 * Get pointer to BIOS data area. This is not at fixed location
696 * because those Win16 programs that do not use any real mode code have
697 * protected NULL pointer catching block at low linear memory and
698 * BIOS data has been moved to another location.
700 BIOSDATA *DOSVM_BiosData( void )
705 proc = GetProcAddress16( GetModuleHandle16( "KERNEL" ),
706 (LPCSTR)(ULONG_PTR)193 );
707 wine_ldt_get_entry( LOWORD(proc), &entry );
708 return (BIOSDATA *)wine_ldt_get_base( &entry );
712 /**********************************************************************
713 * DllMain (DOSVM.Init)
715 BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
717 TRACE_(module)("(%p,%ld,%p)\n", hinstDLL, fdwReason, lpvReserved);
719 if (fdwReason == DLL_PROCESS_ATTACH)
721 DisableThreadLibraryCalls(hinstDLL);
722 DOSVM_InitSegments();
724 event_notifier = CreateEventA(NULL, FALSE, FALSE, NULL);
726 ERR("Failed to create event object!\n");