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