When a Win16 app sets a selector base to low DOS memory, make sure low
[wine] / msdos / dpmi.c
1 /*
2  * DPMI 0.9 emulation
3  *
4  * Copyright 1995 Alexandre Julliard
5  */
6
7 #include <unistd.h>
8 #include <string.h>
9 #include "windef.h"
10 #include "wine/winbase16.h"
11 #include "ldt.h"
12 #include "builtin16.h"
13 #include "global.h"
14 #include "miscemu.h"
15 #include "msdos.h"
16 #include "dosexe.h"
17 #include "task.h"
18 #include "toolhelp.h"
19 #include "selectors.h"
20 #include "process.h"
21 #include "callback.h"
22 #include "debugtools.h"
23
24 DEFAULT_DEBUG_CHANNEL(int31);
25
26 #define DOS_GET_DRIVE(reg) ((reg) ? (reg) - 1 : DRIVE_GetCurrentDrive())
27
28 void CreateBPB(int drive, BYTE *data, BOOL16 limited);  /* defined in int21.c */
29
30 static void* lastvalloced = NULL;
31
32 /* Structure for real-mode callbacks */
33 typedef struct
34 {
35     DWORD edi;
36     DWORD esi;
37     DWORD ebp;
38     DWORD reserved;
39     DWORD ebx;
40     DWORD edx;
41     DWORD ecx;
42     DWORD eax;
43     WORD  fl;
44     WORD  es;
45     WORD  ds;
46     WORD  fs;
47     WORD  gs;
48     WORD  ip;
49     WORD  cs;
50     WORD  sp;
51     WORD  ss;
52 } REALMODECALL;
53
54
55
56 typedef struct tagRMCB {
57     DWORD address;
58     DWORD proc_ofs,proc_sel;
59     DWORD regs_ofs,regs_sel;
60     struct tagRMCB *next;
61 } RMCB;
62
63 static RMCB *FirstRMCB = NULL;
64
65
66 /**********************************************************************
67  *          DPMI_xalloc
68  * special virtualalloc, allocates lineary monoton growing memory.
69  * (the usual VirtualAlloc does not satisfy that restriction)
70  */
71 static LPVOID
72 DPMI_xalloc(int len) {
73         LPVOID  ret;
74         LPVOID  oldlastv = lastvalloced;
75
76         if (lastvalloced) {
77                 int     xflag = 0;
78                 ret = NULL;
79                 while (!ret) {
80                         ret=VirtualAlloc(lastvalloced,len,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE);
81                         if (!ret)
82                                 lastvalloced = (char *) lastvalloced + 0x10000;
83                         /* we failed to allocate one in the first round. 
84                          * try non-linear
85                          */
86                         if (!xflag && (lastvalloced<oldlastv)) { /* wrapped */
87                                 FIXME("failed to allocate lineary growing memory (%d bytes), using non-linear growing...\n",len);
88                                 xflag++;
89                         }
90                         /* if we even fail to allocate something in the next 
91                          * round, return NULL
92                          */
93                         if ((xflag==1) && (lastvalloced >= oldlastv))
94                                 xflag++;
95                         if ((xflag==2) && (lastvalloced < oldlastv)) {
96                                 FIXME("failed to allocate any memory of %d bytes!\n",len);
97                                 return NULL;
98                         }
99                 }
100         } else
101                  ret=VirtualAlloc(NULL,len,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE);
102         lastvalloced = (LPVOID)(((DWORD)ret+len+0xffff)&~0xffff);
103         return ret;
104 }
105
106 static void
107 DPMI_xfree(LPVOID ptr) {
108         VirtualFree(ptr,0,MEM_RELEASE);
109 }
110
111 /* FIXME: perhaps we could grow this mapped area... */
112 static LPVOID
113 DPMI_xrealloc(LPVOID ptr,int newsize) {
114         MEMORY_BASIC_INFORMATION        mbi;
115         LPVOID                          newptr;
116
117         newptr = DPMI_xalloc(newsize);
118         if (ptr) {
119                 if (!VirtualQuery(ptr,&mbi,sizeof(mbi))) {
120                         FIXME("realloc of DPMI_xallocd region %p?\n",ptr);
121                         return NULL;
122                 }
123                 if (mbi.State == MEM_FREE) {
124                         FIXME("realloc of DPMI_xallocd region %p?\n",ptr);
125                         return NULL;
126                 }
127                 /* We do not shrink allocated memory. most reallocs
128                  * only do grows anyway
129                  */
130                 if (newsize<=mbi.RegionSize)
131                         return ptr;
132                 memcpy(newptr,ptr,mbi.RegionSize);
133                 DPMI_xfree(ptr);
134         }
135         return newptr;
136 }
137 /**********************************************************************
138  *          INT_GetRealModeContext
139  */
140 static void INT_GetRealModeContext( REALMODECALL *call, CONTEXT86 *context )
141 {
142     context->Eax    = call->eax;
143     context->Ebx    = call->ebx;
144     context->Ecx    = call->ecx;
145     context->Edx    = call->edx;
146     context->Esi    = call->esi;
147     context->Edi    = call->edi;
148     context->Ebp    = call->ebp;
149     context->EFlags = call->fl | V86_FLAG;
150     context->Eip    = call->ip;
151     context->Esp    = call->sp;
152     context->SegCs  = call->cs;
153     context->SegDs  = call->ds;
154     context->SegEs  = call->es;
155     context->SegFs  = call->fs;
156     context->SegGs  = call->gs;
157     context->SegSs  = call->ss;
158 }
159
160
161 /**********************************************************************
162  *          INT_SetRealModeContext
163  */
164 static void INT_SetRealModeContext( REALMODECALL *call, CONTEXT86 *context )
165 {
166     call->eax = context->Eax;
167     call->ebx = context->Ebx;
168     call->ecx = context->Ecx;
169     call->edx = context->Edx;
170     call->esi = context->Esi;
171     call->edi = context->Edi;
172     call->ebp = context->Ebp;
173     call->fl  = LOWORD(context->EFlags);
174     call->ip  = LOWORD(context->Eip);
175     call->sp  = LOWORD(context->Esp);
176     call->cs  = context->SegCs;
177     call->ds  = context->SegDs;
178     call->es  = context->SegEs;
179     call->fs  = context->SegFs;
180     call->gs  = context->SegGs;
181     call->ss  = context->SegSs;
182 }
183
184 #ifdef __i386__
185
186 void DPMI_CallRMCB32(RMCB *rmcb, UINT16 ss, DWORD esp, UINT16*es, DWORD*edi)
187 #if 0 /* original code, which early gccs puke on */
188 {
189     int _clobber;
190     __asm__ __volatile__(
191         "pushl %%ebp\n"
192         "pushl %%ebx\n"
193         "pushl %%es\n"
194         "pushl %%ds\n"
195         "pushfl\n"
196         "mov %7,%%es\n"
197         "mov %5,%%ds\n"
198         ".byte 0x36, 0xff, 0x18\n" /* lcall *%ss:(%eax) */
199         "popl %%ds\n"
200         "mov %%es,%0\n"
201         "popl %%es\n"
202         "popl %%ebx\n"
203         "popl %%ebp\n"
204     : "=d" (*es), "=D" (*edi), "=S" (_clobber), "=a" (_clobber), "=c" (_clobber)
205     : "0" (ss), "2" (esp),
206       "4" (rmcb->regs_sel), "1" (rmcb->regs_ofs),
207       "3" (&rmcb->proc_ofs) );
208 }
209 #else /* code generated by a gcc new enough */
210 ;
211 __ASM_GLOBAL_FUNC(DPMI_CallRMCB32,
212     "pushl %ebp\n\t"
213     "movl %esp,%ebp\n\t"
214     "pushl %edi\n\t"
215     "pushl %esi\n\t"
216     "movl 0x8(%ebp),%eax\n\t"
217     "movl 0x10(%ebp),%esi\n\t"
218     "movl 0xc(%ebp),%edx\n\t"
219     "movl 0x10(%eax),%ecx\n\t"
220     "movl 0xc(%eax),%edi\n\t"
221     "addl $0x4,%eax\n\t"
222     "pushl %ebp\n\t"
223     "pushl %ebx\n\t"
224     "pushl %es\n\t"
225     "pushl %ds\n\t"
226     "pushfl\n\t"
227     "mov %cx,%es\n\t"
228     "mov %dx,%ds\n\t"
229     ".byte 0x36, 0xff, 0x18\n\t" /* lcall *%ss:(%eax) */
230     "popl %ds\n\t"
231     "mov %es,%dx\n\t"
232     "popl %es\n\t"
233     "popl %ebx\n\t"
234     "popl %ebp\n\t"
235     "movl 0x14(%ebp),%eax\n\t"
236     "movw %dx,(%eax)\n\t"
237     "movl 0x18(%ebp),%edx\n\t"
238     "movl %edi,(%edx)\n\t"
239     "popl %esi\n\t"
240     "popl %edi\n\t"
241     "leave\n\t"
242     "ret")
243 #endif
244
245 #endif /* __i386__ */
246
247 /**********************************************************************
248  *          DPMI_CallRMCBProc
249  *
250  * This routine does the hard work of calling a callback procedure.
251  */
252 static void DPMI_CallRMCBProc( CONTEXT86 *context, RMCB *rmcb, WORD flag )
253 {
254     if (IS_SELECTOR_SYSTEM( rmcb->proc_sel )) {
255         /* Wine-internal RMCB, call directly */
256         ((RMCBPROC)rmcb->proc_ofs)(context);
257     } else {
258 #ifdef __i386__
259         UINT16 ss,es;
260         DWORD esp,edi;
261
262         INT_SetRealModeContext((REALMODECALL *)PTR_SEG_OFF_TO_LIN( rmcb->regs_sel, rmcb->regs_ofs ), context);
263         ss = SELECTOR_AllocBlock( (void *)(context->SegSs<<4), 0x10000, SEGMENT_DATA, FALSE, FALSE );
264         esp = context->Esp;
265
266         FIXME("untested!\n");
267
268         /* The called proc ends with an IRET, and takes these parameters:
269          * DS:ESI = pointer to real-mode SS:SP
270          * ES:EDI = pointer to real-mode call structure
271          * It returns:
272          * ES:EDI = pointer to real-mode call structure (may be a copy)
273          * It is the proc's responsibility to change the return CS:IP in the
274          * real-mode call structure. */
275         if (flag & 1) {
276             /* 32-bit DPMI client */
277             DPMI_CallRMCB32(rmcb, ss, esp, &es, &edi);
278         } else {
279             /* 16-bit DPMI client */
280             CONTEXT86 ctx = *context;
281             ctx.SegCs = rmcb->proc_sel;
282             ctx.Eip   = rmcb->proc_ofs;
283             ctx.SegDs = ss;
284             ctx.Esi   = esp;
285             ctx.SegEs = rmcb->regs_sel;
286             ctx.Edi   = rmcb->regs_ofs;
287             /* FIXME: I'm pretty sure this isn't right - should push flags first */
288             CallTo16RegisterShort(&ctx, 0);
289             es = ctx.SegEs;
290             edi = ctx.Edi;
291         }
292         FreeSelector16(ss);
293         INT_GetRealModeContext((REALMODECALL*)PTR_SEG_OFF_TO_LIN( es, edi ), context);
294 #else
295         ERR("RMCBs only implemented for i386\n");
296 #endif
297     }
298 }
299
300
301 /**********************************************************************
302  *          DPMI_CallRMProc
303  *
304  * This routine does the hard work of calling a real mode procedure.
305  */
306 int DPMI_CallRMProc( CONTEXT86 *context, LPWORD stack, int args, int iret )
307 {
308     LPWORD stack16;
309     LPVOID addr = NULL; /* avoid gcc warning */
310     LPDOSTASK lpDosTask = MZ_Current();
311     RMCB *CurrRMCB;
312     int alloc = 0, already = 0;
313     BYTE *code;
314
315     GlobalUnlock16( GetCurrentTask() );
316
317     TRACE("EAX=%08lx EBX=%08lx ECX=%08lx EDX=%08lx\n",
318                  context->Eax, context->Ebx, context->Ecx, context->Edx );
319     TRACE("ESI=%08lx EDI=%08lx ES=%04lx DS=%04lx CS:IP=%04lx:%04x, %d WORD arguments, %s\n",
320                  context->Esi, context->Edi, context->SegEs, context->SegDs,
321                  context->SegCs, LOWORD(context->Eip), args, iret?"IRET":"FAR" );
322
323 callrmproc_again:
324
325 /* there might be some code that just jumps to RMCBs or the like,
326    in which case following the jumps here might get us to a shortcut */
327     code = CTX_SEG_OFF_TO_LIN(context, context->SegCs, context->Eip);
328     switch (*code) {
329     case 0xe9: /* JMP NEAR */
330       context->Eip += 3 + *(WORD *)(code+1);
331       /* yeah, I know these gotos don't look good... */
332       goto callrmproc_again;
333     case 0xea: /* JMP FAR */
334       context->Eip = *(WORD *)(code+1);
335       context->SegCs = *(WORD *)(code+3);
336       /* ...but since the label is there anyway... */
337       goto callrmproc_again;
338     case 0xeb: /* JMP SHORT */
339       context->Eip += 2 + *(signed char *)(code+1);
340       /* ...because of other gotos below, so... */
341       goto callrmproc_again;
342     }
343
344 /* shortcut for chaining to internal interrupt handlers */
345     if ((context->SegCs == 0xF000) && iret) {
346         return INT_RealModeInterrupt( LOWORD(context->Eip)/4, context);
347     }
348
349 /* shortcut for RMCBs */
350     CurrRMCB = FirstRMCB;
351
352     while (CurrRMCB && (HIWORD(CurrRMCB->address) != context->SegCs))
353         CurrRMCB = CurrRMCB->next;
354
355     if (!(CurrRMCB || lpDosTask)) {
356         FIXME("DPMI real-mode call using DOS VM task system, not fully tested!\n");
357         TRACE("creating VM86 task\n");
358         if (!(lpDosTask = MZ_AllocDPMITask() )) {
359             ERR("could not setup VM86 task\n");
360             return 1;
361         }
362     }
363     if (!already) {
364         if (!context->SegSs) {
365             alloc = 1; /* allocate default stack */
366             stack16 = addr = DOSMEM_GetBlock( 64, (UINT16 *)&(context->SegSs) );
367             context->Esp = 64-2;
368             stack16 += 32-1;
369             if (!addr) {
370                 ERR("could not allocate default stack\n");
371                 return 1;
372             }
373         } else {
374             stack16 = CTX_SEG_OFF_TO_LIN(context, context->SegSs, context->Esp);
375         }
376         context->Esp -= (args + (iret?1:0)) * sizeof(WORD);
377         stack16 -= args;
378         if (args) memcpy(stack16, stack, args*sizeof(WORD) );
379         /* push flags if iret */
380         if (iret) {
381             stack16--; args++;
382             *stack16 = LOWORD(context->EFlags);
383         }
384         /* push return address (return to interrupt wrapper) */
385         *(--stack16) = DOSMEM_wrap_seg;
386         *(--stack16) = 0;
387         /* adjust stack */
388         context->Esp -= 2*sizeof(WORD);
389         already = 1;
390     }
391
392     if (CurrRMCB) {
393         /* RMCB call, invoke protected-mode handler directly */
394         DPMI_CallRMCBProc(context, CurrRMCB, lpDosTask ? lpDosTask->dpmi_flag : 0);
395         /* check if we returned to where we thought we would */
396         if ((context->SegCs != DOSMEM_wrap_seg) ||
397             (LOWORD(context->Eip) != 0)) {
398             /* we need to continue at different address in real-mode space,
399                so we need to set it all up for real mode again */
400             goto callrmproc_again;
401         }
402     } else {
403         TRACE("entering real mode...\n");
404         DOSVM_Enter( context );
405         TRACE("returned from real-mode call\n");
406     }
407     if (alloc) DOSMEM_FreeBlock( addr );
408     return 0;
409 }
410
411
412 /**********************************************************************
413  *          CallRMInt
414  */
415 static void CallRMInt( CONTEXT86 *context )
416 {
417     CONTEXT86 realmode_ctx;
418     FARPROC16 rm_int = INT_GetRMHandler( BL_reg(context) );
419     REALMODECALL *call = (REALMODECALL *)PTR_SEG_OFF_TO_LIN( context->SegEs,
420                                                           DI_reg(context) );
421     INT_GetRealModeContext( call, &realmode_ctx );
422
423     /* we need to check if a real-mode program has hooked the interrupt */
424     if (HIWORD(rm_int)!=0xF000) {
425         /* yup, which means we need to switch to real mode... */
426         realmode_ctx.SegCs = HIWORD(rm_int);
427         realmode_ctx.Eip   = LOWORD(rm_int);
428         if (DPMI_CallRMProc( &realmode_ctx, NULL, 0, TRUE))
429           SET_CFLAG(context);
430     } else {
431         RESET_CFLAG(context);
432         /* use the IP we have instead of BL_reg, in case some apps
433            decide to move interrupts around for whatever reason... */
434         if (INT_RealModeInterrupt( LOWORD(rm_int)/4, &realmode_ctx ))
435           SET_CFLAG(context);
436         if (context->EFlags & 1) {
437           FIXME("%02x: EAX=%08lx EBX=%08lx ECX=%08lx EDX=%08lx\n",
438                 BL_reg(context), realmode_ctx.Eax, realmode_ctx.Ebx,
439                 realmode_ctx.Ecx, realmode_ctx.Edx);
440           FIXME("      ESI=%08lx EDI=%08lx DS=%04lx ES=%04lx\n",
441                 realmode_ctx.Esi, realmode_ctx.Edi,
442                 realmode_ctx.SegDs, realmode_ctx.SegEs );
443         }
444     }
445     INT_SetRealModeContext( call, &realmode_ctx );
446 }
447
448
449 static void CallRMProc( CONTEXT86 *context, int iret )
450 {
451     REALMODECALL *p = (REALMODECALL *)PTR_SEG_OFF_TO_LIN( context->SegEs, DI_reg(context) );
452     CONTEXT86 context16;
453
454     TRACE("RealModeCall: EAX=%08lx EBX=%08lx ECX=%08lx EDX=%08lx\n",
455         p->eax, p->ebx, p->ecx, p->edx);
456     TRACE("              ESI=%08lx EDI=%08lx ES=%04x DS=%04x CS:IP=%04x:%04x, %d WORD arguments, %s\n",
457         p->esi, p->edi, p->es, p->ds, p->cs, p->ip, CX_reg(context), iret?"IRET":"FAR" );
458
459     if (!(p->cs) && !(p->ip)) { /* remove this check
460                                    if Int21/6501 case map function
461                                    has been implemented */
462         SET_CFLAG(context);
463         return;
464     }
465     INT_GetRealModeContext(p, &context16);
466     DPMI_CallRMProc( &context16, ((LPWORD)PTR_SEG_OFF_TO_LIN(context->SegSs, LOWORD(context->Esp)))+3,
467                      CX_reg(context), iret );
468     INT_SetRealModeContext(p, &context16);
469 }
470
471
472 static RMCB *DPMI_AllocRMCB( void )
473 {
474     RMCB *NewRMCB = HeapAlloc(GetProcessHeap(), 0, sizeof(RMCB));
475     UINT16 uParagraph;
476
477     if (NewRMCB)
478     {
479         LPVOID RMCBmem = DOSMEM_GetBlock(4, &uParagraph);
480         LPBYTE p = RMCBmem;
481
482         *p++ = 0xcd; /* RMCB: */
483         *p++ = 0x31; /* int $0x31 */
484 /* it is the called procedure's task to change the return CS:EIP
485    the DPMI 0.9 spec states that if it doesn't, it will be called again */
486         *p++ = 0xeb;
487         *p++ = 0xfc; /* jmp RMCB */
488         NewRMCB->address = MAKELONG(0, uParagraph);
489         NewRMCB->next = FirstRMCB;
490         FirstRMCB = NewRMCB;
491     }
492     return NewRMCB;
493 }
494
495
496 static void AllocRMCB( CONTEXT86 *context )
497 {
498     RMCB *NewRMCB = DPMI_AllocRMCB();
499
500     TRACE("Function to call: %04x:%04x\n", (WORD)context->SegDs, SI_reg(context) );
501
502     if (NewRMCB)
503     {
504         /* FIXME: if 32-bit DPMI client, use ESI and EDI */
505         NewRMCB->proc_ofs = LOWORD(context->Esi);
506         NewRMCB->proc_sel = context->SegDs;
507         NewRMCB->regs_ofs = LOWORD(context->Edi);
508         NewRMCB->regs_sel = context->SegEs;
509         SET_LOWORD( context->Ecx, HIWORD(NewRMCB->address) );
510         SET_LOWORD( context->Edx, LOWORD(NewRMCB->address) );
511     }
512     else
513     {
514         SET_LOWORD( context->Eax, 0x8015 ); /* callback unavailable */
515         SET_CFLAG(context);
516     }
517 }
518
519
520 FARPROC16 WINAPI DPMI_AllocInternalRMCB( RMCBPROC proc )
521 {
522     RMCB *NewRMCB = DPMI_AllocRMCB();
523
524     if (NewRMCB) {
525         NewRMCB->proc_ofs = (DWORD)proc;
526         NewRMCB->proc_sel = 0;
527         NewRMCB->regs_ofs = 0;
528         NewRMCB->regs_sel = 0;
529         return (FARPROC16)(NewRMCB->address);
530     }
531     return NULL;
532 }
533
534
535 static int DPMI_FreeRMCB( DWORD address )
536 {
537     RMCB *CurrRMCB = FirstRMCB;
538     RMCB *PrevRMCB = NULL;
539
540     while (CurrRMCB && (CurrRMCB->address != address))
541     {
542         PrevRMCB = CurrRMCB;
543         CurrRMCB = CurrRMCB->next;
544     }
545     if (CurrRMCB)
546     {
547         if (PrevRMCB)
548         PrevRMCB->next = CurrRMCB->next;
549             else
550         FirstRMCB = CurrRMCB->next;
551         DOSMEM_FreeBlock(DOSMEM_MapRealToLinear(CurrRMCB->address));
552         HeapFree(GetProcessHeap(), 0, CurrRMCB);
553         return 0;
554     }
555     return 1;
556 }
557
558
559 static void FreeRMCB( CONTEXT86 *context )
560 {
561     FIXME("callback address: %04x:%04x\n",
562           CX_reg(context), DX_reg(context));
563
564     if (DPMI_FreeRMCB(MAKELONG(DX_reg(context), CX_reg(context)))) {
565         SET_LOWORD( context->Eax, 0x8024 ); /* invalid callback address */
566         SET_CFLAG(context);
567     }
568 }
569
570
571 void WINAPI DPMI_FreeInternalRMCB( FARPROC16 proc )
572 {
573     DPMI_FreeRMCB( (DWORD)proc );
574 }
575
576
577 /* (see dosmem.c, function DOSMEM_InitDPMI) */
578
579 static void StartPM( CONTEXT86 *context, LPDOSTASK lpDosTask )
580 {
581     UINT16 cs, ss, ds, es;
582     CONTEXT86 pm_ctx;
583     DWORD psp_ofs = (DWORD)(lpDosTask->psp_seg<<4);
584     PDB16 *psp = (PDB16 *)psp_ofs;
585     HANDLE16 env_seg = psp->environment;
586     int is32;
587
588     RESET_CFLAG(context);
589     lpDosTask->dpmi_flag = AX_reg(context);
590     is32 = lpDosTask->dpmi_flag & 1;
591 /* our mode switch wrapper have placed the desired CS into DX */
592     cs = SELECTOR_AllocBlock( (void *)(DX_reg(context)<<4), 0x10000, SEGMENT_CODE, FALSE, FALSE );
593 /* due to a flaw in some CPUs (at least mine), it is best to mark stack segments as 32-bit if they
594    can be used in 32-bit code. Otherwise, these CPUs may not set the high word of esp during a
595    ring transition (from kernel code) to the 16-bit stack, and this causes trouble if executing
596    32-bit code using this stack. */
597     ss = SELECTOR_AllocBlock( (void *)(context->SegSs<<4), 0x10000, SEGMENT_DATA, is32, FALSE );
598 /* do the same for the data segments, just in case */
599     if (context->SegDs == context->SegSs) ds = ss;
600     else ds = SELECTOR_AllocBlock( (void *)(context->SegDs<<4), 0x10000, SEGMENT_DATA, is32, FALSE );
601     es = SELECTOR_AllocBlock( psp, 0x100, SEGMENT_DATA, is32, FALSE );
602 /* convert environment pointer, as the spec says, but we're a bit lazy about the size here... */
603     psp->environment = SELECTOR_AllocBlock( (void *)(env_seg<<4),
604                                             0x10000, SEGMENT_DATA, FALSE, FALSE );
605
606     pm_ctx = *context;
607     pm_ctx.SegCs = DOSMEM_dpmi_sel;
608 /* our mode switch wrapper expects the new CS in DX, and the new SS in AX */
609     pm_ctx.Eax   = ss;
610     pm_ctx.Edx   = cs;
611     pm_ctx.SegDs = ds;
612     pm_ctx.SegEs = es;
613     pm_ctx.SegFs = 0;
614     pm_ctx.SegGs = 0;
615
616     TRACE("DOS program is now entering protected mode\n");
617     CallTo16RegisterShort(&pm_ctx, 0);
618
619     /* in the current state of affairs, we won't ever actually return here... */
620     /* we should have int21/ah=4c do it someday, though... */
621
622     FreeSelector16(psp->environment);
623     psp->environment = env_seg;
624     FreeSelector16(es);
625     if (ds != ss) FreeSelector16(ds);
626     FreeSelector16(ss);
627     FreeSelector16(cs);
628 }
629
630 /* DPMI Raw Mode Switch handler */
631
632 #if 0
633 void WINAPI DPMI_RawModeSwitch( SIGCONTEXT *context )
634 {
635   LPDOSTASK lpDosTask = MZ_Current();
636   CONTEXT86 rm_ctx;
637   int ret;
638
639   if (!lpDosTask) {
640     /* we could probably start a DPMI-only dosmod task here, but I doubt
641        anything other than real DOS apps want to call raw mode switch */
642     ERR("attempting raw mode switch without DOS task!\n");
643     ExitProcess(1);
644   }
645   /* initialize real-mode context as per spec */
646   memset(&rm_ctx, 0, sizeof(rm_ctx));
647   rm_ctx.SegDs  = AX_sig(context);
648   rm_ctx.SegEs  = CX_sig(context);
649   rm_ctx.SegSs  = DX_sig(context);
650   rm_ctx.Esp    = EBX_sig(context);
651   rm_ctx.SegCs  = SI_sig(context);
652   rm_ctx.Eip    = EDI_sig(context);
653   rm_ctx.Ebp    = EBP_sig(context);
654   rm_ctx.SegFs  = 0;
655   rm_ctx.SegGs  = 0;
656   rm_ctx.EFlags = EFL_sig(context); /* at least we need the IF flag */
657
658   /* enter real mode again */
659   TRACE("re-entering real mode at %04lx:%04lx\n",rm_ctx.SegCs,rm_ctx.Eip);
660   ret = DOSVM_Enter( &rm_ctx );
661   /* when the real-mode stuff call its mode switch address,
662      DOSVM_Enter will return and we will continue here */
663
664   if (ret<0) {
665     /* if the sync was lost, there's no way to recover */
666     ExitProcess(1);
667   }
668
669   /* alter protected-mode context as per spec */
670   DS_sig(context)  = LOWORD(rm_ctx.Eax);
671   ES_sig(context)  = LOWORD(rm_ctx.Ecx);
672   SS_sig(context)  = LOWORD(rm_ctx.Edx);
673   ESP_sig(context) = rm_ctx.Ebx;
674   CS_sig(context)  = LOWORD(rm_ctx.Esi);
675   EIP_sig(context) = rm_ctx.Edi;
676   EBP_sig(context) = rm_ctx.Ebp;
677   FS_sig(context) = 0;
678   GS_sig(context) = 0;
679
680   /* Return to new address and hope that we didn't mess up */
681   TRACE("re-entering protected mode at %04x:%08lx\n",
682         CS_sig(context), EIP_sig(context));
683 }
684 #endif
685
686
687 /**********************************************************************
688  *          INT_Int31Handler
689  *
690  * Handler for int 31h (DPMI).
691  */
692
693 void WINAPI INT_Int31Handler( CONTEXT86 *context )
694 {
695     /*
696      * Note: For Win32s processes, the whole linear address space is
697      *       shifted by 0x10000 relative to the OS linear address space.
698      *       See the comment in msdos/vxd.c.
699      */
700     DWORD offset = W32S_APPLICATION() ? W32S_OFFSET : 0;
701
702     DWORD dw;
703     BYTE *ptr;
704
705     LPDOSTASK lpDosTask = MZ_Current();
706
707     if (ISV86(context) && lpDosTask) {
708         /* Called from real mode, check if it's our wrapper */
709         TRACE("called from real mode\n");
710         if (context->SegCs==DOSMEM_dpmi_seg) {
711             /* This is the protected mode switch */
712             StartPM(context,lpDosTask);
713             return;
714         } else
715         if (context->SegCs==DOSMEM_xms_seg) {
716             /* This is the XMS driver entry point */
717             XMS_Handler(context);
718             return;
719         } else
720         {
721             /* Check for RMCB */
722             RMCB *CurrRMCB = FirstRMCB;
723             
724             while (CurrRMCB && (HIWORD(CurrRMCB->address) != context->SegCs))
725                 CurrRMCB = CurrRMCB->next;
726             
727             if (CurrRMCB) {
728                 /* RMCB call, propagate to protected-mode handler */
729                 DPMI_CallRMCBProc(context, CurrRMCB, lpDosTask->dpmi_flag);
730                 return;
731             }
732         }
733     }
734
735     RESET_CFLAG(context);
736     switch(AX_reg(context))
737     {
738     case 0x0000:  /* Allocate LDT descriptors */
739         TRACE("allocate LDT descriptors (%d)\n",CX_reg(context));
740         if (!(context->Eax = AllocSelectorArray16( CX_reg(context) )))
741         {
742             TRACE("failed\n");
743             context->Eax = 0x8011;  /* descriptor unavailable */
744             SET_CFLAG(context);
745         }
746         TRACE("success, array starts at 0x%04x\n",AX_reg(context));
747         break;
748
749     case 0x0001:  /* Free LDT descriptor */
750         TRACE("free LDT descriptor (0x%04x)\n",BX_reg(context));
751         if (FreeSelector16( BX_reg(context) ))
752         {
753             context->Eax = 0x8022;  /* invalid selector */
754             SET_CFLAG(context);
755         }
756         else
757         {
758             /* If a segment register contains the selector being freed, */
759             /* set it to zero. */
760             if (!((context->SegDs^BX_reg(context)) & ~3)) context->SegDs = 0;
761             if (!((context->SegEs^BX_reg(context)) & ~3)) context->SegEs = 0;
762             if (!((context->SegFs^BX_reg(context)) & ~3)) context->SegFs = 0;
763             if (!((context->SegGs^BX_reg(context)) & ~3)) context->SegGs = 0;
764         }
765         break;
766
767     case 0x0002:  /* Real mode segment to descriptor */
768         TRACE("real mode segment to descriptor (0x%04x)\n",BX_reg(context));
769         {
770             WORD entryPoint = 0;  /* KERNEL entry point for descriptor */
771             switch(BX_reg(context))
772             {
773             case 0x0000: entryPoint = 183; break;  /* __0000H */
774             case 0x0040: entryPoint = 193; break;  /* __0040H */
775             case 0xa000: entryPoint = 174; break;  /* __A000H */
776             case 0xb000: entryPoint = 181; break;  /* __B000H */
777             case 0xb800: entryPoint = 182; break;  /* __B800H */
778             case 0xc000: entryPoint = 195; break;  /* __C000H */
779             case 0xd000: entryPoint = 179; break;  /* __D000H */
780             case 0xe000: entryPoint = 190; break;  /* __E000H */
781             case 0xf000: entryPoint = 194; break;  /* __F000H */
782             default:
783                 context->Eax = DOSMEM_AllocSelector(BX_reg(context));
784                 break;
785             }
786             if (entryPoint) 
787                 context->Eax = LOWORD(NE_GetEntryPoint( GetModuleHandle16( "KERNEL" ),
788                                                             entryPoint ));
789         }
790         break;
791
792     case 0x0003:  /* Get next selector increment */
793         TRACE("get selector increment (__AHINCR)\n");
794         context->Eax = __AHINCR;
795         break;
796
797     case 0x0004:  /* Lock selector (not supported) */
798         FIXME("lock selector not supported\n");
799         context->Eax = 0;  /* FIXME: is this a correct return value? */
800         break;
801
802     case 0x0005:  /* Unlock selector (not supported) */
803         FIXME("unlock selector not supported\n");
804         context->Eax = 0;  /* FIXME: is this a correct return value? */
805         break;
806
807     case 0x0006:  /* Get selector base address */
808         TRACE("get selector base address (0x%04x)\n",BX_reg(context));
809         if (!(dw = GetSelectorBase( BX_reg(context) )))
810         {
811             context->Eax = 0x8022;  /* invalid selector */
812             SET_CFLAG(context);
813         }
814         else
815         {
816             CX_reg(context) = HIWORD(W32S_WINE2APP(dw, offset));
817             DX_reg(context) = LOWORD(W32S_WINE2APP(dw, offset));
818         }
819         break;
820
821     case 0x0007:  /* Set selector base address */
822         TRACE("set selector base address (0x%04x,0x%08lx)\n",
823                      BX_reg(context),
824                      W32S_APP2WINE(MAKELONG(DX_reg(context),CX_reg(context)), offset));
825         dw = W32S_APP2WINE(MAKELONG(DX_reg(context), CX_reg(context)), offset);
826         if (dw < 0x10000)
827             /* app wants to access lower 64K of DOS memory, map it in now */
828             DOSMEM_Init(TRUE);
829         SetSelectorBase(BX_reg(context), dw);
830         break;
831
832     case 0x0008:  /* Set selector limit */
833         TRACE("set selector limit (0x%04x,0x%08lx)\n",BX_reg(context),MAKELONG(DX_reg(context),CX_reg(context)));
834         dw = MAKELONG( DX_reg(context), CX_reg(context) );
835         SetSelectorLimit16( BX_reg(context), dw );
836         break;
837
838     case 0x0009:  /* Set selector access rights */
839         TRACE("set selector access rights(0x%04x,0x%04x)\n",BX_reg(context),CX_reg(context));
840         SelectorAccessRights16( BX_reg(context), 1, CX_reg(context) );
841         break;
842
843     case 0x000a:  /* Allocate selector alias */
844         TRACE("allocate selector alias (0x%04x)\n",BX_reg(context));
845         if (!(AX_reg(context) = AllocCStoDSAlias16( BX_reg(context) )))
846         {
847             AX_reg(context) = 0x8011;  /* descriptor unavailable */
848             SET_CFLAG(context);
849         }
850         break;
851
852     case 0x000b:  /* Get descriptor */
853         TRACE("get descriptor (0x%04x)\n",BX_reg(context));
854         {
855             ldt_entry entry;
856             LDT_GetEntry( SELECTOR_TO_ENTRY( BX_reg(context) ), &entry );
857             entry.base = W32S_WINE2APP(entry.base, offset);
858
859             /* FIXME: should use ES:EDI for 32-bit clients */
860             LDT_EntryToBytes( PTR_SEG_OFF_TO_LIN( context->SegEs,
861                                                   DI_reg(context) ), &entry );
862         }
863         break;
864
865     case 0x000c:  /* Set descriptor */
866         TRACE("set descriptor (0x%04x)\n",BX_reg(context));
867         {
868             ldt_entry entry;
869             LDT_BytesToEntry( PTR_SEG_OFF_TO_LIN( context->SegEs,
870                                                   DI_reg(context) ), &entry );
871             entry.base = W32S_APP2WINE(entry.base, offset);
872             LDT_SetEntry( SELECTOR_TO_ENTRY( BX_reg(context) ), &entry );
873         }
874         break;
875
876     case 0x000d:  /* Allocate specific LDT descriptor */
877         FIXME("allocate descriptor (0x%04x), stub!\n",BX_reg(context));
878         AX_reg(context) = 0x8011; /* descriptor unavailable */
879         SET_CFLAG(context);
880         break;
881     case 0x0100:  /* Allocate DOS memory block */
882         TRACE("allocate DOS memory block (0x%x paragraphs)\n",BX_reg(context));
883         dw = GlobalDOSAlloc16((DWORD)BX_reg(context)<<4);
884         if (dw) {
885             AX_reg(context) = HIWORD(dw);
886             DX_reg(context) = LOWORD(dw);
887         } else {
888             AX_reg(context) = 0x0008; /* insufficient memory */
889             BX_reg(context) = DOSMEM_Available()>>4;
890             SET_CFLAG(context);
891         }
892         break;
893     case 0x0101:  /* Free DOS memory block */
894         TRACE("free DOS memory block (0x%04x)\n",DX_reg(context));
895         dw = GlobalDOSFree16(DX_reg(context));
896         if (!dw) {
897             AX_reg(context) = 0x0009; /* memory block address invalid */
898             SET_CFLAG(context);
899         }
900         break;
901     case 0x0200: /* get real mode interrupt vector */
902         FIXME("get realmode interupt vector(0x%02x) unimplemented.\n",
903               BL_reg(context));
904         SET_CFLAG(context);
905         break;
906     case 0x0201: /* set real mode interrupt vector */
907         FIXME("set realmode interupt vector(0x%02x,0x%04x:0x%04x) unimplemented\n", BL_reg(context),CX_reg(context),DX_reg(context));
908         SET_CFLAG(context);
909         break;
910     case 0x0204:  /* Get protected mode interrupt vector */
911         TRACE("get protected mode interrupt handler (0x%02x), stub!\n",BL_reg(context));
912         dw = (DWORD)INT_GetPMHandler( BL_reg(context) );
913         CX_reg(context) = HIWORD(dw);
914         DX_reg(context) = LOWORD(dw);
915         break;
916
917     case 0x0205:  /* Set protected mode interrupt vector */
918         TRACE("set protected mode interrupt handler (0x%02x,%p), stub!\n",
919             BL_reg(context),PTR_SEG_OFF_TO_LIN(CX_reg(context),DX_reg(context)));
920         INT_SetPMHandler( BL_reg(context),
921                           (FARPROC16)PTR_SEG_OFF_TO_SEGPTR( CX_reg(context),
922                                                             DX_reg(context) ));
923         break;
924
925     case 0x0300:  /* Simulate real mode interrupt */
926         CallRMInt( context );
927         break;
928
929     case 0x0301:  /* Call real mode procedure with far return */
930         CallRMProc( context, FALSE );
931         break;
932
933     case 0x0302:  /* Call real mode procedure with interrupt return */
934         CallRMProc( context, TRUE );
935         break;
936
937     case 0x0303:  /* Allocate Real Mode Callback Address */
938         AllocRMCB( context );
939         break;
940
941     case 0x0304:  /* Free Real Mode Callback Address */
942         FreeRMCB( context );
943         break;
944
945     case 0x0305:  /* Get State Save/Restore Addresses */
946         TRACE("get state save/restore addresses\n");
947         /* we probably won't need this kind of state saving */
948         AX_reg(context) = 0;
949         /* real mode: just point to the lret */
950         BX_reg(context) = DOSMEM_wrap_seg;
951         context->Ecx = 2;
952         /* protected mode: don't have any handler yet... */
953         FIXME("no protected-mode dummy state save/restore handler yet\n");
954         SI_reg(context) = 0;
955         context->Edi = 0;
956         break;
957
958     case 0x0306:  /* Get Raw Mode Switch Addresses */
959         TRACE("get raw mode switch addresses\n");
960         /* real mode, point to standard DPMI return wrapper */
961         BX_reg(context) = DOSMEM_wrap_seg;
962         context->Ecx = 0;
963         /* protected mode, point to DPMI call wrapper */
964         SI_reg(context) = DOSMEM_dpmi_sel;
965         context->Edi = 8; /* offset of the INT 0x31 call */
966         break;
967     case 0x0400:  /* Get DPMI version */
968         TRACE("get DPMI version\n");
969         {
970             SYSTEM_INFO si;
971
972             GetSystemInfo(&si);
973             AX_reg(context) = 0x005a;  /* DPMI version 0.90 */
974             BX_reg(context) = 0x0005;  /* Flags: 32-bit, virtual memory */
975             CL_reg(context) = si.wProcessorLevel;
976             DX_reg(context) = 0x0102;  /* Master/slave interrupt controller base*/
977             break;
978         }
979     case 0x0500:  /* Get free memory information */
980         TRACE("get free memory information\n");
981         {
982             MEMMANINFO mmi;
983
984             mmi.dwSize = sizeof(mmi);
985             MemManInfo16(&mmi);
986             ptr = (BYTE *)PTR_SEG_OFF_TO_LIN(context->SegEs,DI_reg(context));
987             /* the layout is just the same as MEMMANINFO, but without
988              * the dwSize entry.
989              */
990             memcpy(ptr,((char*)&mmi)+4,sizeof(mmi)-4);
991             break;
992         }
993     case 0x0501:  /* Allocate memory block */
994         TRACE("allocate memory block (%ld)\n",MAKELONG(CX_reg(context),BX_reg(context)));
995         if (!(ptr = (BYTE *)DPMI_xalloc(MAKELONG(CX_reg(context), BX_reg(context)))))
996         {
997             AX_reg(context) = 0x8012;  /* linear memory not available */
998             SET_CFLAG(context);
999         } else {
1000             BX_reg(context) = SI_reg(context) = HIWORD(W32S_WINE2APP(ptr, offset));
1001             CX_reg(context) = DI_reg(context) = LOWORD(W32S_WINE2APP(ptr, offset));
1002         }
1003         break;
1004
1005     case 0x0502:  /* Free memory block */
1006         TRACE("free memory block (0x%08lx)\n",
1007                      W32S_APP2WINE(MAKELONG(DI_reg(context),SI_reg(context)), offset));
1008         DPMI_xfree( (void *)W32S_APP2WINE(MAKELONG(DI_reg(context), 
1009                                                SI_reg(context)), offset) );
1010         break;
1011
1012     case 0x0503:  /* Resize memory block */
1013         TRACE("resize memory block (0x%08lx,%ld)\n",
1014                      W32S_APP2WINE(MAKELONG(DI_reg(context),SI_reg(context)), offset),
1015                      MAKELONG(CX_reg(context),BX_reg(context)));
1016         if (!(ptr = (BYTE *)DPMI_xrealloc(
1017                 (void *)W32S_APP2WINE(MAKELONG(DI_reg(context),SI_reg(context)), offset),
1018                 MAKELONG(CX_reg(context),BX_reg(context)))))
1019         {
1020             AX_reg(context) = 0x8012;  /* linear memory not available */
1021             SET_CFLAG(context);
1022         } else {
1023             BX_reg(context) = SI_reg(context) = HIWORD(W32S_WINE2APP(ptr, offset));
1024             CX_reg(context) = DI_reg(context) = LOWORD(W32S_WINE2APP(ptr, offset));
1025         }
1026         break;
1027
1028     case 0x0507:  /* Modify page attributes */
1029         FIXME("modify page attributes unimplemented\n");
1030         break;  /* Just ignore it */
1031
1032     case 0x0600:  /* Lock linear region */
1033         FIXME("lock linear region unimplemented\n");
1034         break;  /* Just ignore it */
1035
1036     case 0x0601:  /* Unlock linear region */
1037         FIXME("unlock linear region unimplemented\n");
1038         break;  /* Just ignore it */
1039
1040     case 0x0602:  /* Unlock real-mode region */
1041         FIXME("unlock realmode region unimplemented\n");
1042         break;  /* Just ignore it */
1043
1044     case 0x0603:  /* Lock real-mode region */
1045         FIXME("lock realmode region unimplemented\n");
1046         break;  /* Just ignore it */
1047
1048     case 0x0604:  /* Get page size */
1049         TRACE("get pagesize\n");
1050         BX_reg(context) = 0;
1051         CX_reg(context) = VIRTUAL_GetPageSize();
1052         break;
1053
1054     case 0x0702:  /* Mark page as demand-paging candidate */
1055         FIXME("mark page as demand-paging candidate\n");
1056         break;  /* Just ignore it */
1057
1058     case 0x0703:  /* Discard page contents */
1059         FIXME("discard page contents\n");
1060         break;  /* Just ignore it */
1061
1062      case 0x0800:  /* Physical address mapping */
1063         FIXME("map real to linear (0x%08lx)\n",MAKELONG(CX_reg(context),BX_reg(context)));
1064          if(!(ptr=DOSMEM_MapRealToLinear(MAKELONG(CX_reg(context),BX_reg(context)))))
1065          {
1066              AX_reg(context) = 0x8021; 
1067              SET_CFLAG(context);
1068          }
1069          else
1070          {
1071              BX_reg(context) = HIWORD(W32S_WINE2APP(ptr, offset));
1072              CX_reg(context) = LOWORD(W32S_WINE2APP(ptr, offset));
1073              RESET_CFLAG(context);
1074          }
1075          break;
1076
1077     default:
1078         INT_BARF( context, 0x31 );
1079         AX_reg(context) = 0x8001;  /* unsupported function */
1080         SET_CFLAG(context);
1081         break;
1082     }
1083
1084 }