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