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