Implemented mode setting things as well as VESA additions and other
[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 "wintypes.h"
10 #include "wine/winbase16.h"
11 #include "ldt.h"
12 #include "global.h"
13 #include "module.h"
14 #include "miscemu.h"
15 #include "msdos.h"
16 #include "task.h"
17 #include "thread.h"     /* for !MZ_SUPPORTED */
18 #include "stackframe.h" /* for !MZ_SUPPORTED */
19 #include "toolhelp.h"
20 #include "selectors.h"
21 #include "process.h"
22 #include "callback.h"
23 #include "debug.h"
24
25 #define DOS_GET_DRIVE(reg) ((reg) ? (reg) - 1 : DRIVE_GetCurrentDrive())
26
27 void CreateBPB(int drive, BYTE *data, BOOL16 limited);  /* defined in int21.c */
28
29 static void* lastvalloced = NULL;
30
31 /* Structure for real-mode callbacks */
32 typedef struct
33 {
34     DWORD edi;
35     DWORD esi;
36     DWORD ebp;
37     DWORD reserved;
38     DWORD ebx;
39     DWORD edx;
40     DWORD ecx;
41     DWORD eax;
42     WORD  fl;
43     WORD  es;
44     WORD  ds;
45     WORD  fs;
46     WORD  gs;
47     WORD  ip;
48     WORD  cs;
49     WORD  sp;
50     WORD  ss;
51 } REALMODECALL;
52
53
54
55 typedef struct tagRMCB {
56     DWORD address;
57     DWORD proc_ofs,proc_sel;
58     DWORD regs_ofs,regs_sel;
59     struct tagRMCB *next;
60 } RMCB;
61
62 static RMCB *FirstRMCB = NULL;
63
64 UINT16 DPMI_wrap_seg;
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+=0x10000;
83                         /* we failed to allocate one in the first round. 
84                          * try non-linear
85                          */
86                         if (!xflag && (lastvalloced<oldlastv)) { /* wrapped */
87                                 FIXME(int31,"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(int31,"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(int31,"realloc of DPMI_xallocd region %p?\n",ptr);
121                         return NULL;
122                 }
123                 if (mbi.State == MEM_FREE) {
124                         FIXME(int31,"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, CONTEXT *context )
141 {
142     EAX_reg(context) = call->eax;
143     EBX_reg(context) = call->ebx;
144     ECX_reg(context) = call->ecx;
145     EDX_reg(context) = call->edx;
146     ESI_reg(context) = call->esi;
147     EDI_reg(context) = call->edi;
148     EBP_reg(context) = call->ebp;
149     EFL_reg(context) = call->fl | V86_FLAG;
150     EIP_reg(context) = call->ip;
151     ESP_reg(context) = call->sp;
152     CS_reg(context)  = call->cs;
153     DS_reg(context)  = call->ds;
154     ES_reg(context)  = call->es;
155     FS_reg(context)  = call->fs;
156     GS_reg(context)  = call->gs;
157     SS_reg(context)  = call->ss;
158     (char*)V86BASE(context) = DOSMEM_MemoryBase(0);
159 }
160
161
162 /**********************************************************************
163  *          INT_SetRealModeContext
164  */
165 static void INT_SetRealModeContext( REALMODECALL *call, CONTEXT *context )
166 {
167     call->eax = EAX_reg(context);
168     call->ebx = EBX_reg(context);
169     call->ecx = ECX_reg(context);
170     call->edx = EDX_reg(context);
171     call->esi = ESI_reg(context);
172     call->edi = EDI_reg(context);
173     call->ebp = EBP_reg(context);
174     call->fl  = FL_reg(context);
175     call->ip  = IP_reg(context);
176     call->sp  = SP_reg(context);
177     call->cs  = CS_reg(context);
178     call->ds  = DS_reg(context);
179     call->es  = ES_reg(context);
180     call->fs  = FS_reg(context);
181     call->gs  = GS_reg(context);
182     call->ss  = SS_reg(context);
183 }
184
185
186 /**********************************************************************
187  *          DPMI_CallRMCBProc
188  *
189  * This routine does the hard work of calling a callback procedure.
190  */
191 static void DPMI_CallRMCBProc( CONTEXT *context, RMCB *rmcb, WORD flag )
192 {
193     if (IS_SELECTOR_SYSTEM( rmcb->proc_sel )) {
194         /* Wine-internal RMCB, call directly */
195         ((RMCBPROC)rmcb->proc_ofs)(context);
196     } else {
197 #ifdef __i386__
198         UINT16 ss,es;
199         DWORD edi;
200
201         INT_SetRealModeContext((REALMODECALL *)PTR_SEG_OFF_TO_LIN( rmcb->regs_sel, rmcb->regs_ofs ), context);
202         ss = SELECTOR_AllocBlock( DOSMEM_MemoryBase(0) + (DWORD)(SS_reg(context)<<4), 0x10000, SEGMENT_DATA, FALSE, FALSE );
203
204         FIXME(int31,"untested!\n");
205
206         /* The called proc ends with an IRET, and takes these parameters:
207          * DS:ESI = pointer to real-mode SS:SP
208          * ES:EDI = pointer to real-mode call structure
209          * It returns:
210          * ES:EDI = pointer to real-mode call structure (may be a copy)
211          * It is the proc's responsibility to change the return CS:IP in the
212          * real-mode call structure. */
213         if (flag & 1) {
214             int _clobber;
215             /* 32-bit DPMI client */
216             __asm__ __volatile__("
217                  pushl %%es
218                  pushl %%ds
219                  pushfl
220                  movl %5,%%es
221                  movl %4,%%ds
222                  lcall %3
223                  popl %%ds
224                  movl %%es,%0
225                  popl %%es
226              "
227              : "=g" (es), "=D" (edi), "=S" (_clobber)
228              : "m" (rmcb->proc_ofs),
229                "g" (ss), "g" (rmcb->regs_sel),
230                "S" (ESP_reg(context)), "1" (rmcb->regs_ofs)
231              : "ecx", "edx", "ebp" );
232         } else {
233             /* 16-bit DPMI client */
234             CONTEXT ctx = *context;
235             CS_reg(&ctx) = rmcb->proc_sel;
236             EIP_reg(&ctx) = rmcb->proc_ofs;
237             DS_reg(&ctx) = ss;
238             ESI_reg(&ctx) = ESP_reg(context);
239             ES_reg(&ctx) = rmcb->regs_sel;
240             EDI_reg(&ctx) = rmcb->regs_ofs;
241             Callbacks->CallRegisterShortProc(&ctx, 2);
242             es = ES_reg(&ctx);
243             edi = EDI_reg(&ctx);
244         }
245         UnMapLS(PTR_SEG_OFF_TO_SEGPTR(ss,0));
246         INT_GetRealModeContext((REALMODECALL*)PTR_SEG_OFF_TO_LIN( es, edi ), context);
247 #else
248         ERR(int31,"RMCBs only implemented for i386\n");
249 #endif
250     }
251 }
252
253
254 /**********************************************************************
255  *          DPMI_CallRMProc
256  *
257  * This routine does the hard work of calling a real mode procedure.
258  */
259 int DPMI_CallRMProc( CONTEXT *context, LPWORD stack, int args, int iret )
260 {
261     LPWORD stack16;
262 #ifndef MZ_SUPPORTED
263     THDB *thdb = THREAD_Current();
264     WORD sel;
265     SEGPTR seg_addr;
266 #endif /* !MZ_SUPPORTED */
267     LPVOID addr = NULL; /* avoid gcc warning */
268     TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
269     NE_MODULE *pModule = pTask ? NE_GetPtr( pTask->hModule ) : NULL;
270     RMCB *CurrRMCB;
271     int alloc = 0, already = 0;
272
273     GlobalUnlock16( GetCurrentTask() );
274
275     TRACE(int31, "EAX=%08lx EBX=%08lx ECX=%08lx EDX=%08lx\n",
276                  EAX_reg(context), EBX_reg(context), ECX_reg(context), EDX_reg(context) );
277     TRACE(int31, "ESI=%08lx EDI=%08lx ES=%04lx DS=%04lx CS:IP=%04lx:%04x, %d WORD arguments, %s\n",
278                  ESI_reg(context), EDI_reg(context), ES_reg(context), DS_reg(context),
279                  CS_reg(context), IP_reg(context), args, iret?"IRET":"FAR" );
280
281 callrmproc_again:
282
283 /* shortcut for chaining to internal interrupt handlers */
284     if ((CS_reg(context) == 0xF000) && iret) {
285         return INT_RealModeInterrupt( IP_reg(context)/4, context);
286     }
287
288 /* shortcut for RMCBs */
289     CurrRMCB = FirstRMCB;
290
291     while (CurrRMCB && (HIWORD(CurrRMCB->address) != CS_reg(context)))
292         CurrRMCB = CurrRMCB->next;
293
294 #ifdef MZ_SUPPORTED
295     if (!(CurrRMCB || pModule->lpDosTask)) {
296         FIXME(int31,"DPMI real-mode call using DOS VM task system, not fully tested!\n");
297         TRACE(int31,"creating VM86 task\n");
298         if (!MZ_InitTask( MZ_AllocDPMITask( pModule->self ) )) {
299             ERR(int31,"could not setup VM86 task\n");
300             return 1;
301         }
302     }
303     if (!already) {
304         if (!SS_reg(context)) {
305             alloc = 1; /* allocate default stack */
306             stack16 = addr = DOSMEM_GetBlock( pModule->self, 64, (UINT16 *)&(SS_reg(context)) );
307             SP_reg(context) = 64-2;
308             stack16 += 32-1;
309             if (!addr) {
310                 ERR(int31,"could not allocate default stack\n");
311                 return 1;
312             }
313         } else {
314             stack16 = CTX_SEG_OFF_TO_LIN(context, SS_reg(context), ESP_reg(context));
315         }
316         SP_reg(context) -= (args + (iret?1:0)) * sizeof(WORD);
317 #else
318     if (!already) {
319         stack16 = THREAD_STACK16(thdb);
320 #endif
321         stack16 -= args;
322         if (args) memcpy(stack16, stack, args*sizeof(WORD) );
323         /* push flags if iret */
324         if (iret) {
325             stack16--; args++;
326             *stack16 = FL_reg(context);
327         }
328 #ifdef MZ_SUPPORTED
329         /* push return address (return to interrupt wrapper) */
330         *(--stack16) = DPMI_wrap_seg;
331         *(--stack16) = 0;
332         /* adjust stack */
333         SP_reg(context) -= 2*sizeof(WORD);
334 #endif
335         already = 1;
336     }
337
338     if (CurrRMCB) {
339         /* RMCB call, invoke protected-mode handler directly */
340         DPMI_CallRMCBProc(context, CurrRMCB, pModule->lpDosTask?pModule->lpDosTask->dpmi_flag:0);
341         /* check if we returned to where we thought we would */
342         if ((CS_reg(context) != DPMI_wrap_seg) ||
343             (IP_reg(context) != 0)) {
344             /* we need to continue at different address in real-mode space,
345                so we need to set it all up for real mode again */
346             goto callrmproc_again;
347         }
348     } else {
349 #ifdef MZ_SUPPORTED
350 #if 0 /* this was probably unnecessary */
351         /* push call address */
352         *(--stack16) = CS_reg(context);
353         *(--stack16) = IP_reg(context);
354         /* adjust stack */
355         SP_reg(context) -= 2*sizeof(WORD);
356         /* set initial CS:IP to the wrapper's "lret" */
357         CS_reg(context) = DPMI_wrap_seg;
358         IP_reg(context) = 2;
359 #endif
360         TRACE(int31,"entering real mode...\n");
361         DOSVM_Enter( context );
362         TRACE(int31,"returned from real-mode call\n");
363 #else
364         addr = CTX_SEG_OFF_TO_LIN(context, CS_reg(context), EIP_reg(context));
365         sel = SELECTOR_AllocBlock( addr, 0x10000, SEGMENT_CODE, FALSE, FALSE );
366         seg_addr = PTR_SEG_OFF_TO_SEGPTR( sel, 0 );
367
368         CS_reg(context) = HIWORD(seg_addr);
369         IP_reg(context) = LOWORD(seg_addr);
370         EBP_reg(context) = OFFSETOF( thdb->cur_stack )
371                                    + (WORD)&((STACK16FRAME*)0)->bp;
372         Callbacks->CallRegisterShortProc(context, args*sizeof(WORD));
373         UnMapLS(seg_addr);
374 #endif
375     }
376     if (alloc) DOSMEM_FreeBlock( pModule->self, addr );
377     return 0;
378 }
379
380
381 /**********************************************************************
382  *          CallRMInt
383  */
384 static void CallRMInt( CONTEXT *context )
385 {
386     CONTEXT realmode_ctx;
387     FARPROC16 rm_int = INT_GetRMHandler( BL_reg(context) );
388     REALMODECALL *call = (REALMODECALL *)PTR_SEG_OFF_TO_LIN( ES_reg(context),
389                                                           DI_reg(context) );
390     INT_GetRealModeContext( call, &realmode_ctx );
391
392     /* we need to check if a real-mode program has hooked the interrupt */
393     if (HIWORD(rm_int)!=0xF000) {
394         /* yup, which means we need to switch to real mode... */
395         CS_reg(&realmode_ctx) = HIWORD(rm_int);
396         EIP_reg(&realmode_ctx) = LOWORD(rm_int);
397         if (DPMI_CallRMProc( &realmode_ctx, NULL, 0, TRUE))
398           SET_CFLAG(context);
399     } else {
400         RESET_CFLAG(context);
401         /* use the IP we have instead of BL_reg, in case some apps
402            decide to move interrupts around for whatever reason... */
403         if (INT_RealModeInterrupt( LOWORD(rm_int)/4, &realmode_ctx ))
404           SET_CFLAG(context);
405         if (EFL_reg(context)&1) {
406           FIXME(int31,"%02x: EAX=%08lx EBX=%08lx ECX=%08lx EDX=%08lx\n",
407                 BL_reg(context), EAX_reg(&realmode_ctx), EBX_reg(&realmode_ctx), 
408                 ECX_reg(&realmode_ctx), EDX_reg(&realmode_ctx));
409           FIXME(int31,"      ESI=%08lx EDI=%08lx DS=%04lx ES=%04lx\n",
410                 ESI_reg(&realmode_ctx), EDI_reg(&realmode_ctx), 
411                 DS_reg(&realmode_ctx), ES_reg(&realmode_ctx) );
412         }
413     }
414     INT_SetRealModeContext( call, &realmode_ctx );
415 }
416
417
418 static void CallRMProc( CONTEXT *context, int iret )
419 {
420     REALMODECALL *p = (REALMODECALL *)PTR_SEG_OFF_TO_LIN( ES_reg(context), DI_reg(context) );
421     CONTEXT context16;
422
423     TRACE(int31, "RealModeCall: EAX=%08lx EBX=%08lx ECX=%08lx EDX=%08lx\n",
424         p->eax, p->ebx, p->ecx, p->edx);
425     TRACE(int31, "              ESI=%08lx EDI=%08lx ES=%04x DS=%04x CS:IP=%04x:%04x, %d WORD arguments, %s\n",
426         p->esi, p->edi, p->es, p->ds, p->cs, p->ip, CX_reg(context), iret?"IRET":"FAR" );
427
428     if (!(p->cs) && !(p->ip)) { /* remove this check
429                                    if Int21/6501 case map function
430                                    has been implemented */
431         SET_CFLAG(context);
432         return;
433     }
434     INT_GetRealModeContext(p, &context16);
435     DPMI_CallRMProc( &context16, ((LPWORD)PTR_SEG_OFF_TO_LIN(SS_reg(context), SP_reg(context)))+3,
436                      CX_reg(context), iret );
437     INT_SetRealModeContext(p, &context16);
438 }
439
440
441 static void WINAPI WINE_UNUSED RMCallbackProc( RMCB *rmcb )
442 {
443     /* This routine should call DPMI_CallRMCBProc, but we don't have the
444        register structure available - this is easily fixed by going through
445        a Win16 register relay instead of calling RMCallbackProc "directly",
446        but I won't bother at this time. */
447     FIXME(int31,"not properly supported on your architecture!\n");
448 }
449
450 static RMCB *DPMI_AllocRMCB( void )
451 {
452     RMCB *NewRMCB = HeapAlloc(GetProcessHeap(), 0, sizeof(RMCB));
453     UINT16 uParagraph;
454
455     if (NewRMCB)
456     {
457 #ifdef MZ_SUPPORTED
458         LPVOID RMCBmem = DOSMEM_GetBlock(0, 4, &uParagraph);
459         LPBYTE p = RMCBmem;
460
461         *p++ = 0xcd; /* RMCB: */
462         *p++ = 0x31; /* int $0x31 */
463 /* it is the called procedure's task to change the return CS:EIP
464    the DPMI 0.9 spec states that if it doesn't, it will be called again */
465         *p++ = 0xeb;
466         *p++ = 0xfc; /* jmp RMCB */
467 #else
468         LPVOID RMCBmem = DOSMEM_GetBlock(0, 15, &uParagraph);
469         LPBYTE p = RMCBmem;
470
471         *p++ = 0x68; /* pushl */
472         *(LPVOID *)p = NewRMCB;
473         p+=4;
474         *p++ = 0x9a; /* lcall */
475         *(FARPROC16 *)p = (FARPROC16)RMCallbackProc; /* FIXME: register relay */
476         p+=4;
477         GET_CS(*(WORD *)p);
478         p+=2;
479         *p++=0xc3; /* lret (FIXME?) */
480 #endif
481         NewRMCB->address = MAKELONG(0, uParagraph);
482         NewRMCB->next = FirstRMCB;
483         FirstRMCB = NewRMCB;
484     }
485     return NewRMCB;
486 }
487
488
489 static void AllocRMCB( CONTEXT *context )
490 {
491     RMCB *NewRMCB = DPMI_AllocRMCB();
492
493     TRACE(int31, "Function to call: %04x:%04x\n", (WORD)DS_reg(context), SI_reg(context) );
494
495     if (NewRMCB)
496     {
497         /* FIXME: if 32-bit DPMI client, use ESI and EDI */
498         NewRMCB->proc_ofs = SI_reg(context);
499         NewRMCB->proc_sel = DS_reg(context);
500         NewRMCB->regs_ofs = DI_reg(context);
501         NewRMCB->regs_sel = ES_reg(context);
502         CX_reg(context) = HIWORD(NewRMCB->address);
503         DX_reg(context) = LOWORD(NewRMCB->address);
504     }
505     else
506     {
507         AX_reg(context) = 0x8015; /* callback unavailable */
508         SET_CFLAG(context);
509     }
510 }
511
512
513 FARPROC16 WINAPI DPMI_AllocInternalRMCB( RMCBPROC proc )
514 {
515     RMCB *NewRMCB = DPMI_AllocRMCB();
516
517     if (NewRMCB) {
518         NewRMCB->proc_ofs = (DWORD)proc;
519         NewRMCB->proc_sel = 0;
520         NewRMCB->regs_ofs = 0;
521         NewRMCB->regs_sel = 0;
522         return (FARPROC16)(NewRMCB->address);
523     }
524     return NULL;
525 }
526
527
528 static int DPMI_FreeRMCB( DWORD address )
529 {
530     RMCB *CurrRMCB = FirstRMCB;
531     RMCB *PrevRMCB = NULL;
532
533     while (CurrRMCB && (CurrRMCB->address != address))
534     {
535         PrevRMCB = CurrRMCB;
536         CurrRMCB = CurrRMCB->next;
537     }
538     if (CurrRMCB)
539     {
540         if (PrevRMCB)
541         PrevRMCB->next = CurrRMCB->next;
542             else
543         FirstRMCB = CurrRMCB->next;
544         DOSMEM_FreeBlock(0, DOSMEM_MapRealToLinear(CurrRMCB->address));
545         HeapFree(GetProcessHeap(), 0, CurrRMCB);
546         return 0;
547     }
548     return 1;
549 }
550
551
552 static void FreeRMCB( CONTEXT *context )
553 {
554     FIXME(int31, "callback address: %04x:%04x\n",
555           CX_reg(context), DX_reg(context));
556
557     if (DPMI_FreeRMCB(MAKELONG(DX_reg(context), CX_reg(context)))) {
558         AX_reg(context) = 0x8024; /* invalid callback address */
559         SET_CFLAG(context);
560     }
561 }
562
563
564 void WINAPI DPMI_FreeInternalRMCB( FARPROC16 proc )
565 {
566     DPMI_FreeRMCB( (DWORD)proc );
567 }
568
569
570 #ifdef MZ_SUPPORTED
571 /* (see loader/dos/module.c, function MZ_InitDPMI) */
572
573 static void StartPM( CONTEXT *context, LPDOSTASK lpDosTask )
574 {
575     char *base = DOSMEM_MemoryBase(0);
576     UINT16 cs, ss, ds, es;
577     CONTEXT pm_ctx;
578
579     RESET_CFLAG(context);
580     lpDosTask->dpmi_flag = AX_reg(context);
581 /* our mode switch wrapper have placed the desired CS into DX */
582     cs = SELECTOR_AllocBlock( base + (DWORD)(DX_reg(context)<<4), 0x10000, SEGMENT_CODE, FALSE, FALSE );
583     ss = SELECTOR_AllocBlock( base + (DWORD)(SS_reg(context)<<4), 0x10000, SEGMENT_DATA, FALSE, FALSE );
584     ds = SELECTOR_AllocBlock( base + (DWORD)(DS_reg(context)<<4), 0x10000, SEGMENT_DATA, FALSE, FALSE );
585     es = SELECTOR_AllocBlock( base + (DWORD)(lpDosTask->psp_seg<<4), 0x100, SEGMENT_DATA, FALSE, FALSE );
586
587     pm_ctx = *context;
588     CS_reg(&pm_ctx) = lpDosTask->dpmi_sel;
589 /* our mode switch wrapper expects the new CS in DX, and the new SS in AX */
590     AX_reg(&pm_ctx) = ss;
591     DX_reg(&pm_ctx) = cs;
592     DS_reg(&pm_ctx) = ds;
593     ES_reg(&pm_ctx) = es;
594     FS_reg(&pm_ctx) = 0;
595     GS_reg(&pm_ctx) = 0;
596
597     TRACE(int31,"DOS program is now entering protected mode\n");
598     Callbacks->CallRegisterShortProc(&pm_ctx, 0);
599
600     /* in the current state of affairs, we won't ever actually return here... */
601
602     UnMapLS(PTR_SEG_OFF_TO_SEGPTR(es,0));
603     UnMapLS(PTR_SEG_OFF_TO_SEGPTR(ds,0));
604     UnMapLS(PTR_SEG_OFF_TO_SEGPTR(ss,0));
605     UnMapLS(PTR_SEG_OFF_TO_SEGPTR(cs,0));
606 }
607 #endif
608
609 /**********************************************************************
610  *          INT_Int31Handler
611  *
612  * Handler for int 31h (DPMI).
613  */
614
615 void WINAPI INT_Int31Handler( CONTEXT *context )
616 {
617     /*
618      * Note: For Win32s processes, the whole linear address space is
619      *       shifted by 0x10000 relative to the OS linear address space.
620      *       See the comment in msdos/vxd.c.
621      */
622     DWORD offset = W32S_APPLICATION() ? W32S_OFFSET : 0;
623
624     DWORD dw;
625     BYTE *ptr;
626
627     TDB *pTask = (TDB *)GlobalLock16( GetCurrentTask() );
628     NE_MODULE *pModule = pTask ? NE_GetPtr( pTask->hModule ) : NULL;
629
630     GlobalUnlock16( GetCurrentTask() );
631
632 #ifdef MZ_SUPPORTED
633     if (ISV86(context) && pModule && pModule->lpDosTask) {
634         /* Called from real mode, check if it's our wrapper */
635         TRACE(int31,"called from real mode\n");
636         if (CS_reg(context)==pModule->lpDosTask->dpmi_seg) {
637             /* This is the protected mode switch */
638             StartPM(context,pModule->lpDosTask);
639             return;
640         } else
641         if (CS_reg(context)==pModule->lpDosTask->xms_seg) {
642             /* This is the XMS driver entry point */
643             XMS_Handler(context);
644             return;
645         } else
646         {
647             /* Check for RMCB */
648             RMCB *CurrRMCB = FirstRMCB;
649             
650             while (CurrRMCB && (HIWORD(CurrRMCB->address) != CS_reg(context)))
651                 CurrRMCB = CurrRMCB->next;
652             
653             if (CurrRMCB) {
654                 /* RMCB call, propagate to protected-mode handler */
655                 DPMI_CallRMCBProc(context, CurrRMCB, pModule->lpDosTask->dpmi_flag);
656                 return;
657             }
658         }
659     }
660 #endif
661
662     RESET_CFLAG(context);
663     switch(AX_reg(context))
664     {
665     case 0x0000:  /* Allocate LDT descriptors */
666         TRACE(int31,"allocate LDT descriptors (%d)\n",CX_reg(context));
667         if (!(AX_reg(context) = AllocSelectorArray16( CX_reg(context) )))
668         {
669             TRACE(int31,"failed\n");
670             AX_reg(context) = 0x8011;  /* descriptor unavailable */
671             SET_CFLAG(context);
672         }
673         TRACE(int31,"success, array starts at 0x%04x\n",AX_reg(context));
674         break;
675
676     case 0x0001:  /* Free LDT descriptor */
677         TRACE(int31,"free LDT descriptor (0x%04x)\n",BX_reg(context));
678         if (FreeSelector16( BX_reg(context) ))
679         {
680             AX_reg(context) = 0x8022;  /* invalid selector */
681             SET_CFLAG(context);
682         }
683         else
684         {
685             /* If a segment register contains the selector being freed, */
686             /* set it to zero. */
687             if (!((DS_reg(context)^BX_reg(context)) & ~3)) DS_reg(context) = 0;
688             if (!((ES_reg(context)^BX_reg(context)) & ~3)) ES_reg(context) = 0;
689             if (!((FS_reg(context)^BX_reg(context)) & ~3)) FS_reg(context) = 0;
690             if (!((GS_reg(context)^BX_reg(context)) & ~3)) GS_reg(context) = 0;
691         }
692         break;
693
694     case 0x0002:  /* Real mode segment to descriptor */
695         TRACE(int31,"real mode segment to descriptor (0x%04x)\n",BX_reg(context));
696         {
697             WORD entryPoint = 0;  /* KERNEL entry point for descriptor */
698             switch(BX_reg(context))
699             {
700             case 0x0000: entryPoint = 183; break;  /* __0000H */
701             case 0x0040: entryPoint = 193; break;  /* __0040H */
702             case 0xa000: entryPoint = 174; break;  /* __A000H */
703             case 0xb000: entryPoint = 181; break;  /* __B000H */
704             case 0xb800: entryPoint = 182; break;  /* __B800H */
705             case 0xc000: entryPoint = 195; break;  /* __C000H */
706             case 0xd000: entryPoint = 179; break;  /* __D000H */
707             case 0xe000: entryPoint = 190; break;  /* __E000H */
708             case 0xf000: entryPoint = 194; break;  /* __F000H */
709             default:
710                 AX_reg(context) = DOSMEM_AllocSelector(BX_reg(context));
711                 break;
712             }
713             if (entryPoint) 
714                 AX_reg(context) = LOWORD(NE_GetEntryPoint( 
715                                                  GetModuleHandle16( "KERNEL" ),
716                                                  entryPoint ));
717         }
718         break;
719
720     case 0x0003:  /* Get next selector increment */
721         TRACE(int31,"get selector increment (__AHINCR)\n");
722         AX_reg(context) = __AHINCR;
723         break;
724
725     case 0x0004:  /* Lock selector (not supported) */
726         FIXME(int31,"lock selector not supported\n");
727         AX_reg(context) = 0;  /* FIXME: is this a correct return value? */
728         break;
729
730     case 0x0005:  /* Unlock selector (not supported) */
731         FIXME(int31,"unlock selector not supported\n");
732         AX_reg(context) = 0;  /* FIXME: is this a correct return value? */
733         break;
734
735     case 0x0006:  /* Get selector base address */
736         TRACE(int31,"get selector base address (0x%04x)\n",BX_reg(context));
737         if (!(dw = GetSelectorBase( BX_reg(context) )))
738         {
739             AX_reg(context) = 0x8022;  /* invalid selector */
740             SET_CFLAG(context);
741         }
742         else
743         {
744 #ifdef MZ_SUPPORTED
745             if (pModule && pModule->lpDosTask) {
746                 DWORD base = (DWORD)DOSMEM_MemoryBase(pModule->self);
747                 if ((dw >= base) && (dw < base + 0x110000)) dw -= base;
748             }
749 #endif
750             CX_reg(context) = HIWORD(W32S_WINE2APP(dw, offset));
751             DX_reg(context) = LOWORD(W32S_WINE2APP(dw, offset));
752         }
753         break;
754
755     case 0x0007:  /* Set selector base address */
756         TRACE(int31, "set selector base address (0x%04x,0x%08lx)\n",
757                      BX_reg(context),
758                      W32S_APP2WINE(MAKELONG(DX_reg(context),CX_reg(context)), offset));
759         dw = W32S_APP2WINE(MAKELONG(DX_reg(context), CX_reg(context)), offset);
760 #ifdef MZ_SUPPORTED
761         /* well, what else could we possibly do? */
762         if (pModule && pModule->lpDosTask) {
763             if (dw < 0x110000) dw += (DWORD)DOSMEM_MemoryBase(pModule->self);
764         }
765 #endif
766         SetSelectorBase(BX_reg(context), dw);
767         break;
768
769     case 0x0008:  /* Set selector limit */
770         TRACE(int31,"set selector limit (0x%04x,0x%08lx)\n",BX_reg(context),MAKELONG(DX_reg(context),CX_reg(context)));
771         dw = MAKELONG( DX_reg(context), CX_reg(context) );
772 #ifdef MZ_SUPPORTED
773         if (pModule && pModule->lpDosTask) {
774             DWORD base = GetSelectorBase( BX_reg(context) );
775             if ((dw == 0xffffffff) || ((base < 0x110000) && (base + dw > 0x110000))) {
776                 AX_reg(context) = 0x8021;  /* invalid value */
777                 SET_CFLAG(context);
778                 break;
779             }
780         }
781 #endif
782         SetSelectorLimit16( BX_reg(context), dw );
783         break;
784
785     case 0x0009:  /* Set selector access rights */
786         TRACE(int31,"set selector access rights(0x%04x,0x%04x)\n",BX_reg(context),CX_reg(context));
787         SelectorAccessRights16( BX_reg(context), 1, CX_reg(context) );
788         break;
789
790     case 0x000a:  /* Allocate selector alias */
791         TRACE(int31,"allocate selector alias (0x%04x)\n",BX_reg(context));
792         if (!(AX_reg(context) = AllocCStoDSAlias16( BX_reg(context) )))
793         {
794             AX_reg(context) = 0x8011;  /* descriptor unavailable */
795             SET_CFLAG(context);
796         }
797         break;
798
799     case 0x000b:  /* Get descriptor */
800         TRACE(int31,"get descriptor (0x%04x)\n",BX_reg(context));
801         {
802             ldt_entry entry;
803             LDT_GetEntry( SELECTOR_TO_ENTRY( BX_reg(context) ), &entry );
804             entry.base = W32S_WINE2APP(entry.base, offset);
805
806             /* FIXME: should use ES:EDI for 32-bit clients */
807             LDT_EntryToBytes( PTR_SEG_OFF_TO_LIN( ES_reg(context),
808                                                   DI_reg(context) ), &entry );
809         }
810         break;
811
812     case 0x000c:  /* Set descriptor */
813         TRACE(int31,"set descriptor (0x%04x)\n",BX_reg(context));
814         {
815             ldt_entry entry;
816             LDT_BytesToEntry( PTR_SEG_OFF_TO_LIN( ES_reg(context),
817                                                   DI_reg(context) ), &entry );
818             entry.base = W32S_APP2WINE(entry.base, offset);
819
820             LDT_SetEntry( SELECTOR_TO_ENTRY( BX_reg(context) ), &entry );
821         }
822         break;
823
824     case 0x000d:  /* Allocate specific LDT descriptor */
825         FIXME(int31,"allocate descriptor (0x%04x), stub!\n",BX_reg(context));
826         AX_reg(context) = 0x8011; /* descriptor unavailable */
827         SET_CFLAG(context);
828         break;
829     case 0x0100:  /* Allocate DOS memory block */
830         TRACE(int31,"allocate DOS memory block (0x%x paragraphs)\n",BX_reg(context));
831         dw = GlobalDOSAlloc16((DWORD)BX_reg(context)<<4);
832         if (dw) {
833             AX_reg(context) = HIWORD(dw);
834             DX_reg(context) = LOWORD(dw);
835         } else {
836             AX_reg(context) = 0x0008; /* insufficient memory */
837             BX_reg(context) = DOSMEM_Available(0)>>4;
838             SET_CFLAG(context);
839         }
840         break;
841     case 0x0101:  /* Free DOS memory block */
842         TRACE(int31,"free DOS memory block (0x%04x)\n",DX_reg(context));
843         dw = GlobalDOSFree16(DX_reg(context));
844         if (!dw) {
845             AX_reg(context) = 0x0009; /* memory block address invalid */
846             SET_CFLAG(context);
847         }
848         break;
849     case 0x0200: /* get real mode interrupt vector */
850         FIXME(int31,"get realmode interupt vector(0x%02x) unimplemented.\n",
851               BL_reg(context));
852         SET_CFLAG(context);
853         break;
854     case 0x0201: /* set real mode interrupt vector */
855         FIXME(int31, "set realmode interupt vector(0x%02x,0x%04x:0x%04x) unimplemented\n", BL_reg(context),CX_reg(context),DX_reg(context));
856         SET_CFLAG(context);
857         break;
858     case 0x0204:  /* Get protected mode interrupt vector */
859         TRACE(int31,"get protected mode interrupt handler (0x%02x), stub!\n",BL_reg(context));
860         dw = (DWORD)INT_GetPMHandler( BL_reg(context) );
861         CX_reg(context) = HIWORD(dw);
862         DX_reg(context) = LOWORD(dw);
863         break;
864
865     case 0x0205:  /* Set protected mode interrupt vector */
866         TRACE(int31,"set protected mode interrupt handler (0x%02x,%p), stub!\n",
867             BL_reg(context),PTR_SEG_OFF_TO_LIN(CX_reg(context),DX_reg(context)));
868         INT_SetPMHandler( BL_reg(context),
869                           (FARPROC16)PTR_SEG_OFF_TO_SEGPTR( CX_reg(context),
870                                                             DX_reg(context) ));
871         break;
872
873     case 0x0300:  /* Simulate real mode interrupt */
874         CallRMInt( context );
875         break;
876
877     case 0x0301:  /* Call real mode procedure with far return */
878         CallRMProc( context, FALSE );
879         break;
880
881     case 0x0302:  /* Call real mode procedure with interrupt return */
882         CallRMProc( context, TRUE );
883         break;
884
885     case 0x0303:  /* Allocate Real Mode Callback Address */
886         AllocRMCB( context );
887         break;
888
889     case 0x0304:  /* Free Real Mode Callback Address */
890         FreeRMCB( context );
891         break;
892
893     case 0x0400:  /* Get DPMI version */
894         TRACE(int31,"get DPMI version\n");
895         {
896             SYSTEM_INFO si;
897
898             GetSystemInfo(&si);
899             AX_reg(context) = 0x005a;  /* DPMI version 0.90 */
900             BX_reg(context) = 0x0005;  /* Flags: 32-bit, virtual memory */
901             CL_reg(context) = si.wProcessorLevel;
902             DX_reg(context) = 0x0102;  /* Master/slave interrupt controller base*/
903             break;
904         }
905     case 0x0500:  /* Get free memory information */
906         TRACE(int31,"get free memory information\n");
907         {
908             MEMMANINFO mmi;
909
910             mmi.dwSize = sizeof(mmi);
911             MemManInfo16(&mmi);
912             ptr = (BYTE *)PTR_SEG_OFF_TO_LIN(ES_reg(context),DI_reg(context));
913             /* the layout is just the same as MEMMANINFO, but without
914              * the dwSize entry.
915              */
916             memcpy(ptr,((char*)&mmi)+4,sizeof(mmi)-4);
917             break;
918         }
919     case 0x0501:  /* Allocate memory block */
920         TRACE(int31,"allocate memory block (%ld)\n",MAKELONG(CX_reg(context),BX_reg(context)));
921         if (!(ptr = (BYTE *)DPMI_xalloc(MAKELONG(CX_reg(context), BX_reg(context)))))
922         {
923             AX_reg(context) = 0x8012;  /* linear memory not available */
924             SET_CFLAG(context);
925         } else {
926             BX_reg(context) = SI_reg(context) = HIWORD(W32S_WINE2APP(ptr, offset));
927             CX_reg(context) = DI_reg(context) = LOWORD(W32S_WINE2APP(ptr, offset));
928         }
929         break;
930
931     case 0x0502:  /* Free memory block */
932         TRACE(int31, "free memory block (0x%08lx)\n",
933                      W32S_APP2WINE(MAKELONG(DI_reg(context),SI_reg(context)), offset));
934         DPMI_xfree( (void *)W32S_APP2WINE(MAKELONG(DI_reg(context), 
935                                                SI_reg(context)), offset) );
936         break;
937
938     case 0x0503:  /* Resize memory block */
939         TRACE(int31, "resize memory block (0x%08lx,%ld)\n",
940                      W32S_APP2WINE(MAKELONG(DI_reg(context),SI_reg(context)), offset),
941                      MAKELONG(CX_reg(context),BX_reg(context)));
942         if (!(ptr = (BYTE *)DPMI_xrealloc(
943                 (void *)W32S_APP2WINE(MAKELONG(DI_reg(context),SI_reg(context)), offset),
944                 MAKELONG(CX_reg(context),BX_reg(context)))))
945         {
946             AX_reg(context) = 0x8012;  /* linear memory not available */
947             SET_CFLAG(context);
948         } else {
949             BX_reg(context) = SI_reg(context) = HIWORD(W32S_WINE2APP(ptr, offset));
950             CX_reg(context) = DI_reg(context) = LOWORD(W32S_WINE2APP(ptr, offset));
951         }
952         break;
953
954     case 0x0507:  /* Modify page attributes */
955         FIXME(int31,"modify page attributes unimplemented\n");
956         break;  /* Just ignore it */
957
958     case 0x0600:  /* Lock linear region */
959         FIXME(int31,"lock linear region unimplemented\n");
960         break;  /* Just ignore it */
961
962     case 0x0601:  /* Unlock linear region */
963         FIXME(int31,"unlock linear region unimplemented\n");
964         break;  /* Just ignore it */
965
966     case 0x0602:  /* Unlock real-mode region */
967         FIXME(int31,"unlock realmode region unimplemented\n");
968         break;  /* Just ignore it */
969
970     case 0x0603:  /* Lock real-mode region */
971         FIXME(int31,"lock realmode region unimplemented\n");
972         break;  /* Just ignore it */
973
974     case 0x0604:  /* Get page size */
975         TRACE(int31,"get pagesize\n");
976         BX_reg(context) = 0;
977         CX_reg(context) = VIRTUAL_GetPageSize();
978         break;
979
980     case 0x0702:  /* Mark page as demand-paging candidate */
981         FIXME(int31,"mark page as demand-paging candidate\n");
982         break;  /* Just ignore it */
983
984     case 0x0703:  /* Discard page contents */
985         FIXME(int31,"discard page contents\n");
986         break;  /* Just ignore it */
987
988      case 0x0800:  /* Physical address mapping */
989         FIXME(int31,"map real to linear (0x%08lx)\n",MAKELONG(CX_reg(context),BX_reg(context)));
990          if(!(ptr=DOSMEM_MapRealToLinear(MAKELONG(CX_reg(context),BX_reg(context)))))
991          {
992              AX_reg(context) = 0x8021; 
993              SET_CFLAG(context);
994          }
995          else
996          {
997              BX_reg(context) = HIWORD(W32S_WINE2APP(ptr, offset));
998              CX_reg(context) = LOWORD(W32S_WINE2APP(ptr, offset));
999              RESET_CFLAG(context);
1000          }
1001          break;
1002
1003     default:
1004         INT_BARF( context, 0x31 );
1005         AX_reg(context) = 0x8001;  /* unsupported function */
1006         SET_CFLAG(context);
1007         break;
1008     }
1009
1010 }