Removed references to obsolete configuration entries.
[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 #include "wine/port.h"
25
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <signal.h>
33 #ifdef HAVE_UNISTD_H
34 # include <unistd.h>
35 #endif
36 #ifdef HAVE_SYS_TIME_H
37 # include <sys/time.h>
38 #endif
39 #include <sys/types.h>
40
41 #include "wine/winbase16.h"
42 #include "wine/exception.h"
43 #include "windef.h"
44 #include "winbase.h"
45 #include "wingdi.h"
46 #include "winuser.h"
47 #include "wownt32.h"
48 #include "winnt.h"
49 #include "wincon.h"
50
51 #include "thread.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 (DOSVM_HasPendingEvents())
229     {
230         /*
231          * Interrupts disabled, but there are still
232          * pending events, make sure that pending flag is turned on.
233          */
234         TRACE( "Another event is pending, setting VIP flag.\n" );
235         NtCurrentTeb()->vm86_pending |= VIP_MASK;
236     }
237
238 #else
239
240     FIXME("No DOS .exe file support on this platform (yet)\n");
241
242 #endif /* MZ_SUPPORTED */
243
244     LeaveCriticalSection(&qcrit);
245 }
246
247
248 #ifdef MZ_SUPPORTED
249 /***********************************************************************
250  *              QueueEvent (WINEDOS.@)
251  */
252 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
253 {
254   LPDOSEVENT event, cur, prev;
255   BOOL       old_pending;
256
257   if (MZ_Current()) {
258     event = malloc(sizeof(DOSEVENT));
259     if (!event) {
260       ERR("out of memory allocating event entry\n");
261       return;
262     }
263     event->irq = irq; event->priority = priority;
264     event->relay = relay; event->data = data;
265
266     EnterCriticalSection(&qcrit);
267     old_pending = DOSVM_HasPendingEvents();
268
269     /* insert event into linked list, in order *after*
270      * all earlier events of higher or equal priority */
271     cur = pending_event; prev = NULL;
272     while (cur && cur->priority<=priority) {
273       prev = cur;
274       cur = cur->next;
275     }
276     event->next = cur;
277     if (prev) prev->next = event;
278     else pending_event = event;
279
280     if (!old_pending && DOSVM_HasPendingEvents()) {
281       TRACE("new event queued, signalling (time=%ld)\n", GetTickCount());
282       
283       /* Alert VM86 thread about the new event. */
284       kill(dosvm_pid,SIGUSR2);
285
286       /* Wake up DOSVM_Wait so that it can serve pending events. */
287       SetEvent(event_notifier);
288     } else {
289       TRACE("new event queued (time=%ld)\n", GetTickCount());
290     }
291
292     LeaveCriticalSection(&qcrit);
293   } else {
294     /* DOS subsystem not running */
295     /* (this probably means that we're running a win16 app
296      *  which uses DPMI to thunk down to DOS services) */
297     if (irq<0) {
298       /* callback event, perform it with dummy context */
299       CONTEXT86 context;
300       memset(&context,0,sizeof(context));
301       (*relay)(&context,data);
302     } else {
303       ERR("IRQ without DOS task: should not happen\n");
304     }
305   }
306 }
307
308 static void DOSVM_ProcessConsole(void)
309 {
310   INPUT_RECORD msg;
311   DWORD res;
312   BYTE scan, ascii;
313
314   if (ReadConsoleInputA(GetStdHandle(STD_INPUT_HANDLE),&msg,1,&res)) {
315     switch (msg.EventType) {
316     case KEY_EVENT:
317       scan = msg.Event.KeyEvent.wVirtualScanCode;
318       ascii = msg.Event.KeyEvent.uChar.AsciiChar;
319       TRACE("scan %02x, ascii %02x\n", scan, ascii);
320
321       /* set the "break" (release) flag if key released */
322       if (!msg.Event.KeyEvent.bKeyDown) scan |= 0x80;
323
324       /* check whether extended bit is set,
325        * and if so, queue the extension prefix */
326       if (msg.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY) {
327         DOSVM_Int09SendScan(0xE0,0);
328       }
329       DOSVM_Int09SendScan(scan, ascii);
330       break;
331     case MOUSE_EVENT:
332       DOSVM_Int33Console(&msg.Event.MouseEvent);
333       break;
334     case WINDOW_BUFFER_SIZE_EVENT:
335       FIXME("unhandled WINDOW_BUFFER_SIZE_EVENT.\n");
336       break;
337     case MENU_EVENT:
338       FIXME("unhandled MENU_EVENT.\n");
339       break;
340     case FOCUS_EVENT:
341       FIXME("unhandled FOCUS_EVENT.\n");
342       break;
343     default:
344       FIXME("unknown console event: %d\n", msg.EventType);
345     }
346   }
347 }
348
349 static void DOSVM_ProcessMessage(MSG *msg)
350 {
351   BYTE scan = 0;
352
353   TRACE("got message %04x, wparam=%08x, lparam=%08lx\n",msg->message,msg->wParam,msg->lParam);
354   if ((msg->message>=WM_MOUSEFIRST)&&
355       (msg->message<=WM_MOUSELAST)) {
356     DOSVM_Int33Message(msg->message,msg->wParam,msg->lParam);
357   } else {
358     switch (msg->message) {
359     case WM_KEYUP:
360       scan = 0x80;
361     case WM_KEYDOWN:
362       scan |= (msg->lParam >> 16) & 0x7f;
363
364       /* check whether extended bit is set,
365        * and if so, queue the extension prefix */
366       if (msg->lParam & 0x1000000) {
367         /* FIXME: some keys (function keys) have
368          * extended bit set even when they shouldn't,
369          * should check for them */
370         DOSVM_Int09SendScan(0xE0,0);
371       }
372       DOSVM_Int09SendScan(scan,0);
373       break;
374     }
375   }
376 }
377
378
379 /***********************************************************************
380  *              DOSVM_Wait
381  *
382  * Wait for asynchronous events. This routine temporarily enables
383  * interrupts and waits until some asynchronous event has been 
384  * processed.
385  */
386 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx )
387 {
388     if (DOSVM_HasPendingEvents())
389     {
390         CONTEXT86 context = *waitctx;
391         
392         /*
393          * If DOSVM_Wait is called from protected mode we emulate
394          * interrupt reflection and convert context into real mode context.
395          * This is actually the correct thing to do as long as DOSVM_Wait
396          * is only called from those interrupt functions that DPMI reflects
397          * to real mode.
398          *
399          * FIXME: Need to think about where to place real mode stack.
400          * FIXME: If DOSVM_Wait calls are nested stack gets corrupted.
401          *        Can this really happen?
402          */
403         if (!ISV86(&context))
404         {
405             context.EFlags |= V86_FLAG;
406             context.SegSs = 0xffff;
407             context.Esp = 0;
408         }
409
410         context.EFlags |= VIF_MASK;
411         context.SegCs = 0;
412         context.Eip = 0;
413
414         DOSVM_SendQueuedEvents(&context);
415
416         if(context.SegCs || context.Eip)
417             DPMI_CallRMProc( &context, NULL, 0, TRUE );
418     }
419     else
420     {
421         HANDLE objs[2];
422         int    objc = DOSVM_IsWin16() ? 2 : 1;
423         DWORD  waitret;
424
425         objs[0] = event_notifier;
426         objs[1] = GetStdHandle(STD_INPUT_HANDLE);
427
428         waitret = MsgWaitForMultipleObjects( objc, objs, FALSE, 
429                                              INFINITE, QS_ALLINPUT );
430         
431         if (waitret == WAIT_OBJECT_0)
432         {
433             /*
434              * New pending event has been queued, we ignore it
435              * here because it will be processed on next call to
436              * DOSVM_Wait.
437              */
438         }
439         else if (objc == 2 && waitret == WAIT_OBJECT_0 + 1)
440         {
441             DOSVM_ProcessConsole();
442         }
443         else if (waitret == WAIT_OBJECT_0 + objc)
444         {
445             MSG msg;
446             while (PeekMessageA(&msg,0,0,0,PM_REMOVE|PM_NOYIELD)) 
447             {
448                 /* got a message */
449                 DOSVM_ProcessMessage(&msg);
450                 /* we don't need a TranslateMessage here */
451                 DispatchMessageA(&msg);
452             }
453         }
454         else
455         {
456             ERR_(module)( "dosvm wait error=%ld\n", GetLastError() );
457         }
458     }
459 }
460
461
462 DWORD WINAPI DOSVM_Loop( HANDLE hThread )
463 {
464   HANDLE objs[2];
465   MSG msg;
466   DWORD waitret;
467
468   objs[0] = GetStdHandle(STD_INPUT_HANDLE);
469   objs[1] = hThread;
470
471   for(;;) {
472       TRACE_(int)("waiting for action\n");
473       waitret = MsgWaitForMultipleObjects(2, objs, FALSE, INFINITE, QS_ALLINPUT);
474       if (waitret == WAIT_OBJECT_0) {
475           DOSVM_ProcessConsole();
476       }
477       else if (waitret == WAIT_OBJECT_0 + 1) {
478          DWORD rv;
479          if(!GetExitCodeThread(hThread, &rv)) {
480              ERR("Failed to get thread exit code!\n");
481              rv = 0;
482          }
483          return rv;
484       }
485       else if (waitret == WAIT_OBJECT_0 + 2) {
486           while (PeekMessageA(&msg,0,0,0,PM_REMOVE)) {
487               if (msg.hwnd) {
488                   /* it's a window message */
489                   DOSVM_ProcessMessage(&msg);
490                   DispatchMessageA(&msg);
491               } else {
492                   /* it's a thread message */
493                   switch (msg.message) {
494                   case WM_QUIT:
495                       /* stop this madness!! */
496                       return 0;
497                   case WM_USER:
498                       /* run passed procedure in this thread */
499                       /* (sort of like APC, but we signal the completion) */
500                       {
501                           DOS_SPC *spc = (DOS_SPC *)msg.lParam;
502                           TRACE_(int)("calling %p with arg %08lx\n", spc->proc, spc->arg);
503                           (spc->proc)(spc->arg);
504                           TRACE_(int)("done, signalling event %x\n", msg.wParam);
505                           SetEvent( (HANDLE)msg.wParam );
506                       }
507                       break;
508                   default:
509                       DispatchMessageA(&msg);
510                   }
511               }
512           }
513       }
514       else
515       {
516           ERR_(int)("MsgWaitForMultipleObjects returned unexpected value.\n");
517           return 0;
518       }
519   }
520 }
521
522 static WINE_EXCEPTION_FILTER(exception_handler)
523 {
524   EXCEPTION_RECORD *rec = GetExceptionInformation()->ExceptionRecord;
525   CONTEXT *context = GetExceptionInformation()->ContextRecord;
526   int arg = rec->ExceptionInformation[0];
527   BOOL ret;
528
529   switch(rec->ExceptionCode) {
530   case EXCEPTION_VM86_INTx:
531     TRACE_(relay)("Call DOS int 0x%02x ret=%04lx:%04lx\n"
532                   " eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n"
533                   " ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
534                   arg, context->SegCs, context->Eip,
535                   context->Eax, context->Ebx, context->Ecx, context->Edx, context->Esi, context->Edi,
536                   context->Ebp, context->Esp, context->SegDs, context->SegEs, context->SegFs, context->SegGs,
537                   context->EFlags );
538     ret = DOSVM_EmulateInterruptRM( context, arg );
539     TRACE_(relay)("Ret  DOS int 0x%02x ret=%04lx:%04lx\n"
540                   " eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n"
541                   " ebp=%08lx esp=%08lx ds=%04lx es=%04lx fs=%04lx gs=%04lx flags=%08lx\n",
542                   arg, context->SegCs, context->Eip,
543                   context->Eax, context->Ebx, context->Ecx, context->Edx, context->Esi, context->Edi,
544                   context->Ebp, context->Esp, context->SegDs, context->SegEs,
545                   context->SegFs, context->SegGs, context->EFlags );
546     return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
547
548   case EXCEPTION_VM86_STI:
549   /* case EXCEPTION_VM86_PICRETURN: */
550     if (!ISV86(context))
551       ERR( "Protected mode STI caught by real mode handler!\n" );
552     DOSVM_SendQueuedEvents(context);
553     return EXCEPTION_CONTINUE_EXECUTION;
554   
555   case EXCEPTION_SINGLE_STEP:
556     ret = DOSVM_EmulateInterruptRM( context, 1 );
557     return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
558   
559   case EXCEPTION_BREAKPOINT:
560     ret = DOSVM_EmulateInterruptRM( context, 3 );
561     return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
562   
563   }
564   return EXCEPTION_CONTINUE_SEARCH;
565 }
566
567 int WINAPI DOSVM_Enter( CONTEXT86 *context )
568 {
569   if (!ISV86(context))
570       ERR( "Called with protected mode context!\n" );
571
572   __TRY
573   {
574       WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)context );
575       TRACE_(module)( "vm86 returned: %s\n", strerror(errno) );
576   }
577   __EXCEPT(exception_handler)
578   {
579     TRACE_(module)( "leaving vm86 mode\n" );
580   }
581   __ENDTRY
582
583   return 0;
584 }
585
586 /***********************************************************************
587  *              OutPIC (WINEDOS.@)
588  */
589 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val)
590 {
591     if (port != 0x20)
592     {
593         FIXME( "Unsupported PIC port %04x\n", port );
594     }
595     else if (val == 0x20 || (val >= 0x60 && val <= 0x67)) 
596     {
597         EnterCriticalSection(&qcrit);
598
599         if (!current_event)
600         {
601             WARN( "%s without active IRQ\n",
602                   val == 0x20 ? "EOI" : "Specific EOI" );
603         }
604         else if (val != 0x20 && val - 0x60 != current_event->irq)
605         {
606             WARN( "Specific EOI but current IRQ %d is not %d\n", 
607                   current_event->irq, val - 0x60 );
608         }
609         else
610         {
611             LPDOSEVENT event = current_event;
612
613             TRACE( "Received %s for current IRQ %d, clearing event\n",
614                    val == 0x20 ? "EOI" : "Specific EOI", event->irq );
615
616             current_event = event->next;
617             if (event->relay)
618                 (*event->relay)(NULL,event->data);
619             free(event);
620
621             if (DOSVM_HasPendingEvents()) 
622             {
623                 TRACE( "Another event pending, setting pending flag\n" );
624                 NtCurrentTeb()->vm86_pending |= VIP_MASK;
625             }
626         }
627
628         LeaveCriticalSection(&qcrit);
629     } 
630     else 
631     {
632         FIXME( "Unrecognized PIC command %02x\n", val );
633     }
634 }
635
636 #else /* !MZ_SUPPORTED */
637
638 /***********************************************************************
639  *              Enter (WINEDOS.@)
640  */
641 INT WINAPI DOSVM_Enter( CONTEXT86 *context )
642 {
643  ERR_(module)("DOS realmode not supported on this architecture!\n");
644  return -1;
645 }
646
647 /***********************************************************************
648  *              Wait (WINEDOS.@)
649  */
650 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx ) { }
651
652 /***********************************************************************
653  *              OutPIC (WINEDOS.@)
654  */
655 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val) {}
656
657 /***********************************************************************
658  *              QueueEvent (WINEDOS.@)
659  */
660 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
661 {
662   if (irq<0) {
663     /* callback event, perform it with dummy context */
664     CONTEXT86 context;
665     memset(&context,0,sizeof(context));
666     (*relay)(&context,data);
667   } else {
668     ERR("IRQ without DOS task: should not happen\n");
669   }
670 }
671
672 #endif /* MZ_SUPPORTED */
673
674
675 /**********************************************************************
676  *         DOSVM_AcknowledgeIRQ
677  *
678  * This routine should be called by all internal IRQ handlers.
679  */
680 void WINAPI DOSVM_AcknowledgeIRQ( CONTEXT86 *context )
681 {
682     /*
683      * Send EOI to PIC.
684      */
685     DOSVM_PIC_ioport_out( 0x20, 0x20 );
686
687     /*
688      * Protected mode IRQ handlers are supposed
689      * to turn VIF flag on before they return.
690      */
691     if (!ISV86(context))
692         NtCurrentTeb()->dpmi_vif = 1;
693 }
694
695
696 /**********************************************************************
697  *          DllMain  (DOSVM.0)
698  */
699 BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
700 {
701     TRACE_(module)("(%p,%ld,%p)\n", hinstDLL, fdwReason, lpvReserved);
702
703     if (fdwReason == DLL_PROCESS_ATTACH)
704     {
705         DisableThreadLibraryCalls(hinstDLL);
706         if (!DOSMEM_InitDosMemory()) return FALSE;
707         DOSVM_InitSegments();
708
709         event_notifier = CreateEventW(NULL, FALSE, FALSE, NULL);
710         if(!event_notifier)
711           ERR("Failed to create event object!\n");
712     }
713     return TRUE;
714 }