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( LPVOID lpExtra )
375 HANDLE obj = GetStdHandle(STD_INPUT_HANDLE);
380 TRACE_(int)("waiting for action\n");
381 waitret = MsgWaitForMultipleObjects(1, &obj, FALSE, INFINITE, QS_ALLINPUT);
382 if (waitret == WAIT_OBJECT_0) {
383 DOSVM_ProcessConsole();
385 else if (waitret == WAIT_OBJECT_0 + 1) {
386 while (PeekMessageA(&msg,0,0,0,PM_REMOVE)) {
388 /* it's a window message */
389 DOSVM_ProcessMessage(&msg);
390 DispatchMessageA(&msg);
392 /* it's a thread message */
393 switch (msg.message) {
395 /* stop this madness!! */
398 /* run passed procedure in this thread */
399 /* (sort of like APC, but we signal the completion) */
401 DOS_SPC *spc = (DOS_SPC *)msg.lParam;
402 TRACE_(int)("calling %p with arg %08x\n", spc->proc, spc->arg);
403 (spc->proc)(spc->arg);
404 TRACE_(int)("done, signalling event %d\n", msg.wParam);
405 SetEvent(msg.wParam);
414 ERR_(int)("MsgWaitForMultipleObjects returned unexpected value.\n");
420 static WINE_EXCEPTION_FILTER(exception_handler)
422 EXCEPTION_RECORD *rec = GetExceptionInformation()->ExceptionRecord;
423 CONTEXT *context = GetExceptionInformation()->ContextRecord;
424 int ret, arg = rec->ExceptionInformation[0];
426 switch(rec->ExceptionCode) {
427 case EXCEPTION_VM86_INTx:
428 if (TRACE_ON(relay)) {
429 DPRINTF("Call DOS int 0x%02x ret=%04lx:%04lx\n",
430 arg, context->SegCs, context->Eip );
431 DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
432 context->Eax, context->Ebx, context->Ecx, context->Edx,
433 context->Esi, context->Edi );
434 DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
435 context->Ebp, context->Esp, context->SegDs, context->SegEs,
436 context->SegFs, context->SegGs, context->EFlags );
438 ret = DOSVM_SimulateInt(arg, context, FALSE);
439 if (TRACE_ON(relay)) {
440 DPRINTF("Ret 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 return ret ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_EXECUTION;
451 case EXCEPTION_VM86_STI:
452 /* case EXCEPTION_VM86_PICRETURN: */
454 EnterCriticalSection(&qcrit);
456 while (NtCurrentTeb()->alarms) {
457 DOSVM_QueueEvent(0,DOS_PRIORITY_REALTIME,NULL,NULL);
458 /* hmm, instead of relying on this signal counter, we should
459 * probably check how many ticks have *really* passed, probably using
460 * QueryPerformanceCounter() or something like that */
461 InterlockedDecrement(&(NtCurrentTeb()->alarms));
463 TRACE_(int)("context=%p, current=%p\n", context, current_context);
464 TRACE_(int)("cs:ip=%04lx:%04lx, ss:sp=%04lx:%04lx\n", context->SegCs, context->Eip, context->SegSs, context->Esp);
465 if (!ISV86(context)) {
466 ERR_(int)("@#&*%%, winedos signal handling is *still* messed up\n");
468 TRACE_(int)("DOS task enabled interrupts %s events pending, sending events (time=%ld)\n", IS_PEND(context)?"with":"without", GetTickCount());
469 DOSVM_SendQueuedEvents(context);
471 LeaveCriticalSection(&qcrit);
472 return EXCEPTION_CONTINUE_EXECUTION;
474 return EXCEPTION_CONTINUE_SEARCH;
477 int WINAPI DOSVM_Enter( CONTEXT86 *context )
479 CONTEXT86 *old_context = current_context;
481 current_context = context;
484 __wine_enter_vm86( context );
485 TRACE_(module)( "vm86 returned: %s\n", strerror(errno) );
487 __EXCEPT(exception_handler)
489 TRACE_(module)( "leaving vm86 mode\n" );
492 current_context = old_context;
496 /***********************************************************************
499 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val)
503 if ((port==0x20) && (val==0x20)) {
504 EnterCriticalSection(&qcrit);
506 /* EOI (End Of Interrupt) */
507 TRACE("received EOI for current IRQ, clearing\n");
508 event = current_event;
509 current_event = event->next;
511 (*event->relay)(NULL,event->data);
515 /* another event is pending, which we should probably
516 * be able to process now */
517 TRACE("another event pending, setting flag\n");
518 current_context->EFlags |= VIP_MASK;
521 WARN("EOI without active IRQ\n");
523 LeaveCriticalSection(&qcrit);
525 FIXME("unrecognized PIC command %02x\n",val);
529 /***********************************************************************
530 * SetTimer (WINEDOS.@)
532 void WINAPI DOSVM_SetTimer( UINT ticks )
534 struct itimerval tim;
537 /* the PC clocks ticks at 1193180 Hz */
538 tim.it_interval.tv_sec=0;
539 tim.it_interval.tv_usec=MulDiv(ticks,1000000,1193180);
541 if (!tim.it_interval.tv_usec) tim.it_interval.tv_usec=1;
542 /* first tick value */
543 tim.it_value = tim.it_interval;
544 TRACE_(int)("setting timer tick delay to %ld us\n", tim.it_interval.tv_usec);
545 setitimer(ITIMER_REAL, &tim, NULL);
549 /***********************************************************************
550 * GetTimer (WINEDOS.@)
552 UINT WINAPI DOSVM_GetTimer( void )
554 struct itimerval tim;
557 getitimer(ITIMER_REAL, &tim);
558 return MulDiv(tim.it_value.tv_usec,1193180,1000000);
563 #else /* !MZ_SUPPORTED */
565 /***********************************************************************
568 INT WINAPI DOSVM_Enter( CONTEXT86 *context )
570 ERR_(module)("DOS realmode not supported on this architecture!\n");
574 /***********************************************************************
577 void WINAPI DOSVM_Wait( INT read_pipe, HANDLE hObject) {}
579 /***********************************************************************
582 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val) {}
584 /***********************************************************************
585 * SetTimer (WINEDOS.@)
587 void WINAPI DOSVM_SetTimer( UINT ticks ) {}
589 /***********************************************************************
590 * GetTimer (WINEDOS.@)
592 UINT WINAPI DOSVM_GetTimer( void ) { return 0; }
594 /***********************************************************************
595 * QueueEvent (WINEDOS.@)
597 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
600 /* callback event, perform it with dummy context */
602 memset(&context,0,sizeof(context));
603 (*relay)(&context,data);
605 ERR("IRQ without DOS task: should not happen");
611 /**********************************************************************
614 * Return the real mode interrupt vector for a given interrupt.
616 FARPROC16 DOSVM_GetRMHandler( BYTE intnum )
618 return ((FARPROC16*)DOSMEM_SystemBase())[intnum];
622 /**********************************************************************
625 * Set the real mode interrupt handler for a given interrupt.
627 void DOSVM_SetRMHandler( BYTE intnum, FARPROC16 handler )
629 TRACE("Set real mode interrupt vector %02x <- %04x:%04x\n",
630 intnum, HIWORD(handler), LOWORD(handler) );
631 ((FARPROC16*)DOSMEM_SystemBase())[intnum] = handler;
635 static const INTPROC real_mode_handlers[] =
637 /* 00 */ 0, 0, 0, 0, 0, 0, 0, 0,
638 /* 08 */ 0, DOSVM_Int09Handler, 0, 0, 0, 0, 0, 0,
639 /* 10 */ DOSVM_Int10Handler, INT_Int11Handler, INT_Int12Handler, INT_Int13Handler,
640 0, INT_Int15Handler, DOSVM_Int16Handler, DOSVM_Int17Handler,
641 /* 18 */ 0, 0, INT_Int1aHandler, 0, 0, 0, 0, 0,
642 /* 20 */ DOSVM_Int20Handler, DOSVM_Int21Handler, 0, 0, 0, INT_Int25Handler, 0, 0,
643 /* 28 */ 0, DOSVM_Int29Handler, INT_Int2aHandler, 0, 0, 0, 0, INT_Int2fHandler,
644 /* 30 */ 0, DOSVM_Int31Handler, 0, DOSVM_Int33Handler, 0, 0, 0, 0,
645 /* 38 */ 0, 0, 0, 0, 0, 0, 0, 0,
646 /* 40 */ 0, 0, 0, 0, 0, 0, 0, 0,
647 /* 48 */ 0, 0, 0, 0, 0, 0, 0, 0,
648 /* 50 */ 0, 0, 0, 0, 0, 0, 0, 0,
649 /* 58 */ 0, 0, 0, 0, 0, 0, 0, 0,
650 /* 60 */ 0, 0, 0, 0, 0, 0, 0, DOSVM_Int67Handler
654 /**********************************************************************
655 * DOSVM_RealModeInterrupt
657 * Handle real mode interrupts
659 void DOSVM_RealModeInterrupt( BYTE intnum, CONTEXT86 *context )
661 if (intnum < sizeof(real_mode_handlers)/sizeof(INTPROC) && real_mode_handlers[intnum])
662 (*real_mode_handlers[intnum])(context);
665 FIXME("Unknown Interrupt in DOS mode: 0x%x\n", intnum);
666 FIXME(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx\n",
667 context->Eax, context->Ebx, context->Ecx, context->Edx);
668 FIXME(" esi=%08lx edi=%08lx ds=%04lx es=%04lx\n",
669 context->Esi, context->Edi, context->SegDs, context->SegEs );
674 /**********************************************************************
677 BOOL WINAPI DOSVM_Init( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
679 TRACE_(module)("(0x%08x,%ld,%p)\n", hinstDLL, fdwReason, lpvReserved);
681 if (fdwReason == DLL_PROCESS_ATTACH)
683 /* initialize the memory */
684 TRACE("Initializing DOS memory structures\n");
686 DOSDEV_InstallDOSDevices();
689 event_notifier = CreateEventA(NULL, FALSE, FALSE, NULL);
691 ERR("Failed to create event object!\n");