Added some missing functions.
[wine] / dlls / winedos / dosvm.c
1 /*
2  * DOS Virtual Machine
3  *
4  * Copyright 1998 Ove Kåven
5  *
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.
10  *
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.
15  *
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
19  *
20  * Note: This code hasn't been completely cleaned up yet.
21  */
22
23 #include "config.h"
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <signal.h>
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34 #ifdef HAVE_SYS_TIME_H
35 # include <sys/time.h>
36 #endif
37 #include <sys/types.h>
38
39 #include "wine/winbase16.h"
40 #include "wine/exception.h"
41 #include "windef.h"
42 #include "winbase.h"
43 #include "wingdi.h"
44 #include "winuser.h"
45 #include "winnt.h"
46 #include "wincon.h"
47
48 #include "thread.h"
49 #include "msdos.h"
50 #include "file.h"
51 #include "miscemu.h"
52 #include "dosexe.h"
53 #include "dosvm.h"
54 #include "wine/debug.h"
55 #include "excpt.h"
56
57 WINE_DEFAULT_DEBUG_CHANNEL(int);
58 WINE_DECLARE_DEBUG_CHANNEL(module);
59 WINE_DECLARE_DEBUG_CHANNEL(relay);
60
61 WORD DOSVM_psp = 0;
62 WORD DOSVM_retval = 0;
63
64 #ifdef HAVE_SYS_MMAN_H
65 # include <sys/mman.h>
66 #endif
67
68
69 typedef struct _DOSEVENT {
70   int irq,priority;
71   DOSRELAY relay;
72   void *data;
73   struct _DOSEVENT *next;
74 } DOSEVENT, *LPDOSEVENT;
75
76 static struct _DOSEVENT *pending_event, *current_event;
77 static HANDLE event_notifier;
78
79 static CRITICAL_SECTION qcrit;
80 static CRITICAL_SECTION_DEBUG critsect_debug =
81 {
82     0, 0, &qcrit,
83     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
84       0, 0, { 0, (DWORD)(__FILE__ ": qcrit") }
85 };
86 static CRITICAL_SECTION qcrit = { &critsect_debug, -1, 0, 0, 0, 0 };
87
88
89 /***********************************************************************
90  *              DOSVM_HasPendingEvents
91  *
92  * Return true if there are pending events that are not
93  * blocked by currently active event.
94  */
95 static BOOL DOSVM_HasPendingEvents( void )
96 {   
97     if (!pending_event)
98         return FALSE;
99
100     if (!current_event)
101         return TRUE;
102
103     if (pending_event->priority < current_event->priority)
104         return TRUE;
105
106     return FALSE;
107 }
108
109
110 /***********************************************************************
111  *              DOSVM_SendOneEvent
112  *
113  * Process single pending event.
114  *
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.
120  */
121 static void DOSVM_SendOneEvent( CONTEXT86 *context )
122 {
123     LPDOSEVENT event = pending_event;
124
125     /* Remove from pending events list. */
126     pending_event = event->next;
127
128     /* Process active event. */
129     if (event->irq >= 0) 
130     {
131         BYTE intnum = (event->irq < 8) ?
132             (event->irq + 8) : (event->irq - 8 + 0x70);
133             
134         /* Event is an IRQ, move it to current events list. */
135         event->next = current_event;
136         current_event = event;
137
138         TRACE( "Dispatching IRQ %d.\n", event->irq );
139
140         if (ISV86(context))
141         {
142             /* 
143              * Note that if DOSVM_HardwareInterruptRM calls an internal 
144              * interrupt directly, current_event might be cleared 
145              * (and event freed) in this call.
146              */
147             LeaveCriticalSection(&qcrit);
148             DOSVM_HardwareInterruptRM( context, intnum );
149             EnterCriticalSection(&qcrit);
150         }
151         else
152         {
153             /*
154              * This routine only modifies current context so it is
155              * not necessary to release critical section.
156              */
157             DOSVM_HardwareInterruptPM( context, intnum );
158         }
159     } 
160     else 
161     {
162         /* Callback event. */
163         TRACE( "Dispatching callback event.\n" );
164
165         if (ISV86(context))
166         {
167             /*
168              * Call relay immediately in real mode.
169              */
170             LeaveCriticalSection(&qcrit);
171             (*event->relay)( context, event->data );
172             EnterCriticalSection(&qcrit);
173         }
174         else
175         {
176             /*
177              * Force return to relay code. We do not want to
178              * call relay directly because we may be inside a signal handler.
179              */
180             DOSVM_BuildCallFrame( context, event->relay, event->data );
181         }
182
183         free(event);
184     }
185 }
186
187
188 /***********************************************************************
189  *              DOSVM_SendQueuedEvents
190  *
191  * As long as context instruction pointer stays unmodified,
192  * process all pending events that are not blocked by currently
193  * active event.
194  *
195  * This routine assumes that caller has already cleared TEB.vm86_pending 
196  * and checked that interrupts are enabled.
197  */
198 void DOSVM_SendQueuedEvents( CONTEXT86 *context )
199 {   
200     DWORD old_cs = context->SegCs;
201     DWORD old_ip = context->Eip;
202
203     EnterCriticalSection(&qcrit);
204
205     TRACE( "Called in %s mode %s events pending (time=%ld)\n",
206            ISV86(context) ? "real" : "protected",
207            DOSVM_HasPendingEvents() ? "with" : "without",
208            GetTickCount() );
209     TRACE( "cs:ip=%04lx:%08lx, ss:sp=%04lx:%08lx\n",
210            context->SegCs, context->Eip, context->SegSs, context->Esp);
211
212     while (context->SegCs == old_cs &&
213            context->Eip == old_ip &&
214            DOSVM_HasPendingEvents())
215     {
216         DOSVM_SendOneEvent(context);
217
218         /*
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.
222          */
223         NtCurrentTeb()->vm86_pending = 0;
224     }
225
226 #ifdef MZ_SUPPORTED
227
228     if (!ISV86(context) && context->SegCs == old_cs && context->Eip == old_ip)
229     {
230         /*
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.
234          */
235         TRACE( "Called but there was nothing to do, calling NULL relay.\n" );
236         DOSVM_BuildCallFrame( context, NULL, NULL );
237     }
238
239     if (DOSVM_HasPendingEvents())
240     {
241         /*
242          * Interrupts disabled, but there are still
243          * pending events, make sure that pending flag is turned on.
244          */
245         TRACE( "Another event is pending, setting VIP flag.\n" );
246         NtCurrentTeb()->vm86_pending |= VIP_MASK;
247     }
248
249 #else
250
251     FIXME("No DOS .exe file support on this platform (yet)\n");
252
253 #endif /* MZ_SUPPORTED */
254
255     LeaveCriticalSection(&qcrit);
256 }
257
258
259 #ifdef MZ_SUPPORTED
260 /***********************************************************************
261  *              QueueEvent (WINEDOS.@)
262  */
263 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
264 {
265   LPDOSEVENT event, cur, prev;
266   BOOL       old_pending;
267
268   if (MZ_Current()) {
269     event = malloc(sizeof(DOSEVENT));
270     if (!event) {
271       ERR("out of memory allocating event entry\n");
272       return;
273     }
274     event->irq = irq; event->priority = priority;
275     event->relay = relay; event->data = data;
276
277     EnterCriticalSection(&qcrit);
278     old_pending = DOSVM_HasPendingEvents();
279
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) {
284       prev = cur;
285       cur = cur->next;
286     }
287     event->next = cur;
288     if (prev) prev->next = event;
289     else pending_event = event;
290
291     if (!old_pending && DOSVM_HasPendingEvents()) {
292       TRACE("new event queued, signalling (time=%ld)\n", GetTickCount());
293       
294       /* Alert VM86 thread about the new event. */
295       kill(dosvm_pid,SIGUSR2);
296
297       /* Wake up DOSVM_Wait so that it can serve pending events. */
298       SetEvent(event_notifier);
299     } else {
300       TRACE("new event queued (time=%ld)\n", GetTickCount());
301     }
302
303     LeaveCriticalSection(&qcrit);
304   } else {
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) */
308     if (irq<0) {
309       /* callback event, perform it with dummy context */
310       CONTEXT86 context;
311       memset(&context,0,sizeof(context));
312       (*relay)(&context,data);
313     } else {
314       ERR("IRQ without DOS task: should not happen\n");
315     }
316   }
317 }
318
319 static void DOSVM_ProcessConsole(void)
320 {
321   INPUT_RECORD msg;
322   DWORD res;
323   BYTE scan, ascii;
324
325   if (ReadConsoleInputA(GetStdHandle(STD_INPUT_HANDLE),&msg,1,&res)) {
326     switch (msg.EventType) {
327     case KEY_EVENT:
328       scan = msg.Event.KeyEvent.wVirtualScanCode;
329       ascii = msg.Event.KeyEvent.uChar.AsciiChar;
330       TRACE("scan %02x, ascii %02x\n", scan, ascii);
331
332       /* set the "break" (release) flag if key released */
333       if (!msg.Event.KeyEvent.bKeyDown) scan |= 0x80;
334
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);
339       }
340       DOSVM_Int09SendScan(scan, ascii);
341       break;
342     case MOUSE_EVENT:
343       DOSVM_Int33Console(&msg.Event.MouseEvent);
344       break;
345     case WINDOW_BUFFER_SIZE_EVENT:
346       FIXME("unhandled WINDOW_BUFFER_SIZE_EVENT.\n");
347       break;
348     case MENU_EVENT:
349       FIXME("unhandled MENU_EVENT.\n");
350       break;
351     case FOCUS_EVENT:
352       FIXME("unhandled FOCUS_EVENT.\n");
353       break;
354     default:
355       FIXME("unknown console event: %d\n", msg.EventType);
356     }
357   }
358 }
359
360 static void DOSVM_ProcessMessage(MSG *msg)
361 {
362   BYTE scan = 0;
363
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);
368   } else {
369     switch (msg->message) {
370     case WM_KEYUP:
371       scan = 0x80;
372     case WM_KEYDOWN:
373       scan |= (msg->lParam >> 16) & 0x7f;
374
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);
382       }
383       DOSVM_Int09SendScan(scan,0);
384       break;
385     }
386   }
387 }
388
389
390 /***********************************************************************
391  *              DOSVM_Wait
392  *
393  * Wait for asynchronous events. This routine temporarily enables
394  * interrupts and waits until some asynchronous event has been 
395  * processed.
396  */
397 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx )
398 {
399     if (DOSVM_HasPendingEvents())
400     {
401         CONTEXT86 context = *waitctx;
402         
403         /*
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
408          * to real mode.
409          *
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?
413          */
414         if (!ISV86(&context))
415         {
416             context.EFlags |= V86_FLAG;
417             context.SegSs = 0xffff;
418             context.Esp = 0;
419         }
420
421         context.EFlags |= VIF_MASK;
422         context.SegCs = 0;
423         context.Eip = 0;
424
425         DOSVM_SendQueuedEvents(&context);
426
427         if(context.SegCs || context.Eip)
428             DPMI_CallRMProc( &context, NULL, 0, TRUE );
429     }
430     else
431     {
432         HANDLE objs[2];
433         int    objc = DOSVM_IsWin16() ? 2 : 1;
434         DWORD  waitret;
435
436         objs[0] = event_notifier;
437         objs[1] = GetStdHandle(STD_INPUT_HANDLE);
438
439         waitret = MsgWaitForMultipleObjects( objc, objs, FALSE, 
440                                              INFINITE, QS_ALLINPUT );
441         
442         if (waitret == WAIT_OBJECT_0)
443         {
444             /*
445              * New pending event has been queued, we ignore it
446              * here because it will be processed on next call to
447              * DOSVM_Wait.
448              */
449         }
450         else if (objc == 2 && waitret == WAIT_OBJECT_0 + 1)
451         {
452             DOSVM_ProcessConsole();
453         }
454         else if (waitret == WAIT_OBJECT_0 + objc)
455         {
456             MSG msg;
457             while (PeekMessageA(&msg,0,0,0,PM_REMOVE|PM_NOYIELD)) 
458             {
459                 /* got a message */
460                 DOSVM_ProcessMessage(&msg);
461                 /* we don't need a TranslateMessage here */
462                 DispatchMessageA(&msg);
463             }
464         }
465         else
466         {
467             ERR_(module)( "dosvm wait error=%ld\n", GetLastError() );
468         }
469     }
470 }
471
472
473 DWORD WINAPI DOSVM_Loop( HANDLE hThread )
474 {
475   HANDLE objs[2];
476   MSG msg;
477   DWORD waitret;
478
479   objs[0] = GetStdHandle(STD_INPUT_HANDLE);
480   objs[1] = hThread;
481
482   for(;;) {
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();
487       }
488       else if (waitret == WAIT_OBJECT_0 + 1) {
489          DWORD rv;
490          if(!GetExitCodeThread(hThread, &rv)) {
491              ERR("Failed to get thread exit code!\n");
492              rv = 0;
493          }
494          return rv;
495       }
496       else if (waitret == WAIT_OBJECT_0 + 2) {
497           while (PeekMessageA(&msg,0,0,0,PM_REMOVE)) {
498               if (msg.hwnd) {
499                   /* it's a window message */
500                   DOSVM_ProcessMessage(&msg);
501                   DispatchMessageA(&msg);
502               } else {
503                   /* it's a thread message */
504                   switch (msg.message) {
505                   case WM_QUIT:
506                       /* stop this madness!! */
507                       return 0;
508                   case WM_USER:
509                       /* run passed procedure in this thread */
510                       /* (sort of like APC, but we signal the completion) */
511                       {
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 );
517                       }
518                       break;
519                   default:
520                       DispatchMessageA(&msg);
521                   }
522               }
523           }
524       }
525       else
526       {
527           ERR_(int)("MsgWaitForMultipleObjects returned unexpected value.\n");
528           return 0;
529       }
530   }
531 }
532
533 static WINE_EXCEPTION_FILTER(exception_handler)
534 {
535   EXCEPTION_RECORD *rec = GetExceptionInformation()->ExceptionRecord;
536   CONTEXT *context = GetExceptionInformation()->ContextRecord;
537   int arg = rec->ExceptionInformation[0];
538   BOOL ret;
539
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 );
551       }
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 );
562     }
563     return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
564
565   case EXCEPTION_VM86_STI:
566   /* case EXCEPTION_VM86_PICRETURN: */
567     if (!ISV86(context))
568       ERR( "Protected mode STI caught by real mode handler!\n" );
569
570     context->EFlags |= VIF_MASK;
571     context->EFlags &= ~VIP_MASK;
572     DOSVM_SendQueuedEvents(context);
573     return EXCEPTION_CONTINUE_EXECUTION;
574   }
575   return EXCEPTION_CONTINUE_SEARCH;
576 }
577
578 int WINAPI DOSVM_Enter( CONTEXT86 *context )
579 {
580   if (!ISV86(context))
581       ERR( "Called with protected mode context!\n" );
582
583   __TRY
584   {
585     __wine_enter_vm86( context );
586     TRACE_(module)( "vm86 returned: %s\n", strerror(errno) );
587   }
588   __EXCEPT(exception_handler)
589   {
590     TRACE_(module)( "leaving vm86 mode\n" );
591   }
592   __ENDTRY
593
594   return 0;
595 }
596
597 /***********************************************************************
598  *              OutPIC (WINEDOS.@)
599  */
600 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val)
601 {
602     LPDOSEVENT event;
603
604     if ((port==0x20) && (val==0x20)) {
605       EnterCriticalSection(&qcrit);
606       if (current_event) {
607         /* EOI (End Of Interrupt) */
608         TRACE("received EOI for current IRQ, clearing\n");
609         event = current_event;
610         current_event = event->next;
611         if (event->relay)
612         (*event->relay)(NULL,event->data);
613         free(event);
614
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;
620         }
621       } else {
622         WARN("EOI without active IRQ\n");
623       }
624       LeaveCriticalSection(&qcrit);
625     } else {
626       FIXME("unrecognized PIC command %02x\n",val);
627     }
628 }
629
630 #else /* !MZ_SUPPORTED */
631
632 /***********************************************************************
633  *              Enter (WINEDOS.@)
634  */
635 INT WINAPI DOSVM_Enter( CONTEXT86 *context )
636 {
637  ERR_(module)("DOS realmode not supported on this architecture!\n");
638  return -1;
639 }
640
641 /***********************************************************************
642  *              Wait (WINEDOS.@)
643  */
644 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx ) { }
645
646 /***********************************************************************
647  *              OutPIC (WINEDOS.@)
648  */
649 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val) {}
650
651 /***********************************************************************
652  *              QueueEvent (WINEDOS.@)
653  */
654 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
655 {
656   if (irq<0) {
657     /* callback event, perform it with dummy context */
658     CONTEXT86 context;
659     memset(&context,0,sizeof(context));
660     (*relay)(&context,data);
661   } else {
662     ERR("IRQ without DOS task: should not happen\n");
663   }
664 }
665
666 #endif /* MZ_SUPPORTED */
667
668
669 /**********************************************************************
670  *         DOSVM_AcknowledgeIRQ
671  *
672  * This routine should be called by all internal IRQ handlers.
673  */
674 void WINAPI DOSVM_AcknowledgeIRQ( CONTEXT86 *context )
675 {
676     /*
677      * Send EOI to PIC.
678      */
679     DOSVM_PIC_ioport_out( 0x20, 0x20 );
680
681     /*
682      * Protected mode IRQ handlers are supposed
683      * to turn VIF flag on before they return.
684      */
685     if (!ISV86(context))
686         NtCurrentTeb()->dpmi_vif = 1;
687 }
688
689
690 /**********************************************************************
691  *          DllMain  (DOSVM.Init)
692  */
693 BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
694 {
695     TRACE_(module)("(%p,%ld,%p)\n", hinstDLL, fdwReason, lpvReserved);
696
697     if (fdwReason == DLL_PROCESS_ATTACH)
698     {
699         DisableThreadLibraryCalls(hinstDLL);
700         DOSVM_InitSegments();
701
702         event_notifier = CreateEventA(NULL, FALSE, FALSE, NULL);
703         if(!event_notifier)
704           ERR("Failed to create event object!\n");
705     }
706     return TRUE;
707 }