gdiplus: Added Gdip[Get/Set]TextureWrapMode.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 "winternl.h"
46 #include "wingdi.h"
47 #include "winuser.h"
48 #include "wownt32.h"
49 #include "winnt.h"
50 #include "wincon.h"
51
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 #ifdef MZ_SUPPORTED
60 WINE_DECLARE_DEBUG_CHANNEL(relay);
61 #endif
62
63 WORD DOSVM_psp = 0;
64 WORD DOSVM_retval = 0;
65
66 #ifdef HAVE_SYS_MMAN_H
67 # include <sys/mman.h>
68 #endif
69
70
71 typedef struct _DOSEVENT {
72   int irq,priority;
73   DOSRELAY relay;
74   void *data;
75   struct _DOSEVENT *next;
76 } DOSEVENT, *LPDOSEVENT;
77
78 static struct _DOSEVENT *pending_event, *current_event;
79 static HANDLE event_notifier;
80
81 static CRITICAL_SECTION qcrit;
82 static CRITICAL_SECTION_DEBUG critsect_debug =
83 {
84     0, 0, &qcrit,
85     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
86       0, 0, { (DWORD_PTR)(__FILE__ ": qcrit") }
87 };
88 static CRITICAL_SECTION qcrit = { &critsect_debug, -1, 0, 0, 0, 0 };
89
90
91 /***********************************************************************
92  *              DOSVM_HasPendingEvents
93  *
94  * Return true if there are pending events that are not
95  * blocked by currently active event.
96  */
97 static BOOL DOSVM_HasPendingEvents( void )
98 {   
99     if (!pending_event)
100         return FALSE;
101
102     if (!current_event)
103         return TRUE;
104
105     if (pending_event->priority < current_event->priority)
106         return TRUE;
107
108     return FALSE;
109 }
110
111
112 /***********************************************************************
113  *              DOSVM_SendOneEvent
114  *
115  * Process single pending event.
116  *
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.
122  */
123 static void DOSVM_SendOneEvent( CONTEXT86 *context )
124 {
125     LPDOSEVENT event = pending_event;
126
127     /* Remove from pending events list. */
128     pending_event = event->next;
129
130     /* Process active event. */
131     if (event->irq >= 0) 
132     {
133         BYTE intnum = (event->irq < 8) ?
134             (event->irq + 8) : (event->irq - 8 + 0x70);
135             
136         /* Event is an IRQ, move it to current events list. */
137         event->next = current_event;
138         current_event = event;
139
140         TRACE( "Dispatching IRQ %d.\n", event->irq );
141
142         if (ISV86(context))
143         {
144             /* 
145              * Note that if DOSVM_HardwareInterruptRM calls an internal 
146              * interrupt directly, current_event might be cleared 
147              * (and event freed) in this call.
148              */
149             LeaveCriticalSection(&qcrit);
150             DOSVM_HardwareInterruptRM( context, intnum );
151             EnterCriticalSection(&qcrit);
152         }
153         else
154         {
155             /*
156              * This routine only modifies current context so it is
157              * not necessary to release critical section.
158              */
159             DOSVM_HardwareInterruptPM( context, intnum );
160         }
161     } 
162     else 
163     {
164         /* Callback event. */
165         TRACE( "Dispatching callback event.\n" );
166
167         if (ISV86(context))
168         {
169             /*
170              * Call relay immediately in real mode.
171              */
172             LeaveCriticalSection(&qcrit);
173             (*event->relay)( context, event->data );
174             EnterCriticalSection(&qcrit);
175         }
176         else
177         {
178             /*
179              * Force return to relay code. We do not want to
180              * call relay directly because we may be inside a signal handler.
181              */
182             DOSVM_BuildCallFrame( context, event->relay, event->data );
183         }
184
185         free(event);
186     }
187 }
188
189
190 /***********************************************************************
191  *              DOSVM_SendQueuedEvents
192  *
193  * As long as context instruction pointer stays unmodified,
194  * process all pending events that are not blocked by currently
195  * active event.
196  *
197  * This routine assumes that caller has already cleared TEB.vm86_pending 
198  * and checked that interrupts are enabled.
199  */
200 void DOSVM_SendQueuedEvents( CONTEXT86 *context )
201 {   
202     DWORD old_cs = context->SegCs;
203     DWORD old_ip = context->Eip;
204
205     EnterCriticalSection(&qcrit);
206
207     TRACE( "Called in %s mode %s events pending (time=%d)\n",
208            ISV86(context) ? "real" : "protected",
209            DOSVM_HasPendingEvents() ? "with" : "without",
210            GetTickCount() );
211     TRACE( "cs:ip=%04x:%08x, ss:sp=%04x:%08x\n",
212            context->SegCs, context->Eip, context->SegSs, context->Esp);
213
214     while (context->SegCs == old_cs &&
215            context->Eip == old_ip &&
216            DOSVM_HasPendingEvents())
217     {
218         DOSVM_SendOneEvent(context);
219
220         /*
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.
224          */
225         get_vm86_teb_info()->vm86_pending = 0;
226     }
227
228 #ifdef MZ_SUPPORTED
229
230     if (DOSVM_HasPendingEvents())
231     {
232         /*
233          * Interrupts disabled, but there are still
234          * pending events, make sure that pending flag is turned on.
235          */
236         TRACE( "Another event is pending, setting VIP flag.\n" );
237         get_vm86_teb_info()->vm86_pending |= VIP_MASK;
238     }
239
240 #else
241
242     FIXME("No DOS .exe file support on this platform (yet)\n");
243
244 #endif /* MZ_SUPPORTED */
245
246     LeaveCriticalSection(&qcrit);
247 }
248
249
250 #ifdef MZ_SUPPORTED
251 /***********************************************************************
252  *              QueueEvent (WINEDOS.@)
253  */
254 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
255 {
256   LPDOSEVENT event, cur, prev;
257   BOOL       old_pending;
258
259   if (MZ_Current()) {
260     event = malloc(sizeof(DOSEVENT));
261     if (!event) {
262       ERR("out of memory allocating event entry\n");
263       return;
264     }
265     event->irq = irq; event->priority = priority;
266     event->relay = relay; event->data = data;
267
268     EnterCriticalSection(&qcrit);
269     old_pending = DOSVM_HasPendingEvents();
270
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) {
275       prev = cur;
276       cur = cur->next;
277     }
278     event->next = cur;
279     if (prev) prev->next = event;
280     else pending_event = event;
281
282     if (!old_pending && DOSVM_HasPendingEvents()) {
283       TRACE("new event queued, signalling (time=%d)\n", GetTickCount());
284       
285       /* Alert VM86 thread about the new event. */
286       kill(dosvm_pid,SIGUSR2);
287
288       /* Wake up DOSVM_Wait so that it can serve pending events. */
289       SetEvent(event_notifier);
290     } else {
291       TRACE("new event queued (time=%d)\n", GetTickCount());
292     }
293
294     LeaveCriticalSection(&qcrit);
295   } else {
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) */
299     if (irq<0) {
300       /* callback event, perform it with dummy context */
301       CONTEXT86 context;
302       memset(&context,0,sizeof(context));
303       (*relay)(&context,data);
304     } else {
305       ERR("IRQ without DOS task: should not happen\n");
306     }
307   }
308 }
309
310 static void DOSVM_ProcessConsole(void)
311 {
312   INPUT_RECORD msg;
313   DWORD res;
314   BYTE scan, ascii;
315
316   if (ReadConsoleInputA(GetStdHandle(STD_INPUT_HANDLE),&msg,1,&res)) {
317     switch (msg.EventType) {
318     case KEY_EVENT:
319       scan = msg.Event.KeyEvent.wVirtualScanCode;
320       ascii = msg.Event.KeyEvent.uChar.AsciiChar;
321       TRACE("scan %02x, ascii %02x\n", scan, ascii);
322
323       /* set the "break" (release) flag if key released */
324       if (!msg.Event.KeyEvent.bKeyDown) scan |= 0x80;
325
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);
330       }
331       DOSVM_Int09SendScan(scan, ascii);
332       break;
333     case MOUSE_EVENT:
334       DOSVM_Int33Console(&msg.Event.MouseEvent);
335       break;
336     case WINDOW_BUFFER_SIZE_EVENT:
337       FIXME("unhandled WINDOW_BUFFER_SIZE_EVENT.\n");
338       break;
339     case MENU_EVENT:
340       FIXME("unhandled MENU_EVENT.\n");
341       break;
342     case FOCUS_EVENT:
343       FIXME("unhandled FOCUS_EVENT.\n");
344       break;
345     default:
346       FIXME("unknown console event: %d\n", msg.EventType);
347     }
348   }
349 }
350
351 static void DOSVM_ProcessMessage(MSG *msg)
352 {
353   BYTE scan = 0;
354
355   TRACE("got message %04x, wparam=%08lx, 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);
359   } else {
360     switch (msg->message) {
361     case WM_KEYUP:
362       scan = 0x80;
363     case WM_KEYDOWN:
364       scan |= (msg->lParam >> 16) & 0x7f;
365
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);
373       }
374       DOSVM_Int09SendScan(scan,0);
375       break;
376     }
377   }
378 }
379
380
381 /***********************************************************************
382  *              DOSVM_Wait
383  *
384  * Wait for asynchronous events. This routine temporarily enables
385  * interrupts and waits until some asynchronous event has been 
386  * processed.
387  */
388 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx )
389 {
390     if (DOSVM_HasPendingEvents())
391     {
392         CONTEXT86 context = *waitctx;
393         
394         /*
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
399          * to real mode.
400          *
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?
404          */
405         if (!ISV86(&context))
406         {
407             context.EFlags |= V86_FLAG;
408             context.SegSs = 0xffff;
409             context.Esp = 0;
410         }
411
412         context.EFlags |= VIF_MASK;
413         context.SegCs = 0;
414         context.Eip = 0;
415
416         DOSVM_SendQueuedEvents(&context);
417
418         if(context.SegCs || context.Eip)
419             DPMI_CallRMProc( &context, NULL, 0, TRUE );
420     }
421     else
422     {
423         HANDLE objs[2];
424         int    objc = DOSVM_IsWin16() ? 2 : 1;
425         DWORD  waitret;
426
427         objs[0] = event_notifier;
428         objs[1] = GetStdHandle(STD_INPUT_HANDLE);
429
430         waitret = MsgWaitForMultipleObjects( objc, objs, FALSE, 
431                                              INFINITE, QS_ALLINPUT );
432         
433         if (waitret == WAIT_OBJECT_0)
434         {
435             /*
436              * New pending event has been queued, we ignore it
437              * here because it will be processed on next call to
438              * DOSVM_Wait.
439              */
440         }
441         else if (objc == 2 && waitret == WAIT_OBJECT_0 + 1)
442         {
443             DOSVM_ProcessConsole();
444         }
445         else if (waitret == WAIT_OBJECT_0 + objc)
446         {
447             MSG msg;
448             while (PeekMessageA(&msg,0,0,0,PM_REMOVE|PM_NOYIELD)) 
449             {
450                 /* got a message */
451                 DOSVM_ProcessMessage(&msg);
452                 /* we don't need a TranslateMessage here */
453                 DispatchMessageA(&msg);
454             }
455         }
456         else
457         {
458             ERR_(module)( "dosvm wait error=%d\n", GetLastError() );
459         }
460     }
461 }
462
463
464 DWORD WINAPI DOSVM_Loop( HANDLE hThread )
465 {
466   HANDLE objs[2];
467   int count = 0;
468   MSG msg;
469   DWORD waitret;
470
471   objs[count++] = hThread;
472   if (GetConsoleMode( GetStdHandle(STD_INPUT_HANDLE), NULL ))
473       objs[count++] = GetStdHandle(STD_INPUT_HANDLE);
474
475   for(;;) {
476       TRACE_(int)("waiting for action\n");
477       waitret = MsgWaitForMultipleObjects(count, objs, FALSE, INFINITE, QS_ALLINPUT);
478       if (waitret == WAIT_OBJECT_0) {
479          DWORD rv;
480          if(!GetExitCodeThread(hThread, &rv)) {
481              ERR("Failed to get thread exit code!\n");
482              rv = 0;
483          }
484          return rv;
485       }
486       else if (waitret == WAIT_OBJECT_0 + count) {
487           while (PeekMessageA(&msg,0,0,0,PM_REMOVE)) {
488               if (msg.hwnd) {
489                   /* it's a window message */
490                   DOSVM_ProcessMessage(&msg);
491                   DispatchMessageA(&msg);
492               } else {
493                   /* it's a thread message */
494                   switch (msg.message) {
495                   case WM_QUIT:
496                       /* stop this madness!! */
497                       return 0;
498                   case WM_USER:
499                       /* run passed procedure in this thread */
500                       /* (sort of like APC, but we signal the completion) */
501                       {
502                           DOS_SPC *spc = (DOS_SPC *)msg.lParam;
503                           TRACE_(int)("calling %p with arg %08lx\n", spc->proc, spc->arg);
504                           (spc->proc)(spc->arg);
505                           TRACE_(int)("done, signalling event %lx\n", msg.wParam);
506                           SetEvent( (HANDLE)msg.wParam );
507                       }
508                       break;
509                   default:
510                       DispatchMessageA(&msg);
511                   }
512               }
513           }
514       }
515       else if (waitret == WAIT_OBJECT_0 + 1)
516       {
517           DOSVM_ProcessConsole();
518       }
519       else
520       {
521           ERR_(int)("MsgWaitForMultipleObjects returned unexpected value.\n");
522           return 0;
523       }
524   }
525 }
526
527 static LONG WINAPI exception_handler(EXCEPTION_POINTERS *eptr)
528 {
529   EXCEPTION_RECORD *rec = eptr->ExceptionRecord;
530   CONTEXT *context = eptr->ContextRecord;
531   int arg = rec->ExceptionInformation[0];
532   BOOL ret;
533
534   switch(rec->ExceptionCode) {
535   case EXCEPTION_VM86_INTx:
536     TRACE_(relay)("Call DOS int 0x%02x ret=%04x:%04x\n"
537                   " eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n"
538                   " ebp=%08x esp=%08x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
539                   arg, context->SegCs, context->Eip,
540                   context->Eax, context->Ebx, context->Ecx, context->Edx, context->Esi, context->Edi,
541                   context->Ebp, context->Esp, context->SegDs, context->SegEs, context->SegFs, context->SegGs,
542                   context->EFlags );
543     ret = DOSVM_EmulateInterruptRM( context, arg );
544     TRACE_(relay)("Ret  DOS int 0x%02x ret=%04x:%04x\n"
545                   " eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n"
546                   " ebp=%08x esp=%08x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
547                   arg, context->SegCs, context->Eip,
548                   context->Eax, context->Ebx, context->Ecx, context->Edx, context->Esi, context->Edi,
549                   context->Ebp, context->Esp, context->SegDs, context->SegEs,
550                   context->SegFs, context->SegGs, context->EFlags );
551     return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
552
553   case EXCEPTION_VM86_STI:
554   /* case EXCEPTION_VM86_PICRETURN: */
555     if (!ISV86(context))
556       ERR( "Protected mode STI caught by real mode handler!\n" );
557     DOSVM_SendQueuedEvents(context);
558     return EXCEPTION_CONTINUE_EXECUTION;
559   
560   case EXCEPTION_SINGLE_STEP:
561     ret = DOSVM_EmulateInterruptRM( context, 1 );
562     return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
563   
564   case EXCEPTION_BREAKPOINT:
565     ret = DOSVM_EmulateInterruptRM( context, 3 );
566     return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
567   
568   }
569   return EXCEPTION_CONTINUE_SEARCH;
570 }
571
572 INT WINAPI DOSVM_Enter( CONTEXT86 *context )
573 {
574   INT ret = 0;
575   if (!ISV86(context))
576       ERR( "Called with protected mode context!\n" );
577
578   __TRY
579   {
580       if (!WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)context )) ret = -1;
581       TRACE_(module)( "ret %d err %u\n", ret, GetLastError() );
582   }
583   __EXCEPT(exception_handler)
584   {
585     TRACE_(module)( "leaving vm86 mode\n" );
586   }
587   __ENDTRY
588
589   return ret;
590 }
591
592 /***********************************************************************
593  *              OutPIC (WINEDOS.@)
594  */
595 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val)
596 {
597     if (port != 0x20)
598     {
599         FIXME( "Unsupported PIC port %04x\n", port );
600     }
601     else if (val == 0x20 || (val >= 0x60 && val <= 0x67)) 
602     {
603         EnterCriticalSection(&qcrit);
604
605         if (!current_event)
606         {
607             WARN( "%s without active IRQ\n",
608                   val == 0x20 ? "EOI" : "Specific EOI" );
609         }
610         else if (val != 0x20 && val - 0x60 != current_event->irq)
611         {
612             WARN( "Specific EOI but current IRQ %d is not %d\n", 
613                   current_event->irq, val - 0x60 );
614         }
615         else
616         {
617             LPDOSEVENT event = current_event;
618
619             TRACE( "Received %s for current IRQ %d, clearing event\n",
620                    val == 0x20 ? "EOI" : "Specific EOI", event->irq );
621
622             current_event = event->next;
623             if (event->relay)
624                 (*event->relay)(NULL,event->data);
625             free(event);
626
627             if (DOSVM_HasPendingEvents()) 
628             {
629                 TRACE( "Another event pending, setting pending flag\n" );
630                 get_vm86_teb_info()->vm86_pending |= VIP_MASK;
631             }
632         }
633
634         LeaveCriticalSection(&qcrit);
635     } 
636     else 
637     {
638         FIXME( "Unrecognized PIC command %02x\n", val );
639     }
640 }
641
642 #else /* !MZ_SUPPORTED */
643
644 /***********************************************************************
645  *              Enter (WINEDOS.@)
646  */
647 INT WINAPI DOSVM_Enter( CONTEXT86 *context )
648 {
649     SetLastError( ERROR_NOT_SUPPORTED );
650     return -1;
651 }
652
653 /***********************************************************************
654  *              Wait (WINEDOS.@)
655  */
656 void WINAPI DOSVM_Wait( CONTEXT86 *waitctx ) { }
657
658 /***********************************************************************
659  *              OutPIC (WINEDOS.@)
660  */
661 void WINAPI DOSVM_PIC_ioport_out( WORD port, BYTE val) {}
662
663 /***********************************************************************
664  *              QueueEvent (WINEDOS.@)
665  */
666 void WINAPI DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
667 {
668   if (irq<0) {
669     /* callback event, perform it with dummy context */
670     CONTEXT86 context;
671     memset(&context,0,sizeof(context));
672     (*relay)(&context,data);
673   } else {
674     ERR("IRQ without DOS task: should not happen\n");
675   }
676 }
677
678 #endif /* MZ_SUPPORTED */
679
680
681 /**********************************************************************
682  *         DOSVM_AcknowledgeIRQ
683  *
684  * This routine should be called by all internal IRQ handlers.
685  */
686 void WINAPI DOSVM_AcknowledgeIRQ( CONTEXT86 *context )
687 {
688     /*
689      * Send EOI to PIC.
690      */
691     DOSVM_PIC_ioport_out( 0x20, 0x20 );
692
693     /*
694      * Protected mode IRQ handlers are supposed
695      * to turn VIF flag on before they return.
696      */
697     if (!ISV86(context))
698         get_vm86_teb_info()->dpmi_vif = 1;
699 }
700
701
702 /**********************************************************************
703  *          DllMain  (DOSVM.0)
704  */
705 BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved )
706 {
707     TRACE_(module)("(%p,%d,%p)\n", hinstDLL, fdwReason, lpvReserved);
708
709     if (fdwReason == DLL_PROCESS_ATTACH)
710     {
711         DisableThreadLibraryCalls(hinstDLL);
712         if (!DOSMEM_InitDosMemory()) return FALSE;
713         DOSVM_InitSegments();
714
715         event_notifier = CreateEventW(NULL, FALSE, FALSE, NULL);
716         if(!event_notifier)
717           ERR("Failed to create event object!\n");
718     }
719     return TRUE;
720 }