winedos: Merge all of winedos back into krnl386.
[wine] / dlls / krnl386.exe16 / int31.c
1 /*
2  * DPMI 0.9 emulation
3  *
4  * Copyright 1995 Alexandre Julliard
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
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <stdarg.h>
25
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winternl.h"
29 #include "wine/winbase16.h"
30 #include "wownt32.h"
31 #include "kernel16_private.h"
32 #include "dosexe.h"
33
34 #include "excpt.h"
35 #include "wine/debug.h"
36 #include "wine/exception.h"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(int31);
39
40 /* Structure for real-mode callbacks */
41 typedef struct
42 {
43     DWORD edi;
44     DWORD esi;
45     DWORD ebp;
46     DWORD reserved;
47     DWORD ebx;
48     DWORD edx;
49     DWORD ecx;
50     DWORD eax;
51     WORD  fl;
52     WORD  es;
53     WORD  ds;
54     WORD  fs;
55     WORD  gs;
56     WORD  ip;
57     WORD  cs;
58     WORD  sp;
59     WORD  ss;
60 } REALMODECALL;
61
62 typedef struct tagRMCB {
63     DWORD address;
64     DWORD proc_ofs,proc_sel;
65     DWORD regs_ofs,regs_sel;
66     struct tagRMCB *next;
67 } RMCB;
68
69 static RMCB *FirstRMCB = NULL;
70 static WORD dpmi_flag;
71 static void* lastvalloced = NULL;
72 static BYTE DPMI_retval;
73
74 #include "pshpack1.h"
75
76 typedef struct {
77  WORD Handle;
78  DWORD Offset;
79 } MOVEOFS;
80
81 typedef struct {
82  DWORD Length;
83  MOVEOFS Source;
84  MOVEOFS Dest;
85 } MOVESTRUCT;
86
87 #include "poppack.h"
88
89 /**********************************************************************
90  *          DOSVM_IsDos32
91  * 
92  * Return TRUE if we are in 32-bit protected mode DOS process.
93  */
94 BOOL DOSVM_IsDos32(void)
95 {
96   return (dpmi_flag & 1) ? TRUE : FALSE;
97 }
98
99
100 /**********************************************************************
101  *          alloc_pm_selector
102  *
103  * Allocate a 64k sized selector corresponding to a real mode segment.
104  */
105 static WORD alloc_pm_selector( WORD seg, unsigned char flags )
106 {
107     WORD sel = wine_ldt_alloc_entries( 1 );
108
109     if (sel)
110     {
111         LDT_ENTRY entry;
112         wine_ldt_set_base( &entry, (void *)(seg << 4) );
113         wine_ldt_set_limit( &entry, 0xffff );
114         wine_ldt_set_flags( &entry, flags );
115         wine_ldt_set_entry( sel, &entry );
116     }
117     return sel;
118 }
119
120
121 /**********************************************************************
122  *          dpmi_exception_handler
123  *
124  * Handle EXCEPTION_VM86_STI exceptions generated
125  * when there are pending asynchronous events.
126  */
127 static LONG WINAPI dpmi_exception_handler(EXCEPTION_POINTERS *eptr)
128 {
129     EXCEPTION_RECORD *rec = eptr->ExceptionRecord;
130     CONTEXT *context = eptr->ContextRecord;
131
132     if (rec->ExceptionCode == EXCEPTION_VM86_STI)
133     {
134         if (ISV86(context))
135             ERR( "Real mode STI caught by protected mode handler!\n" );
136         DOSVM_SendQueuedEvents(context);
137         return EXCEPTION_CONTINUE_EXECUTION;
138     }
139     else if (rec->ExceptionCode == EXCEPTION_VM86_INTx)
140     {
141         if (ISV86(context))
142             ERR( "Real mode INTx caught by protected mode handler!\n" );
143         DPMI_retval = (BYTE)rec->ExceptionInformation[0];
144         return EXCEPTION_EXECUTE_HANDLER;
145     }
146
147     return EXCEPTION_CONTINUE_SEARCH;
148 }
149
150
151 /**********************************************************************
152  *          INT_GetRealModeContext
153  */
154 static void INT_GetRealModeContext( REALMODECALL *call, CONTEXT86 *context )
155 {
156     context->Eax    = call->eax;
157     context->Ebx    = call->ebx;
158     context->Ecx    = call->ecx;
159     context->Edx    = call->edx;
160     context->Esi    = call->esi;
161     context->Edi    = call->edi;
162     context->Ebp    = call->ebp;
163     context->EFlags = call->fl | V86_FLAG;
164     context->Eip    = call->ip;
165     context->Esp    = call->sp;
166     context->SegCs  = call->cs;
167     context->SegDs  = call->ds;
168     context->SegEs  = call->es;
169     context->SegFs  = call->fs;
170     context->SegGs  = call->gs;
171     context->SegSs  = call->ss;
172 }
173
174
175 /**********************************************************************
176  *          INT_SetRealModeContext
177  */
178 static void INT_SetRealModeContext( REALMODECALL *call, CONTEXT86 *context )
179 {
180     call->eax = context->Eax;
181     call->ebx = context->Ebx;
182     call->ecx = context->Ecx;
183     call->edx = context->Edx;
184     call->esi = context->Esi;
185     call->edi = context->Edi;
186     call->ebp = context->Ebp;
187     call->fl  = LOWORD(context->EFlags);
188     call->ip  = LOWORD(context->Eip);
189     call->sp  = LOWORD(context->Esp);
190     call->cs  = context->SegCs;
191     call->ds  = context->SegDs;
192     call->es  = context->SegEs;
193     call->fs  = context->SegFs;
194     call->gs  = context->SegGs;
195     call->ss  = context->SegSs;
196 }
197
198 /**********************************************************************
199  *          DPMI_xalloc
200  * special virtualalloc, allocates linearly monoton growing memory.
201  * (the usual VirtualAlloc does not satisfy that restriction)
202  */
203 static LPVOID DPMI_xalloc( DWORD len ) 
204 {
205     LPVOID  ret;
206     LPVOID  oldlastv = lastvalloced;
207
208     if (lastvalloced) 
209     {
210         int xflag = 0;
211
212         ret = NULL;
213         while (!ret) 
214         {
215             ret = VirtualAlloc( lastvalloced, len,
216                                 MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE );
217             if (!ret)
218                 lastvalloced = (char *) lastvalloced + 0x10000;
219
220             /* we failed to allocate one in the first round.
221              * try non-linear
222              */
223             if (!xflag && (lastvalloced<oldlastv)) 
224             { 
225                 /* wrapped */
226                 FIXME( "failed to allocate linearly growing memory (%d bytes), "
227                        "using non-linear growing...\n", len );
228                 xflag++;
229             }
230
231             /* if we even fail to allocate something in the next
232              * round, return NULL
233              */
234             if ((xflag==1) && (lastvalloced >= oldlastv))
235                 xflag++;
236
237             if ((xflag==2) && (lastvalloced < oldlastv)) {
238                 FIXME( "failed to allocate any memory of %d bytes!\n", len );
239                 return NULL;
240             }
241         }
242     } 
243     else
244     {
245         ret = VirtualAlloc( NULL, len, 
246                             MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE );
247     }
248
249     lastvalloced = (LPVOID)(((DWORD)ret+len+0xffff)&~0xffff);
250     return ret;
251 }
252
253 /**********************************************************************
254  *          DPMI_xfree
255  */
256 static void DPMI_xfree( LPVOID ptr ) 
257 {
258     VirtualFree( ptr, 0, MEM_RELEASE );
259 }
260
261 /**********************************************************************
262  *          DPMI_xrealloc
263  *
264  * FIXME: perhaps we could grow this mapped area... 
265  */
266 static LPVOID DPMI_xrealloc( LPVOID ptr, DWORD newsize ) 
267 {
268     MEMORY_BASIC_INFORMATION        mbi;
269     LPVOID                          newptr;
270
271     newptr = DPMI_xalloc( newsize );
272     if (ptr) 
273     {
274         if (!VirtualQuery(ptr,&mbi,sizeof(mbi))) 
275         {
276             FIXME( "realloc of DPMI_xallocd region %p?\n", ptr );
277             return NULL;
278         }
279
280         if (mbi.State == MEM_FREE) 
281         {
282             FIXME( "realloc of DPMI_xallocd region %p?\n", ptr );
283             return NULL;
284         }
285
286         /* We do not shrink allocated memory. most reallocs
287          * only do grows anyway
288          */
289         if (newsize <= mbi.RegionSize)
290             return ptr;
291
292         memcpy( newptr, ptr, mbi.RegionSize );
293         DPMI_xfree( ptr );
294     }
295
296     return newptr;
297 }
298
299
300 void DPMI_CallRMCB32(RMCB *rmcb, UINT16 ss, DWORD esp, UINT16*es, DWORD*edi)
301 #if 0 /* original code, which early gccs puke on */
302 {
303     int _clobber;
304     __asm__ __volatile__(
305         "pushl %%ebp\n"
306         "pushl %%ebx\n"
307         "pushl %%es\n"
308         "pushl %%ds\n"
309         "pushfl\n"
310         "mov %7,%%es\n"
311         "mov %5,%%ds\n"
312         ".byte 0x36, 0xff, 0x18\n" /* lcall *%ss:(%eax) */
313         "popl %%ds\n"
314         "mov %%es,%0\n"
315         "popl %%es\n"
316         "popl %%ebx\n"
317         "popl %%ebp\n"
318     : "=d" (*es), "=D" (*edi), "=S" (_clobber), "=a" (_clobber), "=c" (_clobber)
319     : "0" (ss), "2" (esp),
320       "4" (rmcb->regs_sel), "1" (rmcb->regs_ofs),
321       "3" (&rmcb->proc_ofs) );
322 }
323 #else /* code generated by a gcc new enough */
324 ;
325 __ASM_GLOBAL_FUNC(DPMI_CallRMCB32,
326     "pushl %ebp\n\t"
327     __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
328     __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
329     "movl %esp,%ebp\n\t"
330     __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
331     "pushl %edi\n\t"
332     __ASM_CFI(".cfi_rel_offset %edi,-4\n\t")
333     "pushl %esi\n\t"
334     __ASM_CFI(".cfi_rel_offset %esi,-8\n\t")
335     "movl 0x8(%ebp),%eax\n\t"
336     "movl 0x10(%ebp),%esi\n\t"
337     "movl 0xc(%ebp),%edx\n\t"
338     "movl 0x10(%eax),%ecx\n\t"
339     "movl 0xc(%eax),%edi\n\t"
340     "addl $0x4,%eax\n\t"
341     "pushl %ebp\n\t"
342     "pushl %ebx\n\t"
343     "pushl %es\n\t"
344     "pushl %ds\n\t"
345     "pushfl\n\t"
346     "mov %cx,%es\n\t"
347     "mov %dx,%ds\n\t"
348     ".byte 0x36, 0xff, 0x18\n\t" /* lcall *%ss:(%eax) */
349     "popl %ds\n\t"
350     "mov %es,%dx\n\t"
351     "popl %es\n\t"
352     "popl %ebx\n\t"
353     "popl %ebp\n\t"
354     "movl 0x14(%ebp),%eax\n\t"
355     "movw %dx,(%eax)\n\t"
356     "movl 0x18(%ebp),%edx\n\t"
357     "movl %edi,(%edx)\n\t"
358     "popl %esi\n\t"
359     __ASM_CFI(".cfi_same_value %esi\n\t")
360     "popl %edi\n\t"
361     __ASM_CFI(".cfi_same_value %edi\n\t")
362     "leave\n\t"
363     __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
364     __ASM_CFI(".cfi_same_value %ebp\n\t")
365     "ret")
366 #endif
367
368 /**********************************************************************
369  *          DPMI_CallRMCBProc
370  *
371  * This routine does the hard work of calling a callback procedure.
372  */
373 static void DPMI_CallRMCBProc( CONTEXT86 *context, RMCB *rmcb, WORD flag )
374 {
375     DWORD old_vif = get_vm86_teb_info()->dpmi_vif;
376
377     /* Disable virtual interrupts. */
378     get_vm86_teb_info()->dpmi_vif = 0;
379
380     if (wine_ldt_is_system( rmcb->proc_sel )) {
381         /* Wine-internal RMCB, call directly */
382         ((RMCBPROC)rmcb->proc_ofs)(context);
383     } else __TRY {
384         UINT16 ss,es;
385         DWORD esp,edi;
386
387         INT_SetRealModeContext(MapSL(MAKESEGPTR( rmcb->regs_sel, rmcb->regs_ofs )), context);
388         ss = alloc_pm_selector( context->SegSs, WINE_LDT_FLAGS_DATA );
389         esp = context->Esp;
390
391         FIXME("untested!\n");
392
393         /* The called proc ends with an IRET, and takes these parameters:
394          * DS:ESI = pointer to real-mode SS:SP
395          * ES:EDI = pointer to real-mode call structure
396          * It returns:
397          * ES:EDI = pointer to real-mode call structure (may be a copy)
398          * It is the proc's responsibility to change the return CS:IP in the
399          * real-mode call structure. */
400         if (flag & 1) {
401             /* 32-bit DPMI client */
402             DPMI_CallRMCB32(rmcb, ss, esp, &es, &edi);
403         } else {
404             /* 16-bit DPMI client */
405             CONTEXT86 ctx = *context;
406             ctx.SegCs = rmcb->proc_sel;
407             ctx.Eip   = rmcb->proc_ofs;
408             ctx.SegDs = ss;
409             ctx.Esi   = esp;
410             ctx.SegEs = rmcb->regs_sel;
411             ctx.Edi   = rmcb->regs_ofs;
412             /* FIXME: I'm pretty sure this isn't right - should push flags first */
413             WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&ctx );
414             es = ctx.SegEs;
415             edi = ctx.Edi;
416         }
417         wine_ldt_free_entries( ss, 1 );
418         INT_GetRealModeContext( MapSL( MAKESEGPTR( es, edi )), context);
419     } __EXCEPT(dpmi_exception_handler) { } __ENDTRY
420
421     /* Restore virtual interrupt flag. */
422     get_vm86_teb_info()->dpmi_vif = old_vif;
423 }
424
425
426 /**********************************************************************
427  *          DPMI_CallRMProc
428  *
429  * This routine does the hard work of calling a real mode procedure.
430  */
431 int DPMI_CallRMProc( CONTEXT86 *context, LPWORD stack, int args, int iret )
432 {
433     LPWORD stack16;
434     LPVOID addr = NULL; /* avoid gcc warning */
435     RMCB *CurrRMCB;
436     int alloc = 0, already = 0;
437     BYTE *code;
438
439     TRACE("EAX=%08x EBX=%08x ECX=%08x EDX=%08x\n",
440                  context->Eax, context->Ebx, context->Ecx, context->Edx );
441     TRACE("ESI=%08x EDI=%08x ES=%04x DS=%04x CS:IP=%04x:%04x, %d WORD arguments, %s\n",
442                  context->Esi, context->Edi, context->SegEs, context->SegDs,
443                  context->SegCs, LOWORD(context->Eip), args, iret?"IRET":"FAR" );
444
445 callrmproc_again:
446
447 /* there might be some code that just jumps to RMCBs or the like,
448    in which case following the jumps here might get us to a shortcut */
449     code = CTX_SEG_OFF_TO_LIN(context, context->SegCs, context->Eip);
450     switch (*code) {
451     case 0xe9: /* JMP NEAR */
452       context->Eip += 3 + *(WORD *)(code+1);
453       /* yeah, I know these gotos don't look good... */
454       goto callrmproc_again;
455     case 0xea: /* JMP FAR */
456       context->Eip = *(WORD *)(code+1);
457       context->SegCs = *(WORD *)(code+3);
458       /* ...but since the label is there anyway... */
459       goto callrmproc_again;
460     case 0xeb: /* JMP SHORT */
461       context->Eip += 2 + *(signed char *)(code+1);
462       /* ...because of other gotos below, so... */
463       goto callrmproc_again;
464     }
465
466 /* shortcut for chaining to internal interrupt handlers */
467     if ((context->SegCs == 0xF000) && iret)
468     {
469         DOSVM_CallBuiltinHandler( context, LOWORD(context->Eip)/4 );
470         return 0;
471     }
472
473 /* shortcut for RMCBs */
474     CurrRMCB = FirstRMCB;
475
476     while (CurrRMCB && (HIWORD(CurrRMCB->address) != context->SegCs))
477         CurrRMCB = CurrRMCB->next;
478
479     if (!CurrRMCB && !MZ_Current())
480     {
481         FIXME("DPMI real-mode call using DOS VM task system, not fully tested!\n");
482         TRACE("creating VM86 task\n");
483         MZ_AllocDPMITask();
484     }
485     if (!already) {
486         if (!context->SegSs) {
487             alloc = 1; /* allocate default stack */
488             stack16 = addr = DOSMEM_AllocBlock( 64, (UINT16 *)&(context->SegSs) );
489             context->Esp = 64-2;
490             stack16 += 32-1;
491             if (!addr) {
492                 ERR("could not allocate default stack\n");
493                 return 1;
494             }
495         } else {
496             stack16 = CTX_SEG_OFF_TO_LIN(context, context->SegSs, context->Esp);
497         }
498         context->Esp -= (args + (iret?1:0)) * sizeof(WORD);
499         stack16 -= args;
500         if (args) memcpy(stack16, stack, args*sizeof(WORD) );
501         /* push flags if iret */
502         if (iret) {
503             stack16--; args++;
504             *stack16 = LOWORD(context->EFlags);
505         }
506         /* push return address (return to interrupt wrapper) */
507         *(--stack16) = DOSVM_dpmi_segments->wrap_seg;
508         *(--stack16) = 0;
509         /* adjust stack */
510         context->Esp -= 2*sizeof(WORD);
511         already = 1;
512     }
513
514     if (CurrRMCB) {
515         /* RMCB call, invoke protected-mode handler directly */
516         DPMI_CallRMCBProc(context, CurrRMCB, dpmi_flag);
517         /* check if we returned to where we thought we would */
518         if ((context->SegCs != DOSVM_dpmi_segments->wrap_seg) ||
519             (LOWORD(context->Eip) != 0)) {
520             /* we need to continue at different address in real-mode space,
521                so we need to set it all up for real mode again */
522             goto callrmproc_again;
523         }
524     } else {
525         TRACE("entering real mode...\n");
526         DOSVM_Enter( context );
527         TRACE("returned from real-mode call\n");
528     }
529     if (alloc) DOSMEM_FreeBlock( addr );
530     return 0;
531 }
532
533
534 /**********************************************************************
535  *          CallRMInt
536  */
537 static void DOSVM_CallRMInt( CONTEXT86 *context )
538 {
539     CONTEXT86 realmode_ctx;
540     FARPROC16 rm_int = DOSVM_GetRMHandler( BL_reg(context) );
541     REALMODECALL *call = CTX_SEG_OFF_TO_LIN( context, 
542                                              context->SegEs, 
543                                              context->Edi );
544     INT_GetRealModeContext( call, &realmode_ctx );
545
546     /* we need to check if a real-mode program has hooked the interrupt */
547     if (HIWORD(rm_int)!=0xF000) {
548         /* yup, which means we need to switch to real mode... */
549         realmode_ctx.SegCs = HIWORD(rm_int);
550         realmode_ctx.Eip   = LOWORD(rm_int);
551         if (DPMI_CallRMProc( &realmode_ctx, NULL, 0, TRUE))
552           SET_CFLAG(context);
553     } else {
554         RESET_CFLAG(context);
555         /* use the IP we have instead of BL_reg, in case some apps
556            decide to move interrupts around for whatever reason... */
557         DOSVM_CallBuiltinHandler( &realmode_ctx, LOWORD(rm_int)/4 );
558     }
559     INT_SetRealModeContext( call, &realmode_ctx );
560 }
561
562
563 /**********************************************************************
564  *          CallRMProc
565  */
566 static void DOSVM_CallRMProc( CONTEXT86 *context, int iret )
567 {
568     REALMODECALL *p = CTX_SEG_OFF_TO_LIN( context, 
569                                           context->SegEs, 
570                                           context->Edi );
571     CONTEXT86 context16;
572
573     TRACE("RealModeCall: EAX=%08x EBX=%08x ECX=%08x EDX=%08x\n",
574           p->eax, p->ebx, p->ecx, p->edx);
575     TRACE("              ESI=%08x EDI=%08x ES=%04x DS=%04x CS:IP=%04x:%04x, %d WORD arguments, %s\n",
576           p->esi, p->edi, p->es, p->ds, p->cs, p->ip, CX_reg(context), iret?"IRET":"FAR" );
577
578     if (!(p->cs) && !(p->ip)) { /* remove this check
579                                    if Int21/6501 case map function
580                                    has been implemented */
581         SET_CFLAG(context);
582         return;
583      }
584     INT_GetRealModeContext(p, &context16);
585     DPMI_CallRMProc( &context16, ((LPWORD)MapSL(MAKESEGPTR(context->SegSs, LOWORD(context->Esp))))+3,
586                      CX_reg(context), iret );
587     INT_SetRealModeContext(p, &context16);
588 }
589
590
591 /* (see dosmem.c, function DOSMEM_InitDPMI) */
592 static void StartPM( CONTEXT86 *context )
593 {
594     UINT16 cs, ss, ds, es;
595     CONTEXT86 pm_ctx;
596     DWORD psp_ofs = (DWORD)(DOSVM_psp<<4);
597     PDB16 *psp = (PDB16 *)psp_ofs;
598     HANDLE16 env_seg = psp->environment;
599     unsigned char selflags = WINE_LDT_FLAGS_DATA;
600
601     RESET_CFLAG(context);
602     dpmi_flag = AX_reg(context);
603 /* our mode switch wrapper have placed the desired CS into DX */
604     cs = alloc_pm_selector( context->Edx, WINE_LDT_FLAGS_CODE );
605 /* due to a flaw in some CPUs (at least mine), it is best to mark stack segments as 32-bit if they
606    can be used in 32-bit code. Otherwise, these CPUs may not set the high word of esp during a
607    ring transition (from kernel code) to the 16-bit stack, and this causes trouble if executing
608    32-bit code using this stack. */
609     if (dpmi_flag & 1) selflags |= WINE_LDT_FLAGS_32BIT;
610     ss = alloc_pm_selector( context->SegSs, selflags );
611 /* do the same for the data segments, just in case */
612     if (context->SegDs == context->SegSs) ds = ss;
613     else ds = alloc_pm_selector( context->SegDs, selflags );
614     es = alloc_pm_selector( DOSVM_psp, selflags );
615 /* convert environment pointer, as the spec says, but we're a bit lazy about the size here... */
616     psp->environment = alloc_pm_selector( env_seg, WINE_LDT_FLAGS_DATA );
617
618     pm_ctx = *context;
619     pm_ctx.SegCs = DOSVM_dpmi_segments->dpmi_sel;
620 /* our mode switch wrapper expects the new CS in DX, and the new SS in AX */
621     pm_ctx.Eax   = ss;
622     pm_ctx.Edx   = cs;
623     pm_ctx.SegDs = ds;
624     pm_ctx.SegEs = es;
625     pm_ctx.SegFs = wine_get_fs();
626     pm_ctx.SegGs = wine_get_gs();
627     pm_ctx.EFlags &= ~V86_FLAG;
628
629     TRACE("DOS program is now entering %d-bit protected mode\n", 
630           DOSVM_IsDos32() ? 32 : 16);
631
632     __TRY 
633     {
634         WOWCallback16Ex( 0, WCB16_REGS, 0, NULL, (DWORD *)&pm_ctx );
635     } 
636     __EXCEPT(dpmi_exception_handler) 
637     { 
638     } 
639     __ENDTRY
640
641     TRACE( "Protected mode DOS program is terminating\n" );
642
643     /*
644      * FIXME: Instead of calling DOSVM_Exit, we should release all
645      *        allocated protected mode resources and call MZ_Exit
646      *        using real mode context. See DPMI specification.
647      */
648     DOSVM_Exit( DPMI_retval );
649
650 #if 0
651     wine_ldt_free_entries( psp->environment, 1 );
652     psp->environment = env_seg;
653     wine_ldt_free_entries(es,1);
654     if (ds != ss) wine_ldt_free_entries(ds,1);
655     wine_ldt_free_entries(ss,1);
656     wine_ldt_free_entries(cs,1);
657 #endif
658 }
659
660 static RMCB *DPMI_AllocRMCB( void )
661 {
662     RMCB *NewRMCB = HeapAlloc(GetProcessHeap(), 0, sizeof(RMCB));
663     UINT16 uParagraph;
664
665     if (NewRMCB)
666     {
667         LPVOID RMCBmem = DOSMEM_AllocBlock(4, &uParagraph);
668         LPBYTE p = RMCBmem;
669
670         *p++ = 0xcd; /* RMCB: */
671         *p++ = 0x31; /* int $0x31 */
672 /* it is the called procedure's task to change the return CS:EIP
673    the DPMI 0.9 spec states that if it doesn't, it will be called again */
674         *p++ = 0xeb;
675         *p++ = 0xfc; /* jmp RMCB */
676         NewRMCB->address = MAKELONG(0, uParagraph);
677         NewRMCB->next = FirstRMCB;
678         FirstRMCB = NewRMCB;
679     }
680     return NewRMCB;
681 }
682
683
684 FARPROC16 DPMI_AllocInternalRMCB( RMCBPROC proc )
685 {
686     RMCB *NewRMCB = DPMI_AllocRMCB();
687
688     if (NewRMCB) {
689         NewRMCB->proc_ofs = (DWORD)proc;
690         NewRMCB->proc_sel = 0;
691         NewRMCB->regs_ofs = 0;
692         NewRMCB->regs_sel = 0;
693         return (FARPROC16)(NewRMCB->address);
694     }
695     return NULL;
696 }
697
698
699 static int DPMI_FreeRMCB( DWORD address )
700 {
701     RMCB *CurrRMCB = FirstRMCB;
702     RMCB *PrevRMCB = NULL;
703
704     while (CurrRMCB && (CurrRMCB->address != address))
705     {
706         PrevRMCB = CurrRMCB;
707         CurrRMCB = CurrRMCB->next;
708     }
709     if (CurrRMCB)
710     {
711         if (PrevRMCB)
712         PrevRMCB->next = CurrRMCB->next;
713             else
714         FirstRMCB = CurrRMCB->next;
715         DOSMEM_FreeBlock(PTR_REAL_TO_LIN(SELECTOROF(CurrRMCB->address),OFFSETOF(CurrRMCB->address)));
716         HeapFree(GetProcessHeap(), 0, CurrRMCB);
717         return 0;
718     }
719     return 1;
720 }
721
722
723 /**********************************************************************
724  *          DOSVM_RawModeSwitchHandler
725  *
726  * DPMI Raw Mode Switch handler
727  */
728 void WINAPI DOSVM_RawModeSwitchHandler( CONTEXT86 *context )
729 {
730   CONTEXT86 rm_ctx;
731   int ret;
732
733   /* initialize real-mode context as per spec */
734   memset(&rm_ctx, 0, sizeof(rm_ctx));
735   rm_ctx.SegDs  = AX_reg(context);
736   rm_ctx.SegEs  = CX_reg(context);
737   rm_ctx.SegSs  = DX_reg(context);
738   rm_ctx.Esp    = context->Ebx;
739   rm_ctx.SegCs  = SI_reg(context);
740   rm_ctx.Eip    = context->Edi;
741   rm_ctx.Ebp    = context->Ebp;
742   rm_ctx.SegFs  = 0;
743   rm_ctx.SegGs  = 0;
744
745   /* Copy interrupt state. */
746   if (get_vm86_teb_info()->dpmi_vif)
747       rm_ctx.EFlags = V86_FLAG | VIF_MASK;
748   else
749       rm_ctx.EFlags = V86_FLAG;
750
751   /* enter real mode again */
752   TRACE("re-entering real mode at %04x:%04x\n",rm_ctx.SegCs,rm_ctx.Eip);
753   ret = DOSVM_Enter( &rm_ctx );
754   /* when the real-mode stuff call its mode switch address,
755      DOSVM_Enter will return and we will continue here */
756
757   if (ret<0) {
758     ERR("Sync lost!\n");
759     /* if the sync was lost, there's no way to recover */
760     ExitProcess(1);
761   }
762
763   /* alter protected-mode context as per spec */
764   context->SegDs   = LOWORD(rm_ctx.Eax);
765   context->SegEs   = LOWORD(rm_ctx.Ecx);
766   context->SegSs   = LOWORD(rm_ctx.Edx);
767   context->Esp     = rm_ctx.Ebx;
768   context->SegCs   = LOWORD(rm_ctx.Esi);
769   context->Eip     = rm_ctx.Edi;
770   context->Ebp     = rm_ctx.Ebp;
771   context->SegFs   = 0;
772   context->SegGs   = 0;
773
774   /* Copy interrupt state. */
775   if (rm_ctx.EFlags & VIF_MASK)
776       get_vm86_teb_info()->dpmi_vif = 1;
777   else
778       get_vm86_teb_info()->dpmi_vif = 0;
779
780   /* Return to new address and hope that we didn't mess up */
781   TRACE("re-entering protected mode at %04x:%08x\n",
782       context->SegCs, context->Eip);
783 }
784
785
786 /**********************************************************************
787  *          AllocRMCB
788  */
789 static void DOSVM_AllocRMCB( CONTEXT86 *context )
790 {
791     RMCB *NewRMCB = DPMI_AllocRMCB();
792
793     TRACE("Function to call: %04x:%04x\n", (WORD)context->SegDs, SI_reg(context) );
794
795     if (NewRMCB)
796     {
797        NewRMCB->proc_ofs = DOSVM_IsDos32() ? context->Esi : LOWORD(context->Esi);
798         NewRMCB->proc_sel = context->SegDs;
799        NewRMCB->regs_ofs = DOSVM_IsDos32() ? context->Edi : LOWORD(context->Edi);
800         NewRMCB->regs_sel = context->SegEs;
801         SET_CX( context, HIWORD(NewRMCB->address) );
802         SET_DX( context, LOWORD(NewRMCB->address) );
803     }
804     else
805     {
806         SET_AX( context, 0x8015 ); /* callback unavailable */
807         SET_CFLAG(context);
808     }
809 }
810
811
812 /**********************************************************************
813  *          FreeRMCB
814  */
815 static void DOSVM_FreeRMCB( CONTEXT86 *context )
816 {
817     FIXME("callback address: %04x:%04x\n",
818           CX_reg(context), DX_reg(context));
819
820     if (DPMI_FreeRMCB(MAKELONG(DX_reg(context), CX_reg(context)))) {
821         SET_AX( context, 0x8024 ); /* invalid callback address */
822         SET_CFLAG(context);
823     }
824 }
825
826
827 static BYTE * XMS_Offset( MOVEOFS *ofs )
828 {
829     if (ofs->Handle) return (BYTE*)GlobalLock16(ofs->Handle)+ofs->Offset;
830     else return PTR_REAL_TO_LIN(SELECTOROF(ofs->Offset),OFFSETOF(ofs->Offset));
831 }
832
833 /**********************************************************************
834  *          XMS_Handler
835  */
836 static void XMS_Handler( CONTEXT86 *context )
837 {
838     switch(AH_reg(context))
839     {
840     case 0x00:   /* Get XMS version number */
841         TRACE("get XMS version number\n");
842         SET_AX( context, 0x0200 ); /* 2.0 */
843         SET_BX( context, 0x0000 ); /* internal revision */
844         SET_DX( context, 0x0001 ); /* HMA exists */
845         break;
846     case 0x08:   /* Query Free Extended Memory */
847     {
848         MEMORYSTATUS status;
849
850         TRACE("query free extended memory\n");
851         GlobalMemoryStatus( &status );
852         SET_DX( context, status.dwAvailVirtual >> 10 );
853         SET_AX( context, status.dwAvailVirtual >> 10 );
854         TRACE("returning largest %dK, total %dK\n", AX_reg(context), DX_reg(context));
855     }
856     break;
857     case 0x09:   /* Allocate Extended Memory Block */
858         TRACE("allocate extended memory block (%dK)\n",
859             DX_reg(context));
860         SET_DX( context, GlobalAlloc16(GMEM_MOVEABLE, (DWORD)DX_reg(context)<<10) );
861         SET_AX( context, DX_reg(context) ? 1 : 0 );
862         if (!DX_reg(context)) SET_BL( context, 0xA0 ); /* out of memory */
863         break;
864     case 0x0a:   /* Free Extended Memory Block */
865         TRACE("free extended memory block %04x\n",DX_reg(context));
866        if(!DX_reg(context) || GlobalFree16(DX_reg(context))) {
867          SET_AX( context, 0 );    /* failure */
868          SET_BL( context, 0xa2 ); /* invalid handle */
869        } else
870          SET_AX( context, 1 );    /* success */
871         break;
872     case 0x0b:   /* Move Extended Memory Block */
873     {
874         MOVESTRUCT*move=CTX_SEG_OFF_TO_LIN(context,
875             context->SegDs,context->Esi);
876         BYTE*src,*dst;
877         TRACE("move extended memory block\n");
878         src=XMS_Offset(&move->Source);
879         dst=XMS_Offset(&move->Dest);
880         memcpy(dst,src,move->Length);
881         if (move->Source.Handle) GlobalUnlock16(move->Source.Handle);
882         if (move->Dest.Handle) GlobalUnlock16(move->Dest.Handle);
883         break;
884     }
885     case 0x88:   /* Query Any Free Extended Memory */
886     {
887         MEMORYSTATUS status;
888         SYSTEM_INFO  info;
889
890         TRACE("query any free extended memory\n");
891
892         GlobalMemoryStatus( &status );
893         GetSystemInfo( &info );
894         context->Eax = status.dwAvailVirtual >> 10;
895         context->Edx = status.dwAvailVirtual >> 10;
896         context->Ecx = (DWORD)info.lpMaximumApplicationAddress;
897         SET_BL( context, 0 ); /* No errors. */
898
899         TRACE("returning largest %dK, total %dK, highest 0x%x\n",
900               context->Eax, context->Edx, context->Ecx);
901     }
902     break;
903     default:
904         INT_BARF( context, 0x31 );
905         SET_AX( context, 0x0000 ); /* failure */
906         SET_BL( context, 0x80 );   /* function not implemented */
907         break;
908     }
909 }
910
911
912 /**********************************************************************
913  *         DOSVM_CheckWrappers
914  *
915  * Check if this was really a wrapper call instead of an interrupt.
916  */
917 BOOL DOSVM_CheckWrappers( CONTEXT86 *context )
918 {
919     if (context->SegCs==DOSVM_dpmi_segments->dpmi_seg) {
920         /* This is the protected mode switch */
921         StartPM(context);
922         return TRUE;
923     }
924     else if (context->SegCs==DOSVM_dpmi_segments->xms_seg)
925     {
926         /* This is the XMS driver entry point */
927         XMS_Handler(context);
928         return TRUE;
929     }
930     else
931     {
932         /* Check for RMCB */
933         RMCB *CurrRMCB = FirstRMCB;
934
935         while (CurrRMCB && (HIWORD(CurrRMCB->address) != context->SegCs))
936             CurrRMCB = CurrRMCB->next;
937
938         if (CurrRMCB) {
939             /* RMCB call, propagate to protected-mode handler */
940             DPMI_CallRMCBProc(context, CurrRMCB, dpmi_flag);
941             return TRUE;
942         }
943     }
944
945     return FALSE;
946 }
947
948 /**********************************************************************
949  *         DOSVM_Int31Handler
950  *
951  * Handler for int 31h (DPMI).
952  */
953 void WINAPI DOSVM_Int31Handler( CONTEXT86 *context )
954 {
955     RESET_CFLAG(context);
956     switch(AX_reg(context))
957     {
958     case 0x0000:  /* Allocate LDT descriptors */
959         TRACE( "allocate LDT descriptors (%d)\n", CX_reg(context) );
960         {
961             WORD sel =  AllocSelectorArray16( CX_reg(context) );
962             if(!sel) 
963             {
964                TRACE( "failed\n" );
965                SET_AX( context, 0x8011 ); /* descriptor unavailable */
966                SET_CFLAG( context );
967             } 
968             else 
969             { 
970                 TRACE( "success, array starts at 0x%04x\n", sel );
971                 SET_AX( context, sel );      
972             }
973         }
974         break;
975
976     case 0x0001:  /* Free LDT descriptor */
977         TRACE( "free LDT descriptor (0x%04x)\n", BX_reg(context) );
978         if (FreeSelector16( BX_reg(context) ))
979         {
980             SET_AX( context, 0x8022 );  /* invalid selector */
981             SET_CFLAG( context );
982         }
983         else
984         {
985             /* If a segment register contains the selector being freed, */
986             /* set it to zero. */
987             if (!((context->SegDs^BX_reg(context)) & ~3)) context->SegDs = 0;
988             if (!((context->SegEs^BX_reg(context)) & ~3)) context->SegEs = 0;
989             if (!((context->SegFs^BX_reg(context)) & ~3)) context->SegFs = 0;
990             if (!((context->SegGs^BX_reg(context)) & ~3)) context->SegGs = 0;
991         }
992         break;
993
994     case 0x0002:  /* Real mode segment to descriptor */
995         TRACE( "real mode segment to descriptor (0x%04x)\n", BX_reg(context) );
996         {
997             WORD entryPoint = 0;  /* KERNEL entry point for descriptor */
998             switch(BX_reg(context))
999             {
1000             case 0x0000: entryPoint = 183; break;  /* __0000H */
1001             case 0x0040: entryPoint = 193; break;  /* __0040H */
1002             case 0xa000: entryPoint = 174; break;  /* __A000H */
1003             case 0xb000: entryPoint = 181; break;  /* __B000H */
1004             case 0xb800: entryPoint = 182; break;  /* __B800H */
1005             case 0xc000: entryPoint = 195; break;  /* __C000H */
1006             case 0xd000: entryPoint = 179; break;  /* __D000H */
1007             case 0xe000: entryPoint = 190; break;  /* __E000H */
1008             case 0xf000: entryPoint = 194; break;  /* __F000H */
1009             default:
1010                 FIXME("Real mode segment (%x) to descriptor: no longer supported\n",
1011                       BX_reg(context));
1012                 SET_CFLAG( context );
1013                 break;
1014             }
1015             if (entryPoint)
1016             {
1017                 FARPROC16 proc = GetProcAddress16( GetModuleHandle16( "KERNEL" ),
1018                                                    (LPCSTR)(ULONG_PTR)entryPoint );
1019                 SET_AX( context, LOWORD(proc) );
1020             }
1021         }
1022         break;
1023
1024     case 0x0003:  /* Get next selector increment */
1025         TRACE("get selector increment (__AHINCR)\n");
1026         context->Eax = __AHINCR;
1027         break;
1028
1029     case 0x0004:  /* Lock selector (not supported) */
1030         FIXME("lock selector not supported\n");
1031         context->Eax = 0;  /* FIXME: is this a correct return value? */
1032         break;
1033
1034     case 0x0005:  /* Unlock selector (not supported) */
1035         FIXME("unlock selector not supported\n");
1036         context->Eax = 0;  /* FIXME: is this a correct return value? */
1037         break;
1038
1039     case 0x0006:  /* Get selector base address */
1040         TRACE( "get selector base address (0x%04x)\n", BX_reg(context) );
1041         {
1042             LDT_ENTRY entry;
1043             WORD sel = BX_reg(context);
1044             wine_ldt_get_entry( sel, &entry );
1045             if (wine_ldt_is_empty(&entry))
1046             {
1047                 context->Eax = 0x8022;  /* invalid selector */
1048                 SET_CFLAG(context);
1049             }
1050             else
1051             {
1052                 void *base = wine_ldt_get_base(&entry);
1053                 SET_CX( context, HIWORD(base) );
1054                 SET_DX( context, LOWORD(base) );
1055             }
1056         }
1057         break;
1058
1059     case 0x0007:  /* Set selector base address */
1060         {
1061             DWORD base = MAKELONG( DX_reg(context), CX_reg(context) );
1062             WORD  sel = BX_reg(context);
1063             TRACE( "set selector base address (0x%04x,0x%08x)\n", sel, base );
1064
1065             /* check if Win16 app wants to access lower 64K of DOS memory */
1066             if (base < 0x10000 && DOSVM_IsWin16())
1067                 DOSMEM_MapDosLayout();
1068
1069             SetSelectorBase( sel, base );
1070         }
1071         break;
1072
1073     case 0x0008:  /* Set selector limit */
1074         {
1075             DWORD limit = MAKELONG( DX_reg(context), CX_reg(context) );
1076             TRACE( "set selector limit (0x%04x,0x%08x)\n",
1077                    BX_reg(context), limit );
1078             SetSelectorLimit16( BX_reg(context), limit );
1079         }
1080         break;
1081
1082     case 0x0009:  /* Set selector access rights */
1083         TRACE( "set selector access rights(0x%04x,0x%04x)\n",
1084                BX_reg(context), CX_reg(context) );
1085         SelectorAccessRights16( BX_reg(context), 1, CX_reg(context) );
1086         break;
1087
1088     case 0x000a:  /* Allocate selector alias */
1089         TRACE( "allocate selector alias (0x%04x)\n", BX_reg(context) );
1090         SET_AX( context, AllocCStoDSAlias16( BX_reg(context) ) );
1091         if (!AX_reg(context))
1092         {
1093             SET_AX( context, 0x8011 );  /* descriptor unavailable */
1094             SET_CFLAG(context);
1095         }
1096         break;
1097
1098     case 0x000b:  /* Get descriptor */
1099         TRACE( "get descriptor (0x%04x)\n", BX_reg(context) );
1100         {
1101             LDT_ENTRY *entry = CTX_SEG_OFF_TO_LIN( context, context->SegEs,
1102                                                    context->Edi );
1103             wine_ldt_get_entry( BX_reg(context), entry );
1104         }
1105         break;
1106
1107     case 0x000c:  /* Set descriptor */
1108         TRACE( "set descriptor (0x%04x)\n", BX_reg(context) );
1109         {
1110             LDT_ENTRY *entry = CTX_SEG_OFF_TO_LIN( context, context->SegEs,
1111                                                    context->Edi );
1112             wine_ldt_set_entry( BX_reg(context), entry );
1113         }
1114         break;
1115
1116     case 0x000d:  /* Allocate specific LDT descriptor */
1117         FIXME( "allocate descriptor (0x%04x), stub!\n", BX_reg(context) );
1118         SET_AX( context, 0x8011 ); /* descriptor unavailable */
1119         SET_CFLAG( context );
1120         break;
1121
1122     case 0x000e:  /* Get Multiple Descriptors (1.0) */
1123         FIXME( "get multiple descriptors - unimplemented\n" );
1124         break;
1125
1126     case 0x000f:  /* Set Multiple Descriptors (1.0) */
1127         FIXME( "set multiple descriptors - unimplemented\n" );
1128         break;
1129
1130     case 0x0100:  /* Allocate DOS memory block */
1131         TRACE( "allocate DOS memory block (0x%x paragraphs)\n", BX_reg(context) );
1132         {
1133             DWORD dw = GlobalDOSAlloc16( (DWORD)BX_reg(context) << 4 );
1134             if (dw) {
1135                 SET_AX( context, HIWORD(dw) );
1136                 SET_DX( context, LOWORD(dw) );
1137             } else {
1138                 SET_AX( context, 0x0008 ); /* insufficient memory */
1139                 SET_BX( context, DOSMEM_Available() >> 4 );
1140                 SET_CFLAG(context);
1141             }
1142             break;
1143         }
1144
1145     case 0x0101:  /* Free DOS memory block */
1146         TRACE( "free DOS memory block (0x%04x)\n", DX_reg(context) );
1147         {
1148             WORD error = GlobalDOSFree16( DX_reg(context) );
1149             if (error) {
1150                 SET_AX( context, 0x0009 ); /* memory block address invalid */
1151                 SET_CFLAG( context );
1152             }
1153         }
1154         break;
1155
1156     case 0x0102: /* Resize DOS Memory Block */
1157         FIXME( "resize DOS memory block (0x%04x, 0x%x paragraphs) - unimplemented\n", 
1158                DX_reg(context), BX_reg(context) );
1159         break;
1160
1161     case 0x0200: /* get real mode interrupt vector */
1162         TRACE( "get realmode interrupt vector (0x%02x)\n",
1163                BL_reg(context) );
1164         {
1165             FARPROC16 proc = DOSVM_GetRMHandler( BL_reg(context) );
1166             SET_CX( context, SELECTOROF(proc) );
1167             SET_DX( context, OFFSETOF(proc) );
1168         }
1169         break;
1170
1171     case 0x0201: /* set real mode interrupt vector */
1172         TRACE( "set realmode interrupt vector (0x%02x, 0x%04x:0x%04x)\n", 
1173                BL_reg(context), CX_reg(context), DX_reg(context) );
1174         DOSVM_SetRMHandler( BL_reg(context), 
1175                             (FARPROC16)MAKESEGPTR(CX_reg(context), DX_reg(context)) );
1176         break;
1177
1178     case 0x0202:  /* Get Processor Exception Handler Vector */
1179         FIXME( "Get Processor Exception Handler Vector (0x%02x)\n",
1180                BL_reg(context) );
1181         if (DOSVM_IsDos32()) 
1182         {
1183             SET_CX( context, 0 );
1184             context->Edx = 0;
1185         } 
1186         else 
1187         {
1188             SET_CX( context, 0 );
1189             SET_DX( context, 0 );
1190         }
1191         break;
1192
1193     case 0x0203:  /* Set Processor Exception Handler Vector */
1194          FIXME( "Set Processor Exception Handler Vector (0x%02x)\n",
1195                 BL_reg(context) );
1196          break;
1197
1198     case 0x0204:  /* Get protected mode interrupt vector */
1199         TRACE("get protected mode interrupt handler (0x%02x)\n",
1200               BL_reg(context));
1201         if (DOSVM_IsDos32()) 
1202         {
1203             FARPROC48 handler = DOSVM_GetPMHandler48( BL_reg(context) );
1204             SET_CX( context, handler.selector );
1205             context->Edx = handler.offset;
1206         } 
1207         else 
1208         {
1209             FARPROC16 handler = DOSVM_GetPMHandler16( BL_reg(context) );
1210             SET_CX( context, SELECTOROF(handler) );
1211             SET_DX( context, OFFSETOF(handler) );
1212         }
1213         break;
1214
1215     case 0x0205:  /* Set protected mode interrupt vector */
1216         TRACE("set protected mode interrupt handler (0x%02x,0x%04x:0x%08x)\n",
1217               BL_reg(context), CX_reg(context), context->Edx);
1218         if (DOSVM_IsDos32()) 
1219         {
1220             FARPROC48 handler;
1221             handler.selector = CX_reg(context);
1222             handler.offset = context->Edx;
1223             DOSVM_SetPMHandler48( BL_reg(context), handler );
1224         } 
1225         else 
1226         {
1227             FARPROC16 handler;
1228             handler = (FARPROC16)MAKESEGPTR( CX_reg(context), DX_reg(context)); 
1229             DOSVM_SetPMHandler16( BL_reg(context), handler );
1230         }
1231         break;
1232
1233     case 0x0300:  /* Simulate real mode interrupt */
1234         TRACE( "Simulate real mode interrupt %02x.\n", BL_reg(context));
1235         DOSVM_CallRMInt( context );
1236         break;
1237
1238     case 0x0301:  /* Call real mode procedure with far return */
1239         TRACE( "Call real mode procedure with far return.\n" );
1240         DOSVM_CallRMProc( context, FALSE );
1241         break;
1242
1243     case 0x0302:  /* Call real mode procedure with interrupt return */
1244         TRACE( "Call real mode procedure with interrupt return.\n" );
1245         DOSVM_CallRMProc( context, TRUE );
1246         break;
1247
1248     case 0x0303:  /* Allocate Real Mode Callback Address */
1249         TRACE( "Allocate real mode callback address.\n" );
1250         DOSVM_AllocRMCB( context );
1251         break;
1252
1253     case 0x0304:  /* Free Real Mode Callback Address */
1254         TRACE( "Free real mode callback address.\n" );
1255         DOSVM_FreeRMCB( context );
1256         break;
1257
1258     case 0x0305:  /* Get State Save/Restore Addresses */
1259         TRACE("get state save/restore addresses\n");
1260         /* we probably won't need this kind of state saving */
1261         SET_AX( context, 0 );
1262
1263         /* real mode: just point to the lret */
1264         SET_BX( context, DOSVM_dpmi_segments->wrap_seg );
1265         SET_CX( context, 2 );
1266
1267         /* protected mode: don't have any handler yet... */
1268         /* FIXME: Use DI in 16-bit DPMI and EDI in 32-bit DPMI */
1269         FIXME("no protected-mode dummy state save/restore handler yet\n");
1270         SET_SI( context, 0 );
1271         context->Edi = 0;
1272         break;
1273
1274     case 0x0306:  /* Get Raw Mode Switch Addresses */
1275         TRACE("get raw mode switch addresses\n");
1276
1277         /* real mode, point to standard DPMI return wrapper */
1278         SET_BX( context, DOSVM_dpmi_segments->wrap_seg );
1279         SET_CX( context, 0 );
1280
1281         /* protected mode, point to DPMI call wrapper */
1282         /* FIXME: Use DI in 16-bit DPMI and EDI in 32-bit DPMI */
1283         /* FIXME: Doesn't work in DPMI32... */
1284         SET_SI( context, DOSVM_dpmi_segments->dpmi_sel );
1285         context->Edi = 8; /* offset of the INT 0x31 call */
1286         break;
1287
1288     case 0x0400:  /* Get DPMI version */
1289         TRACE("get DPMI version\n");
1290         {
1291             SYSTEM_INFO si;
1292
1293             GetSystemInfo(&si);
1294             SET_AX( context, 0x005a );  /* DPMI version 0.90 */
1295             SET_BX( context, 0x0005 );  /* Flags: 32-bit, virtual memory */
1296             SET_CL( context, si.wProcessorLevel );
1297             SET_DX( context, 0x0870 );  /* Master/slave interrupt controller base */
1298         }
1299         break;
1300
1301     case 0x0401:  /* Get DPMI Capabilities (1.0) */
1302         FIXME( "get dpmi capabilities - unimplemented\n");
1303         break;
1304
1305     case 0x0500:  /* Get free memory information */
1306         TRACE("get free memory information\n");
1307         {
1308             MEMORYSTATUS status;
1309
1310             /* the layout is just the same as MEMMANINFO, but without
1311              * the dwSize entry.
1312              */
1313             struct
1314             {
1315                 DWORD dwLargestFreeBlock;
1316                 DWORD dwMaxPagesAvailable;
1317                 DWORD dwMaxPagesLockable;
1318                 DWORD dwTotalLinearSpace;
1319                 DWORD dwTotalUnlockedPages;
1320                 DWORD dwFreePages;
1321                 DWORD dwTotalPages;
1322                 DWORD dwFreeLinearSpace;
1323                 DWORD dwSwapFilePages;
1324                 WORD  wPageSize;
1325             } *info = CTX_SEG_OFF_TO_LIN( context, context->SegEs, context->Edi );
1326
1327             GlobalMemoryStatus( &status );
1328             info->wPageSize            = getpagesize();
1329             info->dwLargestFreeBlock   = status.dwAvailVirtual;
1330             info->dwMaxPagesAvailable  = info->dwLargestFreeBlock / info->wPageSize;
1331             info->dwMaxPagesLockable   = info->dwMaxPagesAvailable;
1332             info->dwTotalLinearSpace   = status.dwTotalVirtual / info->wPageSize;
1333             info->dwTotalUnlockedPages = info->dwTotalLinearSpace;
1334             info->dwFreePages          = info->dwMaxPagesAvailable;
1335             info->dwTotalPages         = info->dwTotalLinearSpace;
1336             info->dwFreeLinearSpace    = info->dwMaxPagesAvailable;
1337             info->dwSwapFilePages      = status.dwTotalPageFile / info->wPageSize;
1338             break;
1339         }
1340
1341     case 0x0501:  /* Allocate memory block */
1342         {
1343             DWORD size = MAKELONG( CX_reg(context), BX_reg(context) );
1344             BYTE *ptr;
1345
1346             TRACE( "allocate memory block (%d bytes)\n", size );
1347
1348             ptr = DPMI_xalloc( size );
1349             if (!ptr)
1350             {
1351                 SET_AX( context, 0x8012 );  /* linear memory not available */
1352                 SET_CFLAG(context);
1353             } 
1354             else 
1355             {
1356                 SET_BX( context, HIWORD(ptr) );
1357                 SET_CX( context, LOWORD(ptr) );
1358                 SET_SI( context, HIWORD(ptr) );
1359                 SET_DI( context, LOWORD(ptr) );
1360             }
1361             break;
1362         }
1363
1364     case 0x0502:  /* Free memory block */
1365         {
1366             DWORD handle = MAKELONG( DI_reg(context), SI_reg(context) );
1367             TRACE( "free memory block (0x%08x)\n", handle );
1368             DPMI_xfree( (void *)handle );
1369         }
1370         break;
1371
1372     case 0x0503:  /* Resize memory block */
1373         {
1374             DWORD size = MAKELONG( CX_reg(context), BX_reg(context) );
1375             DWORD handle = MAKELONG( DI_reg(context), SI_reg(context) );
1376             BYTE *ptr;
1377
1378             TRACE( "resize memory block (0x%08x, %d bytes)\n", handle, size );
1379
1380             ptr = DPMI_xrealloc( (void *)handle, size );
1381             if (!ptr)
1382             {
1383                 SET_AX( context, 0x8012 );  /* linear memory not available */
1384                 SET_CFLAG(context);
1385             } else {
1386                 SET_BX( context, HIWORD(ptr) );
1387                 SET_CX( context, LOWORD(ptr) );
1388                 SET_SI( context, HIWORD(ptr) );
1389                 SET_DI( context, LOWORD(ptr) );
1390             }
1391         }
1392         break;
1393
1394     case 0x0507:  /* Set page attributes (1.0) */
1395         FIXME( "set page attributes - unimplemented\n" );
1396         break;  /* Just ignore it */
1397
1398     case 0x0600:  /* Lock linear region */
1399         TRACE( "lock linear region - ignored (no paging)\n" );
1400         break;
1401
1402     case 0x0601:  /* Unlock linear region */
1403         TRACE( "unlock linear region - ignored (no paging)\n" );
1404         break;
1405
1406     case 0x0602:  /* Mark real mode region as pageable */
1407         TRACE( "mark real mode region as pageable - ignored (no paging)\n" );
1408         break;
1409
1410     case 0x0603:  /* Relock real mode region */
1411         TRACE( "relock real mode region - ignored (no paging)\n" );
1412         break;
1413
1414     case 0x0604:  /* Get page size */
1415         TRACE("get pagesize\n");
1416         SET_BX( context, HIWORD(getpagesize()) );
1417         SET_CX( context, LOWORD(getpagesize()) );
1418         break;
1419
1420     case 0x0700: /* Mark pages as paging candidates */
1421         TRACE( "mark pages as paging candidates - ignored (no paging)\n" );
1422         break;
1423
1424     case 0x0701: /* Discard pages */
1425         TRACE( "discard pages - ignored (no paging)\n" );
1426         break;
1427
1428     case 0x0702:  /* Mark page as demand-paging candidate */
1429         TRACE( "mark page as demand-paging candidate - ignored (no paging)\n" );
1430         break;
1431
1432     case 0x0703:  /* Discard page contents */
1433         TRACE( "discard page contents - ignored (no paging)\n" );
1434         break;
1435
1436     case 0x0800:  /* Physical address mapping */
1437         FIXME( "physical address mapping (0x%08x) - unimplemented\n",
1438                MAKELONG(CX_reg(context),BX_reg(context)) );
1439         break;
1440
1441     case 0x0900:  /* Get and Disable Virtual Interrupt State */
1442         TRACE( "Get and Disable Virtual Interrupt State: %d\n",
1443                get_vm86_teb_info()->dpmi_vif );
1444         SET_AL( context, get_vm86_teb_info()->dpmi_vif ? 1 : 0 );
1445         get_vm86_teb_info()->dpmi_vif = 0;
1446         break;
1447
1448     case 0x0901:  /* Get and Enable Virtual Interrupt State */
1449         TRACE( "Get and Enable Virtual Interrupt State: %d\n",
1450                get_vm86_teb_info()->dpmi_vif );
1451         SET_AL( context, get_vm86_teb_info()->dpmi_vif ? 1 : 0 );
1452         get_vm86_teb_info()->dpmi_vif = 1;
1453         break;
1454
1455     case 0x0902:  /* Get Virtual Interrupt State */
1456         TRACE( "Get Virtual Interrupt State: %d\n",
1457                get_vm86_teb_info()->dpmi_vif );
1458         SET_AL( context, get_vm86_teb_info()->dpmi_vif ? 1 : 0 );
1459         break;
1460
1461     case 0x0e00:  /* Get Coprocessor Status (1.0) */
1462         /*
1463          * Return status in AX bits:
1464          * B0    - MPv (MP bit in the virtual MSW/CR0)
1465          *         0 = numeric coprocessor is disabled for this client
1466          *         1 = numeric coprocessor is enabled for this client
1467          * B1    - EMv (EM bit in the virtual MSW/CR0)
1468          *         0 = client is not emulating coprocessor instructions
1469          *         1 = client is emulating coprocessor instructions
1470          * B2    - MPr (MP bit from the actual MSW/CR0)
1471          *         0 = numeric coprocessor is not present
1472          *         1 = numeric coprocessor is present
1473          * B3    - EMr (EM bit from the actual MSW/CR0)
1474          *         0 = host is not emulating coprocessor instructions
1475          *         1 = host is emulating coprocessor instructions
1476          * B4-B7 - coprocessor type
1477          *         00H = no coprocessor
1478          *         02H = 80287
1479          *         03H = 80387
1480          *         04H = 80486 with numeric coprocessor
1481          *         05H-0FH = reserved for future numeric processors
1482          */
1483         TRACE( "Get Coprocessor Status\n" );
1484         SET_AX( context, 69 ); /* 486, coprocessor present and enabled */ 
1485         break;
1486
1487     case 0x0e01: /* Set Coprocessor Emulation (1.0) */
1488         /*
1489          * See function 0x0e00.
1490          * BX bit B0 is new value for MPv.
1491          * BX bit B1 is new value for EMv.
1492          */
1493         if (BX_reg(context) != 1)
1494             FIXME( "Set Coprocessor Emulation to %d - unimplemented\n", 
1495                    BX_reg(context) );
1496         else
1497             TRACE( "Set Coprocessor Emulation - ignored\n" );
1498         break;
1499
1500     default:
1501         INT_BARF( context, 0x31 );
1502         SET_AX( context, 0x8001 );  /* unsupported function */
1503         SET_CFLAG(context);
1504         break;
1505     }  
1506 }