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.
33 #include <sys/types.h>
35 #include "wine/winbase16.h"
36 #include "wine/exception.h"
49 #include "stackframe.h"
50 #include "wine/debug.h"
51 #include "msvcrt/excpt.h"
53 WINE_DEFAULT_DEBUG_CHANNEL(int);
54 WINE_DECLARE_DEBUG_CHANNEL(module);
55 WINE_DECLARE_DEBUG_CHANNEL(relay);
58 WORD DOSVM_retval = 0;
62 #ifdef HAVE_SYS_VM86_H
63 # include <sys/vm86.h>
65 #ifdef HAVE_SYS_MMAN_H
66 # include <sys/mman.h>
69 #define IF_CLR(ctx) ((ctx)->EFlags &= ~VIF_MASK)
70 #define IF_SET(ctx) ((ctx)->EFlags |= VIF_MASK)
71 #define IF_ENABLED(ctx) ((ctx)->EFlags & VIF_MASK)
72 #define SET_PEND(ctx) ((ctx)->EFlags |= VIP_MASK)
73 #define CLR_PEND(ctx) ((ctx)->EFlags &= ~VIP_MASK)
74 #define IS_PEND(ctx) ((ctx)->EFlags & VIP_MASK)
78 typedef struct _DOSEVENT {
82 struct _DOSEVENT *next;
83 } DOSEVENT, *LPDOSEVENT;
85 static CRITICAL_SECTION qcrit = CRITICAL_SECTION_INIT("DOSVM");
86 static struct _DOSEVENT *pending_event, *current_event;
88 static HANDLE event_notifier;
89 static CONTEXT86 *current_context;
91 static int DOSVM_SimulateInt( int vect, CONTEXT86 *context, BOOL inwine )
93 FARPROC16 handler=DOSVM_GetRMHandler(vect);
95 /* check for our real-mode hooks */
97 if (context->SegCs==DOSMEM_wrap_seg) {
98 /* exit from real-mode wrapper */
101 /* we could probably move some other dodgy stuff here too from dpmi.c */
103 /* check if the call is from our fake BIOS interrupt stubs */
104 if ((context->SegCs==0xf000) && !inwine) {
105 if (vect != (context->Eip/4)) {
106 TRACE("something fishy going on here (interrupt stub is %02lx)\n", context->Eip/4);
108 TRACE("builtin interrupt %02x has been branched to\n", vect);
109 DOSVM_RealModeInterrupt(vect, context);
111 /* check if the call goes to an unhooked interrupt */
112 else if (SELECTOROF(handler)==0xf000) {
113 /* if so, call it directly */
114 TRACE("builtin interrupt %02x has been invoked (through vector %02x)\n", OFFSETOF(handler)/4, vect);
115 DOSVM_RealModeInterrupt(OFFSETOF(handler)/4, context);
117 /* the interrupt is hooked, simulate interrupt in DOS space */
119 WORD*stack= PTR_REAL_TO_LIN( context->SegSs, context->Esp );
120 WORD flag=LOWORD(context->EFlags);
122 TRACE_(int)("invoking hooked interrupt %02x at %04x:%04x\n", vect,
123 SELECTOROF(handler), OFFSETOF(handler));
124 if (IF_ENABLED(context)) flag|=IF_MASK;
128 *(--stack)=context->SegCs;
129 *(--stack)=LOWORD(context->Eip);
131 context->SegCs=SELECTOROF(handler);
132 context->Eip=OFFSETOF(handler);
138 #define SHOULD_PEND(x) \
139 (x && ((!current_event) || (x->priority < current_event->priority)))
141 static void DOSVM_SendQueuedEvent(CONTEXT86 *context)
143 LPDOSEVENT event = pending_event;
145 if (SHOULD_PEND(event)) {
146 /* remove from "pending" list */
147 pending_event = event->next;
150 /* it's an IRQ, move it to "current" list */
151 event->next = current_event;
152 current_event = event;
153 TRACE("dispatching IRQ %d\n",event->irq);
154 /* note that if DOSVM_SimulateInt calls an internal interrupt directly,
155 * current_event might be cleared (and event freed) in this very call! */
156 DOSVM_SimulateInt((event->irq<8)?(event->irq+8):(event->irq-8+0x70),context,TRUE);
159 TRACE("dispatching callback event\n");
160 (*event->relay)(context,event->data);
164 if (!SHOULD_PEND(pending_event)) {
165 TRACE("clearing Pending flag\n");
170 static void DOSVM_SendQueuedEvents(CONTEXT86 *context)
172 /* we will send all queued events as long as interrupts are enabled,
173 * but IRQ events will disable interrupts again */
174 while (IS_PEND(context) && IF_ENABLED(context))
175 DOSVM_SendQueuedEvent(context);
178 /***********************************************************************
179 * QueueEvent (WINEDOS.@)
181 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
183 LPDOSEVENT event, cur, prev;
185 if (current_context) {
186 EnterCriticalSection(&qcrit);
187 event = malloc(sizeof(DOSEVENT));
189 ERR("out of memory allocating event entry\n");
192 event->irq = irq; event->priority = priority;
193 event->relay = relay; event->data = data;
195 /* insert event into linked list, in order *after*
196 * all earlier events of higher or equal priority */
197 cur = pending_event; prev = NULL;
198 while (cur && cur->priority<=priority) {
203 if (prev) prev->next = event;
204 else pending_event = event;
206 /* alert the vm86 about the new event */
208 TRACE("new event queued, signalling (time=%ld)\n", GetTickCount());
209 kill(dosvm_pid,SIGUSR2);
212 TRACE("new event queued (time=%ld)\n", GetTickCount());
215 /* Wake up DOSVM_Wait so that it can serve pending events. */
216 SetEvent(event_notifier);
218 LeaveCriticalSection(&qcrit);
220 /* DOS subsystem not running */
221 /* (this probably means that we're running a win16 app
222 * which uses DPMI to thunk down to DOS services) */
224 /* callback event, perform it with dummy context */
226 memset(&context,0,sizeof(context));
227 (*relay)(&context,data);
229 ERR("IRQ without DOS task: should not happen");
234 static void DOSVM_ProcessConsole(void)
240 if (ReadConsoleInputA(GetStdHandle(STD_INPUT_HANDLE),&msg,1,&res)) {
241 switch (msg.EventType) {
243 scan = msg.Event.KeyEvent.wVirtualScanCode;
244 if (!msg.Event.KeyEvent.bKeyDown) scan |= 0x80;
246 /* check whether extended bit is set,
247 * and if so, queue the extension prefix */
248 if (msg.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY) {
249 DOSVM_Int09SendScan(0xE0,0);
251 DOSVM_Int09SendScan(scan,msg.Event.KeyEvent.uChar.AsciiChar);
254 DOSVM_Int33Console(&msg.Event.MouseEvent);
256 case WINDOW_BUFFER_SIZE_EVENT:
257 FIXME("unhandled WINDOW_BUFFER_SIZE_EVENT.\n");
260 FIXME("unhandled MENU_EVENT.\n");
263 FIXME("unhandled FOCUS_EVENT.\n");
266 FIXME("unknown console event: %d\n", msg.EventType);
271 static void DOSVM_ProcessMessage(MSG *msg)
275 TRACE("got message %04x, wparam=%08x, lparam=%08lx\n",msg->message,msg->wParam,msg->lParam);
276 if ((msg->message>=WM_MOUSEFIRST)&&
277 (msg->message<=WM_MOUSELAST)) {
278 DOSVM_Int33Message(msg->message,msg->wParam,msg->lParam);
280 switch (msg->message) {
284 scan |= (msg->lParam >> 16) & 0x7f;
286 /* check whether extended bit is set,
287 * and if so, queue the extension prefix */
288 if (msg->lParam & 0x1000000) {
289 /* FIXME: some keys (function keys) have
290 * extended bit set even when they shouldn't,
291 * should check for them */
292 DOSVM_Int09SendScan(0xE0,0);
294 DOSVM_Int09SendScan(scan,0);
300 /***********************************************************************
303 void WINAPI DOSVM_Wait( INT read_pipe, HANDLE hObject )
309 BOOL got_msg = FALSE;
311 objs[0]=GetStdHandle(STD_INPUT_HANDLE);
312 objs[1]=event_notifier;
316 /* check for messages (waste time before the response check below) */
319 while (PeekMessageA(&msg,0,0,0,PM_REMOVE|PM_NOYIELD)) {
321 DOSVM_ProcessMessage(&msg);
322 /* we don't need a TranslateMessage here */
323 DispatchMessageA(&msg);
329 /* check for console input */
332 if (PeekConsoleInputA(objs[0],&msg,1,&num) && num) {
333 DOSVM_ProcessConsole();
337 if (read_pipe == -1) {
338 /* dispatch pending events */
339 if (SHOULD_PEND(pending_event)) {
340 CONTEXT86 context = *current_context;
343 DOSVM_SendQueuedEvents(&context);
349 struct timeval timeout={0,0};
350 /* quick check for response from dosmod
351 * (faster than doing the full blocking wait, if data already available) */
352 FD_ZERO(&readfds); FD_SET(read_pipe,&readfds);
353 if (select(read_pipe+1,&readfds,NULL,NULL,&timeout)>0)
356 /* nothing yet, block while waiting for something to do */
357 if (MsgWaitForMultipleObjects)
358 waitret = MsgWaitForMultipleObjects(objc,objs,FALSE,INFINITE,QS_ALLINPUT);
360 waitret = WaitForMultipleObjects(objc,objs,FALSE,INFINITE);
362 if (waitret==(DWORD)-1) {
363 ERR_(module)("dosvm wait error=%ld\n",GetLastError());
365 if ((read_pipe != -1) && hObject) {
366 if (waitret==(WAIT_OBJECT_0+2)) break;
368 if (waitret==WAIT_OBJECT_0)
369 goto chk_console_input;
373 DWORD WINAPI DOSVM_Loop( HANDLE hThread )
379 objs[0] = GetStdHandle(STD_INPUT_HANDLE);
383 TRACE_(int)("waiting for action\n");
384 waitret = MsgWaitForMultipleObjects(2, objs, FALSE, INFINITE, QS_ALLINPUT);
385 if (waitret == WAIT_OBJECT_0) {
386 DOSVM_ProcessConsole();
388 else if (waitret == WAIT_OBJECT_0 + 1) {
390 if(!GetExitCodeThread(hThread, &rv)) {
391 ERR("Failed to get thread exit code!\n");
396 else if (waitret == WAIT_OBJECT_0 + 2) {
397 while (PeekMessageA(&msg,0,0,0,PM_REMOVE)) {
399 /* it's a window message */
400 DOSVM_ProcessMessage(&msg);
401 DispatchMessageA(&msg);
403 /* it's a thread message */
404 switch (msg.message) {
406 /* stop this madness!! */
409 /* run passed procedure in this thread */
410 /* (sort of like APC, but we signal the completion) */
412 DOS_SPC *spc = (DOS_SPC *)msg.lParam;
413 TRACE_(int)("calling %p with arg %08x\n", spc->proc, spc->arg);
414 (spc->proc)(spc->arg);
415 TRACE_(int)("done, signalling event %d\n", msg.wParam);
416 SetEvent(msg.wParam);
425 ERR_(int)("MsgWaitForMultipleObjects returned unexpected value.\n");
431 static WINE_EXCEPTION_FILTER(exception_handler)
433 EXCEPTION_RECORD *rec = GetExceptionInformation()->ExceptionRecord;
434 CONTEXT *context = GetExceptionInformation()->ContextRecord;
435 int ret, arg = rec->ExceptionInformation[0];
437 switch(rec->ExceptionCode) {
438 case EXCEPTION_VM86_INTx:
439 if (TRACE_ON(relay)) {
440 DPRINTF("Call DOS int 0x%02x ret=%04lx:%04lx\n",
441 arg, context->SegCs, context->Eip );
442 DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
443 context->Eax, context->Ebx, context->Ecx, context->Edx,
444 context->Esi, context->Edi );
445 DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
446 context->Ebp, context->Esp, context->SegDs, context->SegEs,
447 context->SegFs, context->SegGs, context->EFlags );
449 ret = DOSVM_SimulateInt(arg, context, FALSE);
450 if (TRACE_ON(relay)) {
451 DPRINTF("Ret DOS int 0x%02x ret=%04lx:%04lx\n",
452 arg, context->SegCs, context->Eip );
453 DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
454 context->Eax, context->Ebx, context->Ecx, context->Edx,
455 context->Esi, context->Edi );
456 DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
457 context->Ebp, context->Esp, context->SegDs, context->SegEs,
458 context->SegFs, context->SegGs, context->EFlags );
460 return ret ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_EXECUTION;
462 case EXCEPTION_VM86_STI:
463 /* case EXCEPTION_VM86_PICRETURN: */
465 EnterCriticalSection(&qcrit);
467 while (NtCurrentTeb()->alarms) {
468 DOSVM_QueueEvent(0,DOS_PRIORITY_REALTIME,NULL,NULL);
469 /* hmm, instead of relying on this signal counter, we should
470 * probably check how many ticks have *really* passed, probably using
471 * QueryPerformanceCounter() or something like that */
472 InterlockedDecrement(&(NtCurrentTeb()->alarms));
474 TRACE_(int)("context=%p, current=%p\n", context, current_context);
475 TRACE_(int)("cs:ip=%04lx:%04lx, ss:sp=%04lx:%04lx\n", context->SegCs, context->Eip, context->SegSs, context->Esp);
476 if (!ISV86(context)) {
477 ERR_(int)("@#&*%%, winedos signal handling is *still* messed up\n");
479 TRACE_(int)("DOS task enabled interrupts %s events pending, sending events (time=%ld)\n", IS_PEND(context)?"with":"without", GetTickCount());
480 DOSVM_SendQueuedEvents(context);
482 LeaveCriticalSection(&qcrit);
483 return EXCEPTION_CONTINUE_EXECUTION;
485 return EXCEPTION_CONTINUE_SEARCH;
488 int WINAPI DOSVM_Enter( CONTEXT86 *context )
490 CONTEXT86 *old_context = current_context;
492 current_context = context;
495 __wine_enter_vm86( context );
496 TRACE_(module)( "vm86 returned: %s\n", strerror(errno) );
498 __EXCEPT(exception_handler)
500 TRACE_(module)( "leaving vm86 mode\n" );
503 current_context = old_context;
507 /***********************************************************************
510 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val)
514 if ((port==0x20) && (val==0x20)) {
515 EnterCriticalSection(&qcrit);
517 /* EOI (End Of Interrupt) */
518 TRACE("received EOI for current IRQ, clearing\n");
519 event = current_event;
520 current_event = event->next;
522 (*event->relay)(NULL,event->data);
526 /* another event is pending, which we should probably
527 * be able to process now */
528 TRACE("another event pending, setting flag\n");
529 current_context->EFlags |= VIP_MASK;
532 WARN("EOI without active IRQ\n");
534 LeaveCriticalSection(&qcrit);
536 FIXME("unrecognized PIC command %02x\n",val);
540 /***********************************************************************
541 * SetTimer (WINEDOS.@)
543 void WINAPI DOSVM_SetTimer( UINT ticks )
545 struct itimerval tim;
548 /* the PC clocks ticks at 1193180 Hz */
549 tim.it_interval.tv_sec=0;
550 tim.it_interval.tv_usec=MulDiv(ticks,1000000,1193180);
552 if (!tim.it_interval.tv_usec) tim.it_interval.tv_usec=1;
553 /* first tick value */
554 tim.it_value = tim.it_interval;
555 TRACE_(int)("setting timer tick delay to %ld us\n", tim.it_interval.tv_usec);
556 setitimer(ITIMER_REAL, &tim, NULL);
560 /***********************************************************************
561 * GetTimer (WINEDOS.@)
563 UINT WINAPI DOSVM_GetTimer( void )
565 struct itimerval tim;
568 getitimer(ITIMER_REAL, &tim);
569 return MulDiv(tim.it_value.tv_usec,1193180,1000000);
574 #else /* !MZ_SUPPORTED */
576 /***********************************************************************
579 INT WINAPI DOSVM_Enter( CONTEXT86 *context )
581 ERR_(module)("DOS realmode not supported on this architecture!\n");
585 /***********************************************************************
588 void WINAPI DOSVM_Wait( INT read_pipe, HANDLE hObject) {}
590 /***********************************************************************
593 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val) {}
595 /***********************************************************************
596 * SetTimer (WINEDOS.@)
598 void WINAPI DOSVM_SetTimer( UINT ticks ) {}
600 /***********************************************************************
601 * GetTimer (WINEDOS.@)
603 UINT WINAPI DOSVM_GetTimer( void ) { return 0; }
605 /***********************************************************************
606 * QueueEvent (WINEDOS.@)
608 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
611 /* callback event, perform it with dummy context */
613 memset(&context,0,sizeof(context));
614 (*relay)(&context,data);
616 ERR("IRQ without DOS task: should not happen");
622 /**********************************************************************
625 * Return the real mode interrupt vector for a given interrupt.
627 FARPROC16 DOSVM_GetRMHandler( BYTE intnum )
629 return ((FARPROC16*)DOSMEM_SystemBase())[intnum];
633 /**********************************************************************
636 * Set the real mode interrupt handler for a given interrupt.
638 void DOSVM_SetRMHandler( BYTE intnum, FARPROC16 handler )
640 TRACE("Set real mode interrupt vector %02x <- %04x:%04x\n",
641 intnum, HIWORD(handler), LOWORD(handler) );
642 ((FARPROC16*)DOSMEM_SystemBase())[intnum] = handler;
646 static const INTPROC real_mode_handlers[] =
648 /* 00 */ 0, 0, 0, 0, 0, 0, 0, 0,
649 /* 08 */ 0, DOSVM_Int09Handler, 0, 0, 0, 0, 0, 0,
650 /* 10 */ DOSVM_Int10Handler, INT_Int11Handler, INT_Int12Handler, INT_Int13Handler,
651 0, INT_Int15Handler, DOSVM_Int16Handler, DOSVM_Int17Handler,
652 /* 18 */ 0, 0, INT_Int1aHandler, 0, 0, 0, 0, 0,
653 /* 20 */ DOSVM_Int20Handler, DOSVM_Int21Handler, 0, 0, 0, INT_Int25Handler, 0, 0,
654 /* 28 */ 0, DOSVM_Int29Handler, INT_Int2aHandler, 0, 0, 0, 0, INT_Int2fHandler,
655 /* 30 */ 0, DOSVM_Int31Handler, 0, DOSVM_Int33Handler, 0, 0, 0, 0,
656 /* 38 */ 0, 0, 0, 0, 0, 0, 0, 0,
657 /* 40 */ 0, 0, 0, 0, 0, 0, 0, 0,
658 /* 48 */ 0, 0, 0, 0, 0, 0, 0, 0,
659 /* 50 */ 0, 0, 0, 0, 0, 0, 0, 0,
660 /* 58 */ 0, 0, 0, 0, 0, 0, 0, 0,
661 /* 60 */ 0, 0, 0, 0, 0, 0, 0, DOSVM_Int67Handler
665 /**********************************************************************
666 * DOSVM_RealModeInterrupt
668 * Handle real mode interrupts
670 void DOSVM_RealModeInterrupt( BYTE intnum, CONTEXT86 *context )
672 if (intnum < sizeof(real_mode_handlers)/sizeof(INTPROC) && real_mode_handlers[intnum])
673 (*real_mode_handlers[intnum])(context);
676 FIXME("Unknown Interrupt in DOS mode: 0x%x\n", intnum);
677 FIXME(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx\n",
678 context->Eax, context->Ebx, context->Ecx, context->Edx);
679 FIXME(" esi=%08lx edi=%08lx ds=%04lx es=%04lx\n",
680 context->Esi, context->Edi, context->SegDs, context->SegEs );
685 /**********************************************************************
688 BOOL WINAPI DOSVM_Init( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
690 TRACE_(module)("(0x%08x,%ld,%p)\n", hinstDLL, fdwReason, lpvReserved);
692 if (fdwReason == DLL_PROCESS_ATTACH)
694 /* initialize the memory */
695 TRACE("Initializing DOS memory structures\n");
697 DOSDEV_InstallDOSDevices();
700 event_notifier = CreateEventA(NULL, FALSE, FALSE, NULL);
702 ERR("Failed to create event object!\n");