Added DPMI segments structure and related function to avoid direct
[wine] / msdos / dpmi.c
1 /*
2  * DPMI 0.9 emulation
3  *
4  * Copyright 1995 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #ifdef HAVE_UNISTD_H
25 # include <unistd.h>
26 #endif
27 #include <string.h>
28
29 #include "windef.h"
30 #include "wine/winbase16.h"
31 #include "miscemu.h"
32 #include "msdos.h"
33 #include "task.h"
34 #include "toolhelp.h"
35 #include "selectors.h"
36 #include "callback.h"
37 #include "wine/debug.h"
38 #include "stackframe.h"
39
40 WINE_DEFAULT_DEBUG_CHANNEL(int31);
41
42 #define DOS_GET_DRIVE(reg) ((reg) ? (reg) - 1 : DRIVE_GetCurrentDrive())
43
44 void CreateBPB(int drive, BYTE *data, BOOL16 limited);  /* defined in int21.c */
45
46 static void* lastvalloced = NULL;
47
48
49 DOSVM_TABLE Dosvm = { NULL, };
50
51 static HMODULE DosModule;
52
53 /**********************************************************************
54  *          DPMI_LoadDosSystem
55  */
56 BOOL DPMI_LoadDosSystem(void)
57 {
58     if (DosModule) return TRUE;
59     DosModule = LoadLibraryA( "winedos.dll" );
60     if (!DosModule) {
61         ERR("could not load winedos.dll, DOS subsystem unavailable\n");
62         return FALSE;
63     }
64 #define GET_ADDR(func)  Dosvm.func = (void *)GetProcAddress(DosModule, #func);
65
66     GET_ADDR(LoadDosExe);
67     GET_ADDR(CallRMInt);
68     GET_ADDR(CallRMProc);
69     GET_ADDR(AllocRMCB);
70     GET_ADDR(FreeRMCB);
71     GET_ADDR(RawModeSwitch);
72     GET_ADDR(SetTimer);
73     GET_ADDR(GetTimer);
74     GET_ADDR(inport);
75     GET_ADDR(outport);
76     GET_ADDR(ASPIHandler);
77 #undef GET_ADDR
78     return TRUE;
79 }
80
81 /**********************************************************************
82  *          DPMI_xalloc
83  * special virtualalloc, allocates lineary monoton growing memory.
84  * (the usual VirtualAlloc does not satisfy that restriction)
85  */
86 static LPVOID
87 DPMI_xalloc(int len) {
88         LPVOID  ret;
89         LPVOID  oldlastv = lastvalloced;
90
91         if (lastvalloced) {
92                 int     xflag = 0;
93                 ret = NULL;
94                 while (!ret) {
95                         ret=VirtualAlloc(lastvalloced,len,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE);
96                         if (!ret)
97                                 lastvalloced = (char *) lastvalloced + 0x10000;
98                         /* we failed to allocate one in the first round.
99                          * try non-linear
100                          */
101                         if (!xflag && (lastvalloced<oldlastv)) { /* wrapped */
102                                 FIXME("failed to allocate lineary growing memory (%d bytes), using non-linear growing...\n",len);
103                                 xflag++;
104                         }
105                         /* if we even fail to allocate something in the next
106                          * round, return NULL
107                          */
108                         if ((xflag==1) && (lastvalloced >= oldlastv))
109                                 xflag++;
110                         if ((xflag==2) && (lastvalloced < oldlastv)) {
111                                 FIXME("failed to allocate any memory of %d bytes!\n",len);
112                                 return NULL;
113                         }
114                 }
115         } else
116                  ret=VirtualAlloc(NULL,len,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE);
117         lastvalloced = (LPVOID)(((DWORD)ret+len+0xffff)&~0xffff);
118         return ret;
119 }
120
121 static void
122 DPMI_xfree(LPVOID ptr) {
123         VirtualFree(ptr,0,MEM_RELEASE);
124 }
125
126 /* FIXME: perhaps we could grow this mapped area... */
127 static LPVOID
128 DPMI_xrealloc(LPVOID ptr,DWORD newsize) {
129         MEMORY_BASIC_INFORMATION        mbi;
130         LPVOID                          newptr;
131
132         newptr = DPMI_xalloc(newsize);
133         if (ptr) {
134                 if (!VirtualQuery(ptr,&mbi,sizeof(mbi))) {
135                         FIXME("realloc of DPMI_xallocd region %p?\n",ptr);
136                         return NULL;
137                 }
138                 if (mbi.State == MEM_FREE) {
139                         FIXME("realloc of DPMI_xallocd region %p?\n",ptr);
140                         return NULL;
141                 }
142                 /* We do not shrink allocated memory. most reallocs
143                  * only do grows anyway
144                  */
145                 if (newsize<=mbi.RegionSize)
146                         return ptr;
147                 memcpy(newptr,ptr,mbi.RegionSize);
148                 DPMI_xfree(ptr);
149         }
150         return newptr;
151 }
152
153 /**********************************************************************
154  *          CallRMInt
155  */
156 static void CallRMInt( CONTEXT86 *context )
157 {
158     if (!Dosvm.CallRMInt && !DPMI_LoadDosSystem())
159     {
160         ERR("could not setup real-mode calls\n");
161         return;
162     }
163     Dosvm.CallRMInt( context );
164 }
165
166
167 static void CallRMProc( CONTEXT86 *context, int iret )
168 {
169     if (!Dosvm.CallRMProc && !DPMI_LoadDosSystem())
170     {
171         ERR("could not setup real-mode calls\n");
172         return;
173     }
174     Dosvm.CallRMProc( context, iret );
175 }
176
177 static void AllocRMCB( CONTEXT86 *context )
178 {
179     if (!Dosvm.AllocRMCB && !DPMI_LoadDosSystem())
180     {
181         ERR("could not setup real-mode calls\n");
182         return;
183     }
184     Dosvm.AllocRMCB( context );
185 }
186
187 static void FreeRMCB( CONTEXT86 *context )
188 {
189     if (!Dosvm.FreeRMCB)  /* cannot have allocated one if dosvm not loaded */
190     {
191         SET_LOWORD( context->Eax, 0x8024 ); /* invalid callback address */
192         SET_CFLAG( context );
193     }
194     else Dosvm.FreeRMCB( context );
195 }
196
197 static void RawModeSwitch( CONTEXT86 *context )
198 {
199     if (!Dosvm.RawModeSwitch)
200     {
201       ERR("could not setup real-mode calls\n");
202       return;
203     }
204     else
205     {
206       /*
207        * FIXME: This routine will not work if it is called
208        *        from 32 bit DPMI program and the program returns
209        *        to protected mode while ESP or EIP is over 0xffff.
210        * FIXME: This routine will not work if it is not called
211        *        using 16-bit-to-Wine callback glue function.
212        */
213       STACK16FRAME frame = *CURRENT_STACK16;
214
215       Dosvm.RawModeSwitch( context );
216
217       /*
218        * After this function returns to relay code, protected mode
219        * 16 bit stack will contain STACK16FRAME and single WORD
220        * (EFlags, see next comment).
221        */
222       NtCurrentTeb()->cur_stack =
223         MAKESEGPTR( context->SegSs,
224                     context->Esp - sizeof(STACK16FRAME) - sizeof(WORD) );
225
226       /*
227        * After relay code returns to glue function, protected
228        * mode 16 bit stack will contain interrupt return record:
229        * IP, CS and EFlags. Since EFlags is ignored, it won't
230        * need to be initialized.
231        */
232       context->Esp -= 3 * sizeof(WORD);
233
234       /*
235        * Restore stack frame so that relay code won't be confused.
236        * It should be noted that relay code overwrites IP and CS
237        * in STACK16FRAME with values taken from current CONTEXT86.
238        * These values are what is returned to glue function
239        * (see previous comment).
240        */
241       *CURRENT_STACK16 = frame;
242     }
243 }
244
245 /**********************************************************************
246  *          INT_Int31Handler (WPROCS.149)
247  *
248  * Handler for int 31h (DPMI).
249  */
250
251 void WINAPI INT_Int31Handler( CONTEXT86 *context )
252 {
253     /*
254      * Note: For Win32s processes, the whole linear address space is
255      *       shifted by 0x10000 relative to the OS linear address space.
256      *       See the comment in msdos/vxd.c.
257      */
258     DWORD dw;
259     BYTE *ptr;
260
261     if (context->SegCs == DOSMEM_dpmi_segments.dpmi_sel) {
262         RawModeSwitch( context );
263         return;
264     }
265
266     RESET_CFLAG(context);
267     switch(AX_reg(context))
268     {
269     case 0x0000:  /* Allocate LDT descriptors */
270         TRACE("allocate LDT descriptors (%d)\n",CX_reg(context));
271         if (!(context->Eax = AllocSelectorArray16( CX_reg(context) )))
272         {
273             TRACE("failed\n");
274             context->Eax = 0x8011;  /* descriptor unavailable */
275             SET_CFLAG(context);
276         }
277         TRACE("success, array starts at 0x%04x\n",AX_reg(context));
278         break;
279
280     case 0x0001:  /* Free LDT descriptor */
281         TRACE("free LDT descriptor (0x%04x)\n",BX_reg(context));
282         if (FreeSelector16( BX_reg(context) ))
283         {
284             context->Eax = 0x8022;  /* invalid selector */
285             SET_CFLAG(context);
286         }
287         else
288         {
289             /* If a segment register contains the selector being freed, */
290             /* set it to zero. */
291             if (!((context->SegDs^BX_reg(context)) & ~3)) context->SegDs = 0;
292             if (!((context->SegEs^BX_reg(context)) & ~3)) context->SegEs = 0;
293             if (!((context->SegFs^BX_reg(context)) & ~3)) context->SegFs = 0;
294             if (!((context->SegGs^BX_reg(context)) & ~3)) context->SegGs = 0;
295         }
296         break;
297
298     case 0x0002:  /* Real mode segment to descriptor */
299         TRACE("real mode segment to descriptor (0x%04x)\n",BX_reg(context));
300         {
301             WORD entryPoint = 0;  /* KERNEL entry point for descriptor */
302             switch(BX_reg(context))
303             {
304             case 0x0000: entryPoint = 183; break;  /* __0000H */
305             case 0x0040: entryPoint = 193; break;  /* __0040H */
306             case 0xa000: entryPoint = 174; break;  /* __A000H */
307             case 0xb000: entryPoint = 181; break;  /* __B000H */
308             case 0xb800: entryPoint = 182; break;  /* __B800H */
309             case 0xc000: entryPoint = 195; break;  /* __C000H */
310             case 0xd000: entryPoint = 179; break;  /* __D000H */
311             case 0xe000: entryPoint = 190; break;  /* __E000H */
312             case 0xf000: entryPoint = 194; break;  /* __F000H */
313             default:
314                 context->Eax = DOSMEM_AllocSelector(BX_reg(context));
315                 break;
316             }
317             if (entryPoint)
318                 context->Eax = LOWORD(GetProcAddress16( GetModuleHandle16( "KERNEL" ),
319                                                         (LPCSTR)(ULONG_PTR)entryPoint ));
320         }
321         break;
322
323     case 0x0003:  /* Get next selector increment */
324         TRACE("get selector increment (__AHINCR)\n");
325         context->Eax = __AHINCR;
326         break;
327
328     case 0x0004:  /* Lock selector (not supported) */
329         FIXME("lock selector not supported\n");
330         context->Eax = 0;  /* FIXME: is this a correct return value? */
331         break;
332
333     case 0x0005:  /* Unlock selector (not supported) */
334         FIXME("unlock selector not supported\n");
335         context->Eax = 0;  /* FIXME: is this a correct return value? */
336         break;
337
338     case 0x0006:  /* Get selector base address */
339         TRACE("get selector base address (0x%04x)\n",BX_reg(context));
340         if (!(dw = GetSelectorBase( BX_reg(context) )))
341         {
342             context->Eax = 0x8022;  /* invalid selector */
343             SET_CFLAG(context);
344         }
345         else
346         {
347             SET_CX( context, HIWORD(W32S_WINE2APP(dw)) );
348             SET_DX( context, LOWORD(W32S_WINE2APP(dw)) );
349         }
350         break;
351
352     case 0x0007:  /* Set selector base address */
353         TRACE("set selector base address (0x%04x,0x%08lx)\n",
354                      BX_reg(context),
355                      W32S_APP2WINE(MAKELONG(DX_reg(context),CX_reg(context))));
356         dw = W32S_APP2WINE(MAKELONG(DX_reg(context), CX_reg(context)));
357         if (dw < 0x10000)
358             /* app wants to access lower 64K of DOS memory, load DOS subsystem */
359             DPMI_LoadDosSystem();
360         SetSelectorBase(BX_reg(context), dw);
361         break;
362
363     case 0x0008:  /* Set selector limit */
364         TRACE("set selector limit (0x%04x,0x%08lx)\n",BX_reg(context),MAKELONG(DX_reg(context),CX_reg(context)));
365         dw = MAKELONG( DX_reg(context), CX_reg(context) );
366         SetSelectorLimit16( BX_reg(context), dw );
367         break;
368
369     case 0x0009:  /* Set selector access rights */
370         TRACE("set selector access rights(0x%04x,0x%04x)\n",BX_reg(context),CX_reg(context));
371         SelectorAccessRights16( BX_reg(context), 1, CX_reg(context) );
372         break;
373
374     case 0x000a:  /* Allocate selector alias */
375         TRACE("allocate selector alias (0x%04x)\n",BX_reg(context));
376         if (!SET_AX( context, AllocCStoDSAlias16( BX_reg(context) )))
377         {
378             SET_AX( context, 0x8011 );  /* descriptor unavailable */
379             SET_CFLAG(context);
380         }
381         break;
382
383     case 0x000b:  /* Get descriptor */
384         TRACE("get descriptor (0x%04x)\n",BX_reg(context));
385         {
386             LDT_ENTRY entry;
387             wine_ldt_set_base( &entry, (void*)W32S_WINE2APP(wine_ldt_get_base(&entry)) );
388             /* FIXME: should use ES:EDI for 32-bit clients */
389             *(LDT_ENTRY *)MapSL( MAKESEGPTR( context->SegEs, LOWORD(context->Edi) )) = entry;
390         }
391         break;
392
393     case 0x000c:  /* Set descriptor */
394         TRACE("set descriptor (0x%04x)\n",BX_reg(context));
395         {
396             LDT_ENTRY entry = *(LDT_ENTRY *)MapSL(MAKESEGPTR( context->SegEs, LOWORD(context->Edi)));
397             wine_ldt_set_base( &entry, (void*)W32S_APP2WINE(wine_ldt_get_base(&entry)) );
398             wine_ldt_set_entry( LOWORD(context->Ebx), &entry );
399         }
400         break;
401
402     case 0x000d:  /* Allocate specific LDT descriptor */
403         FIXME("allocate descriptor (0x%04x), stub!\n",BX_reg(context));
404         SET_AX( context, 0x8011 ); /* descriptor unavailable */
405         SET_CFLAG(context);
406         break;
407     case 0x0100:  /* Allocate DOS memory block */
408         TRACE("allocate DOS memory block (0x%x paragraphs)\n",BX_reg(context));
409         dw = GlobalDOSAlloc16((DWORD)BX_reg(context)<<4);
410         if (dw) {
411             SET_AX( context, HIWORD(dw) );
412             SET_DX( context, LOWORD(dw) );
413         } else {
414             SET_AX( context, 0x0008 ); /* insufficient memory */
415             SET_BX( context, DOSMEM_Available()>>4 );
416             SET_CFLAG(context);
417         }
418         break;
419     case 0x0101:  /* Free DOS memory block */
420         TRACE("free DOS memory block (0x%04x)\n",DX_reg(context));
421         dw = GlobalDOSFree16(DX_reg(context));
422         if (!dw) {
423             SET_AX( context, 0x0009 ); /* memory block address invalid */
424             SET_CFLAG(context);
425         }
426         break;
427     case 0x0200: /* get real mode interrupt vector */
428         FIXME("get realmode interupt vector(0x%02x) unimplemented.\n",
429               BL_reg(context));
430         SET_CFLAG(context);
431         break;
432     case 0x0201: /* set real mode interrupt vector */
433         FIXME("set realmode interrupt vector(0x%02x,0x%04x:0x%04x) unimplemented\n", BL_reg(context),CX_reg(context),DX_reg(context));
434         SET_CFLAG(context);
435         break;
436     case 0x0204:  /* Get protected mode interrupt vector */
437         TRACE("get protected mode interrupt handler (0x%02x), stub!\n",BL_reg(context));
438         dw = (DWORD)INT_GetPMHandler( BL_reg(context) );
439         SET_CX( context, HIWORD(dw) );
440         SET_DX( context, LOWORD(dw) );
441         break;
442
443     case 0x0205:  /* Set protected mode interrupt vector */
444         TRACE("set protected mode interrupt handler (0x%02x,%p), stub!\n",
445             BL_reg(context),MapSL(MAKESEGPTR(CX_reg(context),DX_reg(context))));
446         INT_SetPMHandler( BL_reg(context),
447                           (FARPROC16)MAKESEGPTR( CX_reg(context), DX_reg(context) ));
448         break;
449
450     case 0x0300:  /* Simulate real mode interrupt */
451         CallRMInt( context );
452         break;
453
454     case 0x0301:  /* Call real mode procedure with far return */
455         CallRMProc( context, FALSE );
456         break;
457
458     case 0x0302:  /* Call real mode procedure with interrupt return */
459         CallRMProc( context, TRUE );
460         break;
461
462     case 0x0303:  /* Allocate Real Mode Callback Address */
463         AllocRMCB( context );
464         break;
465
466     case 0x0304:  /* Free Real Mode Callback Address */
467         FreeRMCB( context );
468         break;
469
470     case 0x0305:  /* Get State Save/Restore Addresses */
471         TRACE("get state save/restore addresses\n");
472         /* we probably won't need this kind of state saving */
473         SET_AX( context, 0 );
474         /* real mode: just point to the lret */
475         SET_BX( context, DOSMEM_dpmi_segments.wrap_seg );
476         context->Ecx = 2;
477         /* protected mode: don't have any handler yet... */
478         FIXME("no protected-mode dummy state save/restore handler yet\n");
479         SET_SI( context, 0 );
480         context->Edi = 0;
481         break;
482
483     case 0x0306:  /* Get Raw Mode Switch Addresses */
484         TRACE("get raw mode switch addresses\n");
485         /* real mode, point to standard DPMI return wrapper */
486         SET_BX( context, DOSMEM_dpmi_segments.wrap_seg );
487         context->Ecx = 0;
488         /* protected mode, point to DPMI call wrapper */
489         SET_SI( context, DOSMEM_dpmi_segments.dpmi_sel );
490         context->Edi = 8; /* offset of the INT 0x31 call */
491         break;
492     case 0x0400:  /* Get DPMI version */
493         TRACE("get DPMI version\n");
494         {
495             SYSTEM_INFO si;
496
497             GetSystemInfo(&si);
498             SET_AX( context, 0x005a );  /* DPMI version 0.90 */
499             SET_BX( context, 0x0005 );  /* Flags: 32-bit, virtual memory */
500             SET_CL( context, si.wProcessorLevel );
501             SET_DX( context, 0x0102 );  /* Master/slave interrupt controller base*/
502             break;
503         }
504     case 0x0500:  /* Get free memory information */
505         TRACE("get free memory information\n");
506         {
507             MEMMANINFO mmi;
508
509             mmi.dwSize = sizeof(mmi);
510             MemManInfo16(&mmi);
511             ptr = MapSL(MAKESEGPTR(context->SegEs,DI_reg(context)));
512             /* the layout is just the same as MEMMANINFO, but without
513              * the dwSize entry.
514              */
515             memcpy(ptr,((char*)&mmi)+4,sizeof(mmi)-4);
516             break;
517         }
518     case 0x0501:  /* Allocate memory block */
519         TRACE("allocate memory block (%ld)\n",MAKELONG(CX_reg(context),BX_reg(context)));
520         if (!(ptr = (BYTE *)DPMI_xalloc(MAKELONG(CX_reg(context), BX_reg(context)))))
521         {
522             SET_AX( context, 0x8012 );  /* linear memory not available */
523             SET_CFLAG(context);
524         } else {
525             SET_BX( context, HIWORD(W32S_WINE2APP(ptr)) );
526             SET_CX( context, LOWORD(W32S_WINE2APP(ptr)) );
527             SET_SI( context, HIWORD(W32S_WINE2APP(ptr)) );
528             SET_DI( context, LOWORD(W32S_WINE2APP(ptr)) );
529         }
530         break;
531
532     case 0x0502:  /* Free memory block */
533         TRACE("free memory block (0x%08lx)\n",
534                      W32S_APP2WINE(MAKELONG(DI_reg(context),SI_reg(context))));
535         DPMI_xfree( (void *)W32S_APP2WINE(MAKELONG(DI_reg(context), SI_reg(context))) );
536         break;
537
538     case 0x0503:  /* Resize memory block */
539         TRACE("resize memory block (0x%08lx,%ld)\n",
540                      W32S_APP2WINE(MAKELONG(DI_reg(context),SI_reg(context))),
541                      MAKELONG(CX_reg(context),BX_reg(context)));
542         if (!(ptr = (BYTE *)DPMI_xrealloc(
543                 (void *)W32S_APP2WINE(MAKELONG(DI_reg(context),SI_reg(context))),
544                 MAKELONG(CX_reg(context),BX_reg(context)))))
545         {
546             SET_AX( context, 0x8012 );  /* linear memory not available */
547             SET_CFLAG(context);
548         } else {
549             SET_BX( context, HIWORD(W32S_WINE2APP(ptr)) );
550             SET_CX( context, LOWORD(W32S_WINE2APP(ptr)) );
551             SET_SI( context, HIWORD(W32S_WINE2APP(ptr)) );
552             SET_DI( context, LOWORD(W32S_WINE2APP(ptr)) );
553         }
554         break;
555
556     case 0x0507:  /* Modify page attributes */
557         FIXME("modify page attributes unimplemented\n");
558         break;  /* Just ignore it */
559
560     case 0x0600:  /* Lock linear region */
561         FIXME("lock linear region unimplemented\n");
562         break;  /* Just ignore it */
563
564     case 0x0601:  /* Unlock linear region */
565         FIXME("unlock linear region unimplemented\n");
566         break;  /* Just ignore it */
567
568     case 0x0602:  /* Unlock real-mode region */
569         FIXME("unlock realmode region unimplemented\n");
570         break;  /* Just ignore it */
571
572     case 0x0603:  /* Lock real-mode region */
573         FIXME("lock realmode region unimplemented\n");
574         break;  /* Just ignore it */
575
576     case 0x0604:  /* Get page size */
577         TRACE("get pagesize\n");
578         SET_BX( context, 0 );
579         SET_CX( context, getpagesize() );
580         break;
581
582     case 0x0702:  /* Mark page as demand-paging candidate */
583         FIXME("mark page as demand-paging candidate\n");
584         break;  /* Just ignore it */
585
586     case 0x0703:  /* Discard page contents */
587         FIXME("discard page contents\n");
588         break;  /* Just ignore it */
589
590      case 0x0800:  /* Physical address mapping */
591         FIXME("map real to linear (0x%08lx)\n",MAKELONG(CX_reg(context),BX_reg(context)));
592          if(!(ptr=DOSMEM_MapRealToLinear(MAKELONG(CX_reg(context),BX_reg(context)))))
593          {
594              SET_AX( context, 0x8021 );
595              SET_CFLAG(context);
596          }
597          else
598          {
599              SET_BX( context, HIWORD(W32S_WINE2APP(ptr)) );
600              SET_CX( context, LOWORD(W32S_WINE2APP(ptr)) );
601              RESET_CFLAG(context);
602          }
603          break;
604
605     default:
606         INT_BARF( context, 0x31 );
607         SET_AX( context, 0x8001 );  /* unsupported function */
608         SET_CFLAG(context);
609         break;
610     }
611
612 }