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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * Note: This code hasn't been completely cleaned up yet.
24 #include "wine/port.h"
36 #ifdef HAVE_SYS_TIME_H
37 # include <sys/time.h>
39 #include <sys/types.h>
41 #include "wine/winbase16.h"
42 #include "wine/exception.h"
54 #include "wine/debug.h"
57 WINE_DEFAULT_DEBUG_CHANNEL(int);
58 WINE_DECLARE_DEBUG_CHANNEL(module);
60 WINE_DECLARE_DEBUG_CHANNEL(relay);
64 WORD DOSVM_retval = 0;
66 #ifdef HAVE_SYS_MMAN_H
67 # include <sys/mman.h>
71 typedef struct _DOSEVENT {
75 struct _DOSEVENT *next;
76 } DOSEVENT, *LPDOSEVENT;
78 static struct _DOSEVENT *pending_event, *current_event;
79 static HANDLE event_notifier;
81 static CRITICAL_SECTION qcrit;
82 static CRITICAL_SECTION_DEBUG critsect_debug =
85 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
86 0, 0, { (DWORD_PTR)(__FILE__ ": qcrit") }
88 static CRITICAL_SECTION qcrit = { &critsect_debug, -1, 0, 0, 0, 0 };
91 /***********************************************************************
92 * DOSVM_HasPendingEvents
94 * Return true if there are pending events that are not
95 * blocked by currently active event.
97 static BOOL DOSVM_HasPendingEvents( void )
105 if (pending_event->priority < current_event->priority)
112 /***********************************************************************
115 * Process single pending event.
117 * This function should be called with queue critical section locked.
118 * The function temporarily releases the critical section if it is
119 * possible that internal interrupt handler or user procedure will
120 * be called. This is because we may otherwise get a deadlock if
121 * another thread is waiting for the same critical section.
123 static void DOSVM_SendOneEvent( CONTEXT86 *context )
125 LPDOSEVENT event = pending_event;
127 /* Remove from pending events list. */
128 pending_event = event->next;
130 /* Process active event. */
133 BYTE intnum = (event->irq < 8) ?
134 (event->irq + 8) : (event->irq - 8 + 0x70);
136 /* Event is an IRQ, move it to current events list. */
137 event->next = current_event;
138 current_event = event;
140 TRACE( "Dispatching IRQ %d.\n", event->irq );
145 * Note that if DOSVM_HardwareInterruptRM calls an internal
146 * interrupt directly, current_event might be cleared
147 * (and event freed) in this call.
149 LeaveCriticalSection(&qcrit);
150 DOSVM_HardwareInterruptRM( context, intnum );
151 EnterCriticalSection(&qcrit);
156 * This routine only modifies current context so it is
157 * not necessary to release critical section.
159 DOSVM_HardwareInterruptPM( context, intnum );
164 /* Callback event. */
165 TRACE( "Dispatching callback event.\n" );
170 * Call relay immediately in real mode.
172 LeaveCriticalSection(&qcrit);
173 (*event->relay)( context, event->data );
174 EnterCriticalSection(&qcrit);
179 * Force return to relay code. We do not want to
180 * call relay directly because we may be inside a signal handler.
182 DOSVM_BuildCallFrame( context, event->relay, event->data );
190 /***********************************************************************
191 * DOSVM_SendQueuedEvents
193 * As long as context instruction pointer stays unmodified,
194 * process all pending events that are not blocked by currently
197 * This routine assumes that caller has already cleared TEB.vm86_pending
198 * and checked that interrupts are enabled.
200 void DOSVM_SendQueuedEvents( CONTEXT86 *context )
202 DWORD old_cs = context->SegCs;
203 DWORD old_ip = context->Eip;
205 EnterCriticalSection(&qcrit);
207 TRACE( "Called in %s mode %s events pending (time=%ld)\n",
208 ISV86(context) ? "real" : "protected",
209 DOSVM_HasPendingEvents() ? "with" : "without",
211 TRACE( "cs:ip=%04lx:%08lx, ss:sp=%04lx:%08lx\n",
212 context->SegCs, context->Eip, context->SegSs, context->Esp);
214 while (context->SegCs == old_cs &&
215 context->Eip == old_ip &&
216 DOSVM_HasPendingEvents())
218 DOSVM_SendOneEvent(context);
221 * Event handling may have turned pending events flag on.
222 * We disable it here because this prevents some
223 * unnecessary calls to this function.
225 NtCurrentTeb()->vm86_pending = 0;
230 if (DOSVM_HasPendingEvents())
233 * Interrupts disabled, but there are still
234 * pending events, make sure that pending flag is turned on.
236 TRACE( "Another event is pending, setting VIP flag.\n" );
237 NtCurrentTeb()->vm86_pending |= VIP_MASK;
242 FIXME("No DOS .exe file support on this platform (yet)\n");
244 #endif /* MZ_SUPPORTED */
246 LeaveCriticalSection(&qcrit);
251 /***********************************************************************
252 * QueueEvent (WINEDOS.@)
254 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
256 LPDOSEVENT event, cur, prev;
260 event = malloc(sizeof(DOSEVENT));
262 ERR("out of memory allocating event entry\n");
265 event->irq = irq; event->priority = priority;
266 event->relay = relay; event->data = data;
268 EnterCriticalSection(&qcrit);
269 old_pending = DOSVM_HasPendingEvents();
271 /* insert event into linked list, in order *after*
272 * all earlier events of higher or equal priority */
273 cur = pending_event; prev = NULL;
274 while (cur && cur->priority<=priority) {
279 if (prev) prev->next = event;
280 else pending_event = event;
282 if (!old_pending && DOSVM_HasPendingEvents()) {
283 TRACE("new event queued, signalling (time=%ld)\n", GetTickCount());
285 /* Alert VM86 thread about the new event. */
286 kill(dosvm_pid,SIGUSR2);
288 /* Wake up DOSVM_Wait so that it can serve pending events. */
289 SetEvent(event_notifier);
291 TRACE("new event queued (time=%ld)\n", GetTickCount());
294 LeaveCriticalSection(&qcrit);
296 /* DOS subsystem not running */
297 /* (this probably means that we're running a win16 app
298 * which uses DPMI to thunk down to DOS services) */
300 /* callback event, perform it with dummy context */
302 memset(&context,0,sizeof(context));
303 (*relay)(&context,data);
305 ERR("IRQ without DOS task: should not happen\n");
310 static void DOSVM_ProcessConsole(void)
316 if (ReadConsoleInputA(GetStdHandle(STD_INPUT_HANDLE),&msg,1,&res)) {
317 switch (msg.EventType) {
319 scan = msg.Event.KeyEvent.wVirtualScanCode;
320 ascii = msg.Event.KeyEvent.uChar.AsciiChar;
321 TRACE("scan %02x, ascii %02x\n", scan, ascii);
323 /* set the "break" (release) flag if key released */
324 if (!msg.Event.KeyEvent.bKeyDown) scan |= 0x80;
326 /* check whether extended bit is set,
327 * and if so, queue the extension prefix */
328 if (msg.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY) {
329 DOSVM_Int09SendScan(0xE0,0);
331 DOSVM_Int09SendScan(scan, ascii);
334 DOSVM_Int33Console(&msg.Event.MouseEvent);
336 case WINDOW_BUFFER_SIZE_EVENT:
337 FIXME("unhandled WINDOW_BUFFER_SIZE_EVENT.\n");
340 FIXME("unhandled MENU_EVENT.\n");
343 FIXME("unhandled FOCUS_EVENT.\n");
346 FIXME("unknown console event: %d\n", msg.EventType);
351 static void DOSVM_ProcessMessage(MSG *msg)
355 TRACE("got message %04x, wparam=%08x, lparam=%08lx\n",msg->message,msg->wParam,msg->lParam);
356 if ((msg->message>=WM_MOUSEFIRST)&&
357 (msg->message<=WM_MOUSELAST)) {
358 DOSVM_Int33Message(msg->message,msg->wParam,msg->lParam);
360 switch (msg->message) {
364 scan |= (msg->lParam >> 16) & 0x7f;
366 /* check whether extended bit is set,
367 * and if so, queue the extension prefix */
368 if (msg->lParam & 0x1000000) {
369 /* FIXME: some keys (function keys) have
370 * extended bit set even when they shouldn't,
371 * should check for them */
372 DOSVM_Int09SendScan(0xE0,0);
374 DOSVM_Int09SendScan(scan,0);
381 /***********************************************************************
384 * Wait for asynchronous events. This routine temporarily enables
385 * interrupts and waits until some asynchronous event has been
388 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx )
390 if (DOSVM_HasPendingEvents())
392 CONTEXT86 context = *waitctx;
395 * If DOSVM_Wait is called from protected mode we emulate
396 * interrupt reflection and convert context into real mode context.
397 * This is actually the correct thing to do as long as DOSVM_Wait
398 * is only called from those interrupt functions that DPMI reflects
401 * FIXME: Need to think about where to place real mode stack.
402 * FIXME: If DOSVM_Wait calls are nested stack gets corrupted.
403 * Can this really happen?
405 if (!ISV86(&context))
407 context.EFlags |= V86_FLAG;
408 context.SegSs = 0xffff;
412 context.EFlags |= VIF_MASK;
416 DOSVM_SendQueuedEvents(&context);
418 if(context.SegCs || context.Eip)
419 DPMI_CallRMProc( &context, NULL, 0, TRUE );
424 int objc = DOSVM_IsWin16() ? 2 : 1;
427 objs[0] = event_notifier;
428 objs[1] = GetStdHandle(STD_INPUT_HANDLE);
430 waitret = MsgWaitForMultipleObjects( objc, objs, FALSE,
431 INFINITE, QS_ALLINPUT );
433 if (waitret == WAIT_OBJECT_0)
436 * New pending event has been queued, we ignore it
437 * here because it will be processed on next call to
441 else if (objc == 2 && waitret == WAIT_OBJECT_0 + 1)
443 DOSVM_ProcessConsole();
445 else if (waitret == WAIT_OBJECT_0 + objc)
448 while (PeekMessageA(&msg,0,0,0,PM_REMOVE|PM_NOYIELD))
451 DOSVM_ProcessMessage(&msg);
452 /* we don't need a TranslateMessage here */
453 DispatchMessageA(&msg);
458 ERR_(module)( "dosvm wait error=%ld\n", GetLastError() );
464 DWORD WINAPI DOSVM_Loop( HANDLE hThread )
470 objs[0] = GetStdHandle(STD_INPUT_HANDLE);
474 TRACE_(int)("waiting for action\n");
475 waitret = MsgWaitForMultipleObjects(2, objs, FALSE, INFINITE, QS_ALLINPUT);
476 if (waitret == WAIT_OBJECT_0) {
477 DOSVM_ProcessConsole();
479 else if (waitret == WAIT_OBJECT_0 + 1) {
481 if(!GetExitCodeThread(hThread, &rv)) {
482 ERR("Failed to get thread exit code!\n");
487 else if (waitret == WAIT_OBJECT_0 + 2) {
488 while (PeekMessageA(&msg,0,0,0,PM_REMOVE)) {
490 /* it's a window message */
491 DOSVM_ProcessMessage(&msg);
492 DispatchMessageA(&msg);
494 /* it's a thread message */
495 switch (msg.message) {
497 /* stop this madness!! */
500 /* run passed procedure in this thread */
501 /* (sort of like APC, but we signal the completion) */
503 DOS_SPC *spc = (DOS_SPC *)msg.lParam;
504 TRACE_(int)("calling %p with arg %08lx\n", spc->proc, spc->arg);
505 (spc->proc)(spc->arg);
506 TRACE_(int)("done, signalling event %x\n", msg.wParam);
507 SetEvent( (HANDLE)msg.wParam );
511 DispatchMessageA(&msg);
518 ERR_(int)("MsgWaitForMultipleObjects returned unexpected value.\n");
524 static WINE_EXCEPTION_FILTER(exception_handler)
526 EXCEPTION_RECORD *rec = GetExceptionInformation()->ExceptionRecord;
527 CONTEXT *context = GetExceptionInformation()->ContextRecord;
528 int arg = rec->ExceptionInformation[0];
531 switch(rec->ExceptionCode) {
532 case EXCEPTION_VM86_INTx:
533 TRACE_(relay)("Call DOS int 0x%02x ret=%04lx:%04lx\n"
534 " eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n"
535 " ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
536 arg, context->SegCs, context->Eip,
537 context->Eax, context->Ebx, context->Ecx, context->Edx, context->Esi, context->Edi,
538 context->Ebp, context->Esp, context->SegDs, context->SegEs, context->SegFs, context->SegGs,
540 ret = DOSVM_EmulateInterruptRM( context, arg );
541 TRACE_(relay)("Ret DOS int 0x%02x ret=%04lx:%04lx\n"
542 " eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n"
543 " ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
544 arg, context->SegCs, context->Eip,
545 context->Eax, context->Ebx, context->Ecx, context->Edx, context->Esi, context->Edi,
546 context->Ebp, context->Esp, context->SegDs, context->SegEs,
547 context->SegFs, context->SegGs, context->EFlags );
548 return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
550 case EXCEPTION_VM86_STI:
551 /* case EXCEPTION_VM86_PICRETURN: */
553 ERR( "Protected mode STI caught by real mode handler!\n" );
554 DOSVM_SendQueuedEvents(context);
555 return EXCEPTION_CONTINUE_EXECUTION;
557 case EXCEPTION_SINGLE_STEP:
558 ret = DOSVM_EmulateInterruptRM( context, 1 );
559 return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
561 case EXCEPTION_BREAKPOINT:
562 ret = DOSVM_EmulateInterruptRM( context, 3 );
563 return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
566 return EXCEPTION_CONTINUE_SEARCH;
569 int WINAPI DOSVM_Enter( CONTEXT86 *context )
572 ERR( "Called with protected mode context!\n" );
576 WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)context );
577 TRACE_(module)( "vm86 returned: %s\n", strerror(errno) );
579 __EXCEPT(exception_handler)
581 TRACE_(module)( "leaving vm86 mode\n" );
588 /***********************************************************************
591 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val)
595 FIXME( "Unsupported PIC port %04x\n", port );
597 else if (val == 0x20 || (val >= 0x60 && val <= 0x67))
599 EnterCriticalSection(&qcrit);
603 WARN( "%s without active IRQ\n",
604 val == 0x20 ? "EOI" : "Specific EOI" );
606 else if (val != 0x20 && val - 0x60 != current_event->irq)
608 WARN( "Specific EOI but current IRQ %d is not %d\n",
609 current_event->irq, val - 0x60 );
613 LPDOSEVENT event = current_event;
615 TRACE( "Received %s for current IRQ %d, clearing event\n",
616 val == 0x20 ? "EOI" : "Specific EOI", event->irq );
618 current_event = event->next;
620 (*event->relay)(NULL,event->data);
623 if (DOSVM_HasPendingEvents())
625 TRACE( "Another event pending, setting pending flag\n" );
626 NtCurrentTeb()->vm86_pending |= VIP_MASK;
630 LeaveCriticalSection(&qcrit);
634 FIXME( "Unrecognized PIC command %02x\n", val );
638 #else /* !MZ_SUPPORTED */
640 /***********************************************************************
643 INT WINAPI DOSVM_Enter( CONTEXT86 *context )
645 ERR_(module)("DOS realmode not supported on this architecture!\n");
649 /***********************************************************************
652 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx ) { }
654 /***********************************************************************
657 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val) {}
659 /***********************************************************************
660 * QueueEvent (WINEDOS.@)
662 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
665 /* callback event, perform it with dummy context */
667 memset(&context,0,sizeof(context));
668 (*relay)(&context,data);
670 ERR("IRQ without DOS task: should not happen\n");
674 #endif /* MZ_SUPPORTED */
677 /**********************************************************************
678 * DOSVM_AcknowledgeIRQ
680 * This routine should be called by all internal IRQ handlers.
682 void WINAPI DOSVM_AcknowledgeIRQ( CONTEXT86 *context )
687 DOSVM_PIC_ioport_out( 0x20, 0x20 );
690 * Protected mode IRQ handlers are supposed
691 * to turn VIF flag on before they return.
694 NtCurrentTeb()->dpmi_vif = 1;
698 /**********************************************************************
701 BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
703 TRACE_(module)("(%p,%ld,%p)\n", hinstDLL, fdwReason, lpvReserved);
705 if (fdwReason == DLL_PROCESS_ATTACH)
707 DisableThreadLibraryCalls(hinstDLL);
708 if (!DOSMEM_InitDosMemory()) return FALSE;
709 DOSVM_InitSegments();
711 event_notifier = CreateEventW(NULL, FALSE, FALSE, NULL);
713 ERR("Failed to create event object!\n");