oleaut32: Add a test for loading/saving an empty picture.
[wine] / dlls / krnl386.exe16 / dosvm.c
1 /*
2  * DOS Virtual Machine
3  *
4  * Copyright 1998 Ove Kåven
5  * Copyright 2002 Jukka Heinonen
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  *
21  * Note: This code hasn't been completely cleaned up yet.
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <signal.h>
34 #ifdef HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
37 #ifdef HAVE_SYS_TIME_H
38 # include <sys/time.h>
39 #endif
40 #include <sys/types.h>
41
42 #include "wine/winbase16.h"
43 #include "wine/exception.h"
44 #include "windef.h"
45 #include "winbase.h"
46 #include "winternl.h"
47 #include "wingdi.h"
48 #include "winuser.h"
49 #include "wownt32.h"
50 #include "winnt.h"
51 #include "wincon.h"
52
53 #include "dosexe.h"
54 #include "wine/debug.h"
55 #include "excpt.h"
56
57 WINE_DEFAULT_DEBUG_CHANNEL(int);
58 #ifdef MZ_SUPPORTED
59 WINE_DECLARE_DEBUG_CHANNEL(module);
60 WINE_DECLARE_DEBUG_CHANNEL(relay);
61 #endif
62
63 WORD DOSVM_psp = 0;
64 WORD DOSVM_retval = 0;
65
66 /*
67  * Wine DOS memory layout above 640k:
68  *
69  *   a0000 - affff : VGA graphics         (vga.c)
70  *   b0000 - bffff : Monochrome text      (unused)
71  *   b8000 - bffff : VGA text             (vga.c)
72  *   c0000 - cffff : EMS frame            (int67.c)
73  *   d0000 - effff : Free memory for UMBs (himem.c)
74  *   f0000 - fffff : BIOS stuff           (msdos/dosmem.c)
75  *  100000 -10ffff : High memory area     (unused)
76  */
77
78 /*
79  * Table of real mode segments and protected mode selectors
80  * for code stubs and other miscellaneous storage.
81  */
82 struct DPMI_segments *DOSVM_dpmi_segments = NULL;
83
84 /*
85  * First and last address available for upper memory blocks.
86  */
87 #define DOSVM_UMB_BOTTOM 0xd0000
88 #define DOSVM_UMB_TOP    0xeffff
89
90 /*
91  * First free address for upper memory blocks.
92  */
93 static DWORD DOSVM_umb_free = DOSVM_UMB_BOTTOM;
94
95
96 typedef struct _DOSEVENT {
97   int irq,priority;
98   DOSRELAY relay;
99   void *data;
100   struct _DOSEVENT *next;
101 } DOSEVENT, *LPDOSEVENT;
102
103 static struct _DOSEVENT *pending_event, *current_event;
104 static HANDLE event_notifier;
105
106 static CRITICAL_SECTION qcrit;
107 static CRITICAL_SECTION_DEBUG critsect_debug =
108 {
109     0, 0, &qcrit,
110     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
111       0, 0, { (DWORD_PTR)(__FILE__ ": qcrit") }
112 };
113 static CRITICAL_SECTION qcrit = { &critsect_debug, -1, 0, 0, 0, 0 };
114
115
116 /***********************************************************************
117  *              DOSVM_HasPendingEvents
118  *
119  * Return true if there are pending events that are not
120  * blocked by currently active event.
121  */
122 static BOOL DOSVM_HasPendingEvents( void )
123 {   
124     if (!pending_event)
125         return FALSE;
126
127     if (!current_event)
128         return TRUE;
129
130     if (pending_event->priority < current_event->priority)
131         return TRUE;
132
133     return FALSE;
134 }
135
136
137 /***********************************************************************
138  *              DOSVM_SendOneEvent
139  *
140  * Process single pending event.
141  *
142  * This function should be called with queue critical section locked. 
143  * The function temporarily releases the critical section if it is 
144  * possible that internal interrupt handler or user procedure will 
145  * be called. This is because we may otherwise get a deadlock if
146  * another thread is waiting for the same critical section.
147  */
148 static void DOSVM_SendOneEvent( CONTEXT *context )
149 {
150     LPDOSEVENT event = pending_event;
151
152     /* Remove from pending events list. */
153     pending_event = event->next;
154
155     /* Process active event. */
156     if (event->irq >= 0) 
157     {
158         BYTE intnum = (event->irq < 8) ?
159             (event->irq + 8) : (event->irq - 8 + 0x70);
160             
161         /* Event is an IRQ, move it to current events list. */
162         event->next = current_event;
163         current_event = event;
164
165         TRACE( "Dispatching IRQ %d.\n", event->irq );
166
167         if (ISV86(context))
168         {
169             /* 
170              * Note that if DOSVM_HardwareInterruptRM calls an internal 
171              * interrupt directly, current_event might be cleared 
172              * (and event freed) in this call.
173              */
174             LeaveCriticalSection(&qcrit);
175             DOSVM_HardwareInterruptRM( context, intnum );
176             EnterCriticalSection(&qcrit);
177         }
178         else
179         {
180             /*
181              * This routine only modifies current context so it is
182              * not necessary to release critical section.
183              */
184             DOSVM_HardwareInterruptPM( context, intnum );
185         }
186     } 
187     else 
188     {
189         /* Callback event. */
190         TRACE( "Dispatching callback event.\n" );
191
192         if (ISV86(context))
193         {
194             /*
195              * Call relay immediately in real mode.
196              */
197             LeaveCriticalSection(&qcrit);
198             (*event->relay)( context, event->data );
199             EnterCriticalSection(&qcrit);
200         }
201         else
202         {
203             /*
204              * Force return to relay code. We do not want to
205              * call relay directly because we may be inside a signal handler.
206              */
207             DOSVM_BuildCallFrame( context, event->relay, event->data );
208         }
209
210         HeapFree(GetProcessHeap(), 0, event);
211     }
212 }
213
214
215 /***********************************************************************
216  *              DOSVM_SendQueuedEvents
217  *
218  * As long as context instruction pointer stays unmodified,
219  * process all pending events that are not blocked by currently
220  * active event.
221  *
222  * This routine assumes that caller has already cleared TEB.vm86_pending 
223  * and checked that interrupts are enabled.
224  */
225 void DOSVM_SendQueuedEvents( CONTEXT *context )
226 {   
227     DWORD old_cs = context->SegCs;
228     DWORD old_ip = context->Eip;
229
230     EnterCriticalSection(&qcrit);
231
232     TRACE( "Called in %s mode %s events pending (time=%d)\n",
233            ISV86(context) ? "real" : "protected",
234            DOSVM_HasPendingEvents() ? "with" : "without",
235            GetTickCount() );
236     TRACE( "cs:ip=%04x:%08x, ss:sp=%04x:%08x\n",
237            context->SegCs, context->Eip, context->SegSs, context->Esp);
238
239     while (context->SegCs == old_cs &&
240            context->Eip == old_ip &&
241            DOSVM_HasPendingEvents())
242     {
243         DOSVM_SendOneEvent(context);
244
245         /*
246          * Event handling may have turned pending events flag on.
247          * We disable it here because this prevents some
248          * unnecessary calls to this function.
249          */
250         get_vm86_teb_info()->vm86_pending = 0;
251     }
252
253 #ifdef MZ_SUPPORTED
254
255     if (DOSVM_HasPendingEvents())
256     {
257         /*
258          * Interrupts disabled, but there are still
259          * pending events, make sure that pending flag is turned on.
260          */
261         TRACE( "Another event is pending, setting VIP flag.\n" );
262         get_vm86_teb_info()->vm86_pending |= VIP_MASK;
263     }
264
265 #else
266
267     FIXME("No DOS .exe file support on this platform (yet)\n");
268
269 #endif /* MZ_SUPPORTED */
270
271     LeaveCriticalSection(&qcrit);
272 }
273
274
275 #ifdef MZ_SUPPORTED
276 /***********************************************************************
277  *              DOSVM_QueueEvent
278  */
279 void DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
280 {
281   LPDOSEVENT event, cur, prev;
282   BOOL       old_pending;
283
284   if (MZ_Current()) {
285     event = HeapAlloc(GetProcessHeap(), 0, sizeof(DOSEVENT));
286     if (!event) {
287       ERR("out of memory allocating event entry\n");
288       return;
289     }
290     event->irq = irq; event->priority = priority;
291     event->relay = relay; event->data = data;
292
293     EnterCriticalSection(&qcrit);
294     old_pending = DOSVM_HasPendingEvents();
295
296     /* insert event into linked list, in order *after*
297      * all earlier events of higher or equal priority */
298     cur = pending_event; prev = NULL;
299     while (cur && cur->priority<=priority) {
300       prev = cur;
301       cur = cur->next;
302     }
303     event->next = cur;
304     if (prev) prev->next = event;
305     else pending_event = event;
306
307     if (!old_pending && DOSVM_HasPendingEvents()) {
308       TRACE("new event queued, signalling (time=%d)\n", GetTickCount());
309       
310       /* Alert VM86 thread about the new event. */
311       kill(dosvm_pid,SIGUSR2);
312
313       /* Wake up DOSVM_Wait so that it can serve pending events. */
314       SetEvent(event_notifier);
315     } else {
316       TRACE("new event queued (time=%d)\n", GetTickCount());
317     }
318
319     LeaveCriticalSection(&qcrit);
320   } else {
321     /* DOS subsystem not running */
322     /* (this probably means that we're running a win16 app
323      *  which uses DPMI to thunk down to DOS services) */
324     if (irq<0) {
325       /* callback event, perform it with dummy context */
326       CONTEXT context;
327       memset(&context,0,sizeof(context));
328       (*relay)(&context,data);
329     } else {
330       ERR("IRQ without DOS task: should not happen\n");
331     }
332   }
333 }
334
335 static void DOSVM_ProcessConsole(void)
336 {
337   INPUT_RECORD msg;
338   DWORD res;
339   BYTE scan, ascii;
340
341   if (ReadConsoleInputA(GetStdHandle(STD_INPUT_HANDLE),&msg,1,&res)) {
342     switch (msg.EventType) {
343     case KEY_EVENT:
344       scan = msg.Event.KeyEvent.wVirtualScanCode;
345       ascii = msg.Event.KeyEvent.uChar.AsciiChar;
346       TRACE("scan %02x, ascii %02x\n", scan, ascii);
347
348       /* set the "break" (release) flag if key released */
349       if (!msg.Event.KeyEvent.bKeyDown) scan |= 0x80;
350
351       /* check whether extended bit is set,
352        * and if so, queue the extension prefix */
353       if (msg.Event.KeyEvent.dwControlKeyState & ENHANCED_KEY) {
354         DOSVM_Int09SendScan(0xE0,0);
355       }
356       DOSVM_Int09SendScan(scan, ascii);
357       break;
358     case MOUSE_EVENT:
359       DOSVM_Int33Console(&msg.Event.MouseEvent);
360       break;
361     case WINDOW_BUFFER_SIZE_EVENT:
362       FIXME("unhandled WINDOW_BUFFER_SIZE_EVENT.\n");
363       break;
364     case MENU_EVENT:
365       FIXME("unhandled MENU_EVENT.\n");
366       break;
367     case FOCUS_EVENT:
368       FIXME("unhandled FOCUS_EVENT.\n");
369       break;
370     default:
371       FIXME("unknown console event: %d\n", msg.EventType);
372     }
373   }
374 }
375
376 static void DOSVM_ProcessMessage(MSG *msg)
377 {
378   BYTE scan = 0;
379
380   TRACE("got message %04x, wparam=%08lx, lparam=%08lx\n",msg->message,msg->wParam,msg->lParam);
381   if ((msg->message>=WM_MOUSEFIRST)&&
382       (msg->message<=WM_MOUSELAST)) {
383     DOSVM_Int33Message(msg->message,msg->wParam,msg->lParam);
384   } else {
385     switch (msg->message) {
386     case WM_KEYUP:
387       scan = 0x80;
388     case WM_KEYDOWN:
389       scan |= (msg->lParam >> 16) & 0x7f;
390
391       /* check whether extended bit is set,
392        * and if so, queue the extension prefix */
393       if (msg->lParam & 0x1000000) {
394         /* FIXME: some keys (function keys) have
395          * extended bit set even when they shouldn't,
396          * should check for them */
397         DOSVM_Int09SendScan(0xE0,0);
398       }
399       DOSVM_Int09SendScan(scan,0);
400       break;
401     }
402   }
403 }
404
405
406 /***********************************************************************
407  *              DOSVM_Wait
408  *
409  * Wait for asynchronous events. This routine temporarily enables
410  * interrupts and waits until some asynchronous event has been 
411  * processed.
412  */
413 void DOSVM_Wait( CONTEXT *waitctx )
414 {
415     if (DOSVM_HasPendingEvents())
416     {
417         CONTEXT context = *waitctx;
418         
419         /*
420          * If DOSVM_Wait is called from protected mode we emulate
421          * interrupt reflection and convert context into real mode context.
422          * This is actually the correct thing to do as long as DOSVM_Wait
423          * is only called from those interrupt functions that DPMI reflects
424          * to real mode.
425          *
426          * FIXME: Need to think about where to place real mode stack.
427          * FIXME: If DOSVM_Wait calls are nested stack gets corrupted.
428          *        Can this really happen?
429          */
430         if (!ISV86(&context))
431         {
432             context.EFlags |= V86_FLAG;
433             context.SegSs = 0xffff;
434             context.Esp = 0;
435         }
436
437         context.EFlags |= VIF_MASK;
438         context.SegCs = 0;
439         context.Eip = 0;
440
441         DOSVM_SendQueuedEvents(&context);
442
443         if(context.SegCs || context.Eip)
444             DPMI_CallRMProc( &context, NULL, 0, TRUE );
445     }
446     else
447     {
448         HANDLE objs[2];
449         int    objc = DOSVM_IsWin16() ? 2 : 1;
450         DWORD  waitret;
451
452         objs[0] = event_notifier;
453         objs[1] = GetStdHandle(STD_INPUT_HANDLE);
454
455         waitret = MsgWaitForMultipleObjects( objc, objs, FALSE, 
456                                              INFINITE, QS_ALLINPUT );
457         
458         if (waitret == WAIT_OBJECT_0)
459         {
460             /*
461              * New pending event has been queued, we ignore it
462              * here because it will be processed on next call to
463              * DOSVM_Wait.
464              */
465         }
466         else if (objc == 2 && waitret == WAIT_OBJECT_0 + 1)
467         {
468             DOSVM_ProcessConsole();
469         }
470         else if (waitret == WAIT_OBJECT_0 + objc)
471         {
472             MSG msg;
473             while (PeekMessageA(&msg,0,0,0,PM_REMOVE|PM_NOYIELD)) 
474             {
475                 /* got a message */
476                 DOSVM_ProcessMessage(&msg);
477                 /* we don't need a TranslateMessage here */
478                 DispatchMessageA(&msg);
479             }
480         }
481         else
482         {
483             ERR_(module)( "dosvm wait error=%d\n", GetLastError() );
484         }
485     }
486 }
487
488
489 DWORD DOSVM_Loop( HANDLE hThread )
490 {
491   HANDLE objs[2];
492   int count = 0;
493   MSG msg;
494   DWORD waitret;
495
496   objs[count++] = hThread;
497   if (GetConsoleMode( GetStdHandle(STD_INPUT_HANDLE), NULL ))
498       objs[count++] = GetStdHandle(STD_INPUT_HANDLE);
499
500   for(;;) {
501       TRACE_(int)("waiting for action\n");
502       waitret = MsgWaitForMultipleObjects(count, objs, FALSE, INFINITE, QS_ALLINPUT);
503       if (waitret == WAIT_OBJECT_0) {
504          DWORD rv;
505          if(!GetExitCodeThread(hThread, &rv)) {
506              ERR("Failed to get thread exit code!\n");
507              rv = 0;
508          }
509          return rv;
510       }
511       else if (waitret == WAIT_OBJECT_0 + count) {
512           while (PeekMessageA(&msg,0,0,0,PM_REMOVE)) {
513               if (msg.hwnd) {
514                   /* it's a window message */
515                   DOSVM_ProcessMessage(&msg);
516                   DispatchMessageA(&msg);
517               } else {
518                   /* it's a thread message */
519                   switch (msg.message) {
520                   case WM_QUIT:
521                       /* stop this madness!! */
522                       return 0;
523                   case WM_USER:
524                       /* run passed procedure in this thread */
525                       /* (sort of like APC, but we signal the completion) */
526                       {
527                           DOS_SPC *spc = (DOS_SPC *)msg.lParam;
528                           TRACE_(int)("calling %p with arg %08lx\n", spc->proc, spc->arg);
529                           (spc->proc)(spc->arg);
530                           TRACE_(int)("done, signalling event %lx\n", msg.wParam);
531                           SetEvent( (HANDLE)msg.wParam );
532                       }
533                       break;
534                   default:
535                       DispatchMessageA(&msg);
536                   }
537               }
538           }
539       }
540       else if (waitret == WAIT_OBJECT_0 + 1)
541       {
542           DOSVM_ProcessConsole();
543       }
544       else
545       {
546           ERR_(int)("MsgWaitForMultipleObjects returned unexpected value.\n");
547           return 0;
548       }
549   }
550 }
551
552 static LONG WINAPI exception_handler(EXCEPTION_POINTERS *eptr)
553 {
554   EXCEPTION_RECORD *rec = eptr->ExceptionRecord;
555   CONTEXT *context = eptr->ContextRecord;
556   int arg = rec->ExceptionInformation[0];
557   BOOL ret;
558
559   switch(rec->ExceptionCode) {
560   case EXCEPTION_VM86_INTx:
561     TRACE_(relay)("Call DOS int 0x%02x ret=%04x:%04x\n"
562                   " eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n"
563                   " ebp=%08x esp=%08x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
564                   arg, context->SegCs, context->Eip,
565                   context->Eax, context->Ebx, context->Ecx, context->Edx, context->Esi, context->Edi,
566                   context->Ebp, context->Esp, context->SegDs, context->SegEs, context->SegFs, context->SegGs,
567                   context->EFlags );
568     ret = DOSVM_EmulateInterruptRM( context, arg );
569     TRACE_(relay)("Ret  DOS int 0x%02x ret=%04x:%04x\n"
570                   " eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x\n"
571                   " ebp=%08x esp=%08x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
572                   arg, context->SegCs, context->Eip,
573                   context->Eax, context->Ebx, context->Ecx, context->Edx, context->Esi, context->Edi,
574                   context->Ebp, context->Esp, context->SegDs, context->SegEs,
575                   context->SegFs, context->SegGs, context->EFlags );
576     return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
577
578   case EXCEPTION_VM86_STI:
579   /* case EXCEPTION_VM86_PICRETURN: */
580     if (!ISV86(context))
581       ERR( "Protected mode STI caught by real mode handler!\n" );
582     DOSVM_SendQueuedEvents(context);
583     return EXCEPTION_CONTINUE_EXECUTION;
584   
585   case EXCEPTION_SINGLE_STEP:
586     ret = DOSVM_EmulateInterruptRM( context, 1 );
587     return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
588   
589   case EXCEPTION_BREAKPOINT:
590     ret = DOSVM_EmulateInterruptRM( context, 3 );
591     return ret ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER;
592   
593   }
594   return EXCEPTION_CONTINUE_SEARCH;
595 }
596
597 INT DOSVM_Enter( CONTEXT *context )
598 {
599   INT ret = 0;
600   if (!ISV86(context))
601       ERR( "Called with protected mode context!\n" );
602
603   __TRY
604   {
605       if (!WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)context )) ret = -1;
606       TRACE_(module)( "ret %d err %u\n", ret, GetLastError() );
607   }
608   __EXCEPT(exception_handler)
609   {
610     TRACE_(module)( "leaving vm86 mode\n" );
611   }
612   __ENDTRY
613
614   return ret;
615 }
616
617 /***********************************************************************
618  *              DOSVM_PIC_ioport_out
619  */
620 void DOSVM_PIC_ioport_out( WORD port, BYTE val)
621 {
622     if (port != 0x20)
623     {
624         FIXME( "Unsupported PIC port %04x\n", port );
625     }
626     else if (val == 0x20 || (val >= 0x60 && val <= 0x67)) 
627     {
628         EnterCriticalSection(&qcrit);
629
630         if (!current_event)
631         {
632             WARN( "%s without active IRQ\n",
633                   val == 0x20 ? "EOI" : "Specific EOI" );
634         }
635         else if (val != 0x20 && val - 0x60 != current_event->irq)
636         {
637             WARN( "Specific EOI but current IRQ %d is not %d\n", 
638                   current_event->irq, val - 0x60 );
639         }
640         else
641         {
642             LPDOSEVENT event = current_event;
643
644             TRACE( "Received %s for current IRQ %d, clearing event\n",
645                    val == 0x20 ? "EOI" : "Specific EOI", event->irq );
646
647             current_event = event->next;
648             if (event->relay)
649                 (*event->relay)(NULL,event->data);
650             HeapFree(GetProcessHeap(), 0, event);
651
652             if (DOSVM_HasPendingEvents()) 
653             {
654                 TRACE( "Another event pending, setting pending flag\n" );
655                 get_vm86_teb_info()->vm86_pending |= VIP_MASK;
656             }
657         }
658
659         LeaveCriticalSection(&qcrit);
660     } 
661     else 
662     {
663         FIXME( "Unrecognized PIC command %02x\n", val );
664     }
665 }
666
667 #else /* !MZ_SUPPORTED */
668
669 /***********************************************************************
670  *              DOSVM_Enter
671  */
672 INT DOSVM_Enter( CONTEXT *context )
673 {
674     SetLastError( ERROR_NOT_SUPPORTED );
675     return -1;
676 }
677
678 /***********************************************************************
679  *              DOSVM_Wait
680  */
681 void DOSVM_Wait( CONTEXT *waitctx ) { }
682
683 /***********************************************************************
684  *              DOSVM_PIC_ioport_out
685  */
686 void DOSVM_PIC_ioport_out( WORD port, BYTE val) {}
687
688 /***********************************************************************
689  *              DOSVM_QueueEvent
690  */
691 void DOSVM_QueueEvent( INT irq, INT priority, DOSRELAY relay, LPVOID data)
692 {
693   if (irq<0) {
694     /* callback event, perform it with dummy context */
695     CONTEXT context;
696     memset(&context,0,sizeof(context));
697     (*relay)(&context,data);
698   } else {
699     ERR("IRQ without DOS task: should not happen\n");
700   }
701 }
702
703 #endif /* MZ_SUPPORTED */
704
705
706 /**********************************************************************
707  *         DOSVM_AcknowledgeIRQ
708  *
709  * This routine should be called by all internal IRQ handlers.
710  */
711 void WINAPI DOSVM_AcknowledgeIRQ( CONTEXT *context )
712 {
713     /*
714      * Send EOI to PIC.
715      */
716     DOSVM_PIC_ioport_out( 0x20, 0x20 );
717
718     /*
719      * Protected mode IRQ handlers are supposed
720      * to turn VIF flag on before they return.
721      */
722     if (!ISV86(context))
723         get_vm86_teb_info()->dpmi_vif = 1;
724 }
725
726
727 /***********************************************************************
728  *           DOSVM_AllocUMB
729  *
730  * Allocate upper memory block (UMB) from upper memory.
731  * Returned pointer is aligned to 16-byte (paragraph) boundary.
732  *
733  * This routine is only for allocating static storage for
734  * Wine internal uses. Allocated memory can be accessed from
735  * real mode, memory is taken from area already mapped and reserved
736  * by Wine and the allocation has very little memory and speed
737  * overhead. Use of this routine also preserves precious DOS
738  * conventional memory.
739  */
740 static LPVOID DOSVM_AllocUMB( DWORD size )
741 {
742   LPVOID ptr = (LPVOID)DOSVM_umb_free;
743
744   size = ((size + 15) >> 4) << 4;
745
746   if(DOSVM_umb_free + size - 1 > DOSVM_UMB_TOP) {
747     ERR("Out of upper memory area.\n");
748     return 0;
749   }
750
751   DOSVM_umb_free += size;
752   return ptr;
753 }
754
755
756 /**********************************************************************
757  *          alloc_selector
758  *
759  * Allocate a selector corresponding to a real mode address.
760  * size must be < 64k.
761  */
762 static WORD alloc_selector( void *base, DWORD size, unsigned char flags )
763 {
764     WORD sel = wine_ldt_alloc_entries( 1 );
765
766     if (sel)
767     {
768         LDT_ENTRY entry;
769         wine_ldt_set_base( &entry, base );
770         wine_ldt_set_limit( &entry, size - 1 );
771         wine_ldt_set_flags( &entry, flags );
772         wine_ldt_set_entry( sel, &entry );
773     }
774     return sel;
775 }
776
777
778 /***********************************************************************
779  *           DOSVM_AllocCodeUMB
780  *
781  * Allocate upper memory block for storing code stubs.
782  * Initializes real mode segment and 16-bit protected mode selector
783  * for the allocated code block.
784  *
785  * FIXME: should allocate a single PM selector for the whole UMB range.
786  */
787 static LPVOID DOSVM_AllocCodeUMB( DWORD size, WORD *segment, WORD *selector )
788 {
789   LPVOID ptr = DOSVM_AllocUMB( size );
790
791   if (segment)
792     *segment = (DWORD)ptr >> 4;
793
794   if (selector)
795     *selector = alloc_selector( ptr, size, WINE_LDT_FLAGS_CODE );
796
797   return ptr;
798 }
799
800
801 /***********************************************************************
802  *           DOSVM_AllocDataUMB
803  *
804  * Allocate upper memory block for storing data.
805  * Initializes real mode segment and 16-bit protected mode selector
806  * for the allocated data block.
807  */
808 LPVOID DOSVM_AllocDataUMB( DWORD size, WORD *segment, WORD *selector )
809 {
810   LPVOID ptr = DOSVM_AllocUMB( size );
811
812   if (segment)
813     *segment = (DWORD)ptr >> 4;
814
815   if (selector)
816     *selector = alloc_selector( ptr, size, WINE_LDT_FLAGS_DATA );
817
818   return ptr;
819 }
820
821
822 /***********************************************************************
823  *           DOSVM_InitSegments
824  *
825  * Initializes DOSVM_dpmi_segments. Allocates required memory and
826  * sets up segments and selectors for accessing the memory.
827  */
828 void DOSVM_InitSegments(void)
829 {
830     LPSTR ptr;
831     int   i;
832
833     static const char wrap_code[]={
834      0xCD,0x31, /* int $0x31 */
835      0xCB       /* lret */
836     };
837
838     static const char enter_xms[]=
839     {
840         /* XMS hookable entry point */
841         0xEB,0x03,           /* jmp entry */
842         0x90,0x90,0x90,      /* nop;nop;nop */
843                              /* entry: */
844         /* real entry point */
845         /* for simplicity, we'll just use the same hook as DPMI below */
846         0xCD,0x31,           /* int $0x31 */
847         0xCB                 /* lret */
848     };
849
850     static const char enter_pm[]=
851     {
852         0x50,                /* pushw %ax */
853         0x52,                /* pushw %dx */
854         0x55,                /* pushw %bp */
855         0x89,0xE5,           /* movw %sp,%bp */
856         /* get return CS */
857         0x8B,0x56,0x08,      /* movw 8(%bp),%dx */
858         /* just call int 31 here to get into protected mode... */
859         /* it'll check whether it was called from dpmi_seg... */
860         0xCD,0x31,           /* int $0x31 */
861         /* we are now in the context of a 16-bit relay call */
862         /* need to fixup our stack;
863          * 16-bit relay return address will be lost,
864          * but we won't worry quite yet
865          */
866         0x8E,0xD0,           /* movw %ax,%ss */
867         0x66,0x0F,0xB7,0xE5, /* movzwl %bp,%esp */
868         /* set return CS */
869         0x89,0x56,0x08,      /* movw %dx,8(%bp) */
870         0x5D,                /* popw %bp */
871         0x5A,                /* popw %dx */
872         0x58,                /* popw %ax */
873         0xfb,                /* sti, enable and check virtual interrupts */
874         0xCB                 /* lret */
875     };
876
877     static const char relay[]=
878     {
879         0xca, 0x04, 0x00, /* 16-bit far return and pop 4 bytes (relay void* arg) */
880         0xcd, 0x31,       /* int 31 */
881         0xfb, 0x66, 0xcb  /* sti and 32-bit far return */
882     };
883
884     /*
885      * Allocate pointer array.
886      */
887     DOSVM_dpmi_segments = DOSVM_AllocUMB( sizeof(struct DPMI_segments) );
888
889     /*
890      * RM / offset 0: Exit from real mode.
891      * RM / offset 2: Points to lret opcode.
892      */
893     ptr = DOSVM_AllocCodeUMB( sizeof(wrap_code),
894                               &DOSVM_dpmi_segments->wrap_seg, 0 );
895     memcpy( ptr, wrap_code, sizeof(wrap_code) );
896
897     /*
898      * RM / offset 0: XMS driver entry.
899      */
900     ptr = DOSVM_AllocCodeUMB( sizeof(enter_xms),
901                               &DOSVM_dpmi_segments->xms_seg, 0 );
902     memcpy( ptr, enter_xms, sizeof(enter_xms) );
903
904     /*
905      * RM / offset 0: Switch to DPMI.
906      * PM / offset 8: DPMI raw mode switch.
907      */
908     ptr = DOSVM_AllocCodeUMB( sizeof(enter_pm),
909                               &DOSVM_dpmi_segments->dpmi_seg,
910                               &DOSVM_dpmi_segments->dpmi_sel );
911     memcpy( ptr, enter_pm, sizeof(enter_pm) );
912
913     /*
914      * PM / offset N*6: Interrupt N in DPMI32.
915      */
916     ptr = DOSVM_AllocCodeUMB( 6 * 256,
917                               0, &DOSVM_dpmi_segments->int48_sel );
918     for(i=0; i<256; i++) {
919         /*
920          * Each 32-bit interrupt handler is 6 bytes:
921          * 0xCD,<i>            = int <i> (nested 16-bit interrupt)
922          * 0x66,0xCA,0x04,0x00 = ret 4   (32-bit far return and pop 4 bytes / eflags)
923          */
924         ptr[i * 6 + 0] = 0xCD;
925         ptr[i * 6 + 1] = i;
926         ptr[i * 6 + 2] = 0x66;
927         ptr[i * 6 + 3] = 0xCA;
928         ptr[i * 6 + 4] = 0x04;
929         ptr[i * 6 + 5] = 0x00;
930     }
931
932     /*
933      * PM / offset N*5: Interrupt N in 16-bit protected mode.
934      */
935     ptr = DOSVM_AllocCodeUMB( 5 * 256,
936                               0, &DOSVM_dpmi_segments->int16_sel );
937     for(i=0; i<256; i++) {
938         /*
939          * Each 16-bit interrupt handler is 5 bytes:
940          * 0xCD,<i>       = int <i> (interrupt)
941          * 0xCA,0x02,0x00 = ret 2   (16-bit far return and pop 2 bytes / eflags)
942          */
943         ptr[i * 5 + 0] = 0xCD;
944         ptr[i * 5 + 1] = i;
945         ptr[i * 5 + 2] = 0xCA;
946         ptr[i * 5 + 3] = 0x02;
947         ptr[i * 5 + 4] = 0x00;
948     }
949
950     /*
951      * PM / offset 0: Stub where __wine_call_from_16_regs returns.
952      * PM / offset 3: Stub which swaps back to 32-bit application code/stack.
953      * PM / offset 5: Stub which enables interrupts
954      */
955     ptr = DOSVM_AllocCodeUMB( sizeof(relay),
956                               0,  &DOSVM_dpmi_segments->relay_code_sel);
957     memcpy( ptr, relay, sizeof(relay) );
958
959     /*
960      * Space for 16-bit stack used by relay code.
961      */
962     ptr = DOSVM_AllocDataUMB( DOSVM_RELAY_DATA_SIZE,
963                               0, &DOSVM_dpmi_segments->relay_data_sel);
964     memset( ptr, 0, DOSVM_RELAY_DATA_SIZE );
965
966     /*
967      * As we store code in UMB we should make sure it is executable
968      */
969     VirtualProtect((void *)DOSVM_UMB_BOTTOM, DOSVM_UMB_TOP - DOSVM_UMB_BOTTOM, PAGE_EXECUTE_READWRITE, NULL);
970
971     event_notifier = CreateEventW(NULL, FALSE, FALSE, NULL);
972 }