Stub UrlCombineA and initial implementation of UrlCombineW.
[wine] / msdos / dosmem.c
1 /*
2  * DOS memory emulation
3  *
4  * Copyright 1995 Alexandre Julliard
5  * Copyright 1996 Marcus Meissner
6  */
7
8 #include "wine/port.h"
9
10 #include <signal.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <sys/types.h>
14 #ifdef HAVE_SYS_MMAN_H
15 # include <sys/mman.h>
16 #endif
17
18 #include "winbase.h"
19 #include "wine/winbase16.h"
20
21 #include "global.h"
22 #include "selectors.h"
23 #include "miscemu.h"
24 #include "vga.h"
25 #include "dosexe.h"
26 #include "debugtools.h"
27
28 DEFAULT_DEBUG_CHANNEL(dosmem);
29 DECLARE_DEBUG_CHANNEL(selector);
30
31 WORD DOSMEM_0000H;        /* segment at 0:0 */
32 WORD DOSMEM_BiosDataSeg;  /* BIOS data segment at 0x40:0 */
33 WORD DOSMEM_BiosSysSeg;   /* BIOS ROM segment at 0xf000:0 */
34
35 DWORD DOSMEM_CollateTable;
36
37 /* use 2 low bits of 'size' for the housekeeping */
38
39 #define DM_BLOCK_DEBUG          0xABE00000
40 #define DM_BLOCK_TERMINAL       0x00000001
41 #define DM_BLOCK_FREE           0x00000002
42 #define DM_BLOCK_MASK           0x001FFFFC
43
44 /*
45 #define __DOSMEM_DEBUG__
46  */
47
48 typedef struct {
49    unsigned     size;
50 } dosmem_entry;
51
52 typedef struct {
53   unsigned      blocks;
54   unsigned      free;
55 } dosmem_info;
56
57 #define NEXT_BLOCK(block) \
58         (dosmem_entry*)(((char*)(block)) + \
59          sizeof(dosmem_entry) + ((block)->size & DM_BLOCK_MASK))
60
61 #define VM_STUB(x) (0x90CF00CD|(x<<8)) /* INT x; IRET; NOP */
62 #define VM_STUB_SEGMENT 0xf000         /* BIOS segment */
63
64 /* DOS memory base */
65 static char *DOSMEM_dosmem;
66 /* DOS system base (for interrupt vector table and BIOS data area)
67  * ...should in theory (i.e. Windows) be equal to DOSMEM_dosmem (NULL),
68  * but is normally set to 0xf0000 in Wine to allow trapping of NULL pointers,
69  * and only relocated to NULL when absolutely necessary */
70 static char *DOSMEM_sysmem;
71
72 /* various real-mode code stubs */
73 WORD DOSMEM_wrap_seg;
74 WORD DOSMEM_xms_seg;
75 WORD DOSMEM_dpmi_seg;
76 WORD DOSMEM_dpmi_sel;
77
78 /***********************************************************************
79  *           DOSMEM_SystemBase
80  *
81  * Gets the virtual DOS memory base (interrupt table).
82  */
83 char *DOSMEM_SystemBase(void)
84 {
85     return DOSMEM_sysmem;
86 }
87
88 /***********************************************************************
89  *           DOSMEM_MemoryBase
90  *
91  * Gets the DOS memory base.
92  */
93 char *DOSMEM_MemoryBase(void)
94 {
95     return DOSMEM_dosmem;
96 }
97
98 /***********************************************************************
99  *           DOSMEM_MemoryTop
100  *
101  * Gets the DOS memory top.
102  */
103 static char *DOSMEM_MemoryTop(void)
104 {
105     return DOSMEM_dosmem+0x9FFFC; /* 640K */
106 }
107
108 /***********************************************************************
109  *           DOSMEM_InfoBlock
110  *
111  * Gets the DOS memory info block.
112  */
113 static dosmem_info *DOSMEM_InfoBlock(void)
114 {
115     return (dosmem_info*)(DOSMEM_dosmem+0x10000); /* 64K */
116 }
117
118 /***********************************************************************
119  *           DOSMEM_RootBlock
120  *
121  * Gets the DOS memory root block.
122  */
123 static dosmem_entry *DOSMEM_RootBlock(void)
124 {
125     /* first block has to be paragraph-aligned */
126     return (dosmem_entry*)(((char*)DOSMEM_InfoBlock()) +
127                            ((((sizeof(dosmem_info) + 0xf) & ~0xf) - sizeof(dosmem_entry))));
128 }
129
130 /***********************************************************************
131  *           DOSMEM_FillIsrTable
132  *
133  * Fill the interrupt table with fake BIOS calls to BIOSSEG (0xf000).
134  *
135  * NOTES:
136  * Linux normally only traps INTs performed from or destined to BIOSSEG
137  * for us to handle, if the int_revectored table is empty. Filling the
138  * interrupt table with calls to INT stubs in BIOSSEG allows DOS programs
139  * to hook interrupts, as well as use their familiar retf tricks to call
140  * them, AND let Wine handle any unhooked interrupts transparently.
141  */
142 static void DOSMEM_FillIsrTable(void)
143 {
144     SEGPTR *isr = (SEGPTR*)DOSMEM_sysmem;
145     int x;
146  
147     for (x=0; x<256; x++) isr[x]=MAKESEGPTR(VM_STUB_SEGMENT,x*4);
148
149
150 static void DOSMEM_MakeIsrStubs(void)
151 {
152     DWORD *stub = (DWORD*)(DOSMEM_dosmem + (VM_STUB_SEGMENT << 4));
153     int x;
154  
155     for (x=0; x<256; x++) stub[x]=VM_STUB(x);
156
157
158 /***********************************************************************
159  *           DOSMEM_InitDPMI
160  *
161  * Allocate the global DPMI RMCB wrapper.
162  */
163 static void DOSMEM_InitDPMI(void)
164 {
165     LPSTR ptr;
166
167     static const char wrap_code[]={
168      0xCD,0x31, /* int $0x31 */
169      0xCB       /* lret */
170     };
171
172     static const char enter_xms[]=
173     {
174         /* XMS hookable entry point */
175         0xEB,0x03,           /* jmp entry */
176         0x90,0x90,0x90,      /* nop;nop;nop */
177                              /* entry: */
178         /* real entry point */
179         /* for simplicity, we'll just use the same hook as DPMI below */
180         0xCD,0x31,           /* int $0x31 */
181         0xCB                 /* lret */
182     };
183
184     static const char enter_pm[]=
185     {
186         0x50,                /* pushw %ax */
187         0x52,                /* pushw %dx */
188         0x55,                /* pushw %bp */
189         0x89,0xE5,           /* movw %sp,%bp */
190         /* get return CS */
191         0x8B,0x56,0x08,      /* movw 8(%bp),%dx */
192         /* just call int 31 here to get into protected mode... */
193         /* it'll check whether it was called from dpmi_seg... */
194         0xCD,0x31,           /* int $0x31 */
195         /* we are now in the context of a 16-bit relay call */
196         /* need to fixup our stack;
197          * 16-bit relay return address will be lost, but we won't worry quite yet */
198         0x8E,0xD0,           /* movw %ax,%ss */
199         0x66,0x0F,0xB7,0xE5, /* movzwl %bp,%esp */
200         /* set return CS */
201         0x89,0x56,0x08,      /* movw %dx,8(%bp) */
202         0x5D,                /* popw %bp */
203         0x5A,                /* popw %dx */
204         0x58,                /* popw %ax */
205         0xCB                 /* lret */
206     };
207
208     ptr = DOSMEM_GetBlock( sizeof(wrap_code), &DOSMEM_wrap_seg );
209     memcpy( ptr, wrap_code, sizeof(wrap_code) );
210     ptr = DOSMEM_GetBlock( sizeof(enter_xms), &DOSMEM_xms_seg );
211     memcpy( ptr, enter_xms, sizeof(enter_xms) );
212     ptr = DOSMEM_GetBlock( sizeof(enter_pm), &DOSMEM_dpmi_seg );
213     memcpy( ptr, enter_pm, sizeof(enter_pm) );
214     DOSMEM_dpmi_sel = SELECTOR_AllocBlock( ptr, sizeof(enter_pm), WINE_LDT_FLAGS_CODE );
215 }
216
217 BIOSDATA * DOSMEM_BiosData()
218 {
219     return (BIOSDATA *)(DOSMEM_sysmem + 0x400);
220 }
221
222 BYTE * DOSMEM_BiosSys()
223 {
224     return DOSMEM_dosmem+0xf0000;
225 }
226
227 struct _DOS_LISTOFLISTS * DOSMEM_LOL()
228 {
229     return (struct _DOS_LISTOFLISTS *)DOSMEM_MapRealToLinear
230       (MAKESEGPTR(HIWORD(DOS_LOLSeg),0));
231 }
232
233 /***********************************************************************
234  *           DOSMEM_FillBiosSegments
235  *
236  * Fill the BIOS data segment with dummy values.
237  */
238 static void DOSMEM_FillBiosSegments(void)
239 {
240     BYTE *pBiosSys = DOSMEM_BiosSys();
241     BYTE *pBiosROMTable = pBiosSys+0xe6f5;
242     BIOSDATA *pBiosData = DOSMEM_BiosData();
243
244     /* bogus 0xe0xx addresses !! Adapt int 0x10/0x1b if change needed */
245     VIDEOFUNCTIONALITY *pVidFunc = (VIDEOFUNCTIONALITY *)(pBiosSys+0xe000);
246     VIDEOSTATE *pVidState = (VIDEOSTATE *)(pBiosSys+0xe010);
247     int i;
248
249       /* Clear all unused values */
250     memset( pBiosData, 0, sizeof(*pBiosData) );
251     memset( pVidFunc,  0, sizeof(*pVidFunc ) );
252     memset( pVidState, 0, sizeof(*pVidState) );
253
254     /* FIXME: should check the number of configured drives and ports */
255
256     pBiosData->Com1Addr             = 0x3f8;
257     pBiosData->Com2Addr             = 0x2f8;
258     pBiosData->Lpt1Addr             = 0x378;
259     pBiosData->Lpt2Addr             = 0x278;
260     pBiosData->InstalledHardware    = 0x5463;
261     pBiosData->MemSize              = 640;
262     pBiosData->NextKbdCharPtr       = 0x1e;
263     pBiosData->FirstKbdCharPtr      = 0x1e;
264     pBiosData->VideoMode            = 3;
265     pBiosData->VideoColumns         = 80;
266     pBiosData->VideoPageSize        = 80 * 25 * 2;
267     pBiosData->VideoPageStartAddr   = 0xb800;
268     pBiosData->VideoCtrlAddr        = 0x3d4;
269     pBiosData->Ticks                = INT1A_GetTicksSinceMidnight();
270     pBiosData->NbHardDisks          = 2;
271     pBiosData->KbdBufferStart       = 0x1e;
272     pBiosData->KbdBufferEnd         = 0x3e;
273     pBiosData->RowsOnScreenMinus1   = 23;
274     pBiosData->BytesPerChar         = 0x10;
275     pBiosData->ModeOptions          = 0x64;
276     pBiosData->FeatureBitsSwitches  = 0xf9;
277     pBiosData->VGASettings          = 0x51;
278     pBiosData->DisplayCombination   = 0x08;
279     pBiosData->DiskDataRate         = 0;
280
281     /* fill ROM configuration table (values from Award) */
282     *(pBiosROMTable+0x0)        = 0x08; /* number of bytes following LO */
283     *(pBiosROMTable+0x1)        = 0x00; /* number of bytes following HI */
284     *(pBiosROMTable+0x2)        = 0xfc; /* model */
285     *(pBiosROMTable+0x3)        = 0x01; /* submodel */
286     *(pBiosROMTable+0x4)        = 0x00; /* BIOS revision */
287     *(pBiosROMTable+0x5)        = 0x74; /* feature byte 1 */
288     *(pBiosROMTable+0x6)        = 0x00; /* feature byte 2 */
289     *(pBiosROMTable+0x7)        = 0x00; /* feature byte 3 */
290     *(pBiosROMTable+0x8)        = 0x00; /* feature byte 4 */
291     *(pBiosROMTable+0x9)        = 0x00; /* feature byte 5 */
292
293     
294     for (i = 0; i < 7; i++)
295         pVidFunc->ModeSupport[i] = 0xff;
296     
297     pVidFunc->ScanlineSupport     = 7;
298     pVidFunc->NumberCharBlocks    = 0;
299     pVidFunc->ActiveCharBlocks    = 0;
300     pVidFunc->MiscFlags           = 0x8ff;
301     pVidFunc->SavePointerFlags    = 0x3f;
302
303     pVidState->StaticFuncTable    = 0xf000e000;  /* FIXME: always real mode ? */
304     pVidState->VideoMode          = pBiosData->VideoMode; /* needs updates! */
305     pVidState->NumberColumns      = pBiosData->VideoColumns; /* needs updates! */
306     pVidState->RegenBufLen        = 0;
307     pVidState->RegenBufAddr       = 0;
308
309     for (i = 0; i < 8; i++)
310         pVidState->CursorPos[i] = 0;
311
312     pVidState->CursorType         = 0x0a0b;  /* start/end line */
313     pVidState->ActivePage         = 0;
314     pVidState->CRTCPort           = 0x3da;
315     pVidState->Port3x8            = 0;
316     pVidState->Port3x9            = 0;
317     pVidState->NumberRows         = 23;     /* number of rows - 1 */
318     pVidState->BytesPerChar       = 0x10;
319     pVidState->DCCActive          = pBiosData->DisplayCombination;
320     pVidState->DCCAlternate       = 0;
321     pVidState->NumberColors       = 16;
322     pVidState->NumberPages        = 1;
323     pVidState->NumberScanlines    = 3; /* (0,1,2,3) = (200,350,400,480) */
324     pVidState->CharBlockPrimary   = 0;
325     pVidState->CharBlockSecondary = 0;
326     pVidState->MiscFlags =
327                            (pBiosData->VGASettings & 0x0f)
328                          | ((pBiosData->ModeOptions & 1) << 4); /* cursor emulation */
329     pVidState->NonVGASupport      = 0;
330     pVidState->VideoMem           = (pBiosData->ModeOptions & 0x60 >> 5);
331     pVidState->SavePointerState   = 0;
332     pVidState->DisplayStatus      = 4;
333
334     /* BIOS date string */
335     strcpy((char *)pBiosSys+0xfff5, "13/01/99");
336
337     /* BIOS ID */
338     *(pBiosSys+0xfffe) = 0xfc;
339 }
340
341 /***********************************************************************
342  *           DOSMEM_InitCollateTable
343  *
344  * Initialises the collate table (character sorting, language dependent)
345  */
346 static void DOSMEM_InitCollateTable()
347 {
348         DWORD           x;
349         unsigned char   *tbl;
350         int             i;
351
352         x = GlobalDOSAlloc16(258);
353         DOSMEM_CollateTable = MAKELONG(0,(x>>16));
354         tbl = DOSMEM_MapRealToLinear(DOSMEM_CollateTable);
355         *(WORD*)tbl     = 0x100;
356         tbl += 2;
357         for ( i = 0; i < 0x100; i++) *tbl++ = i;
358 }
359
360 /***********************************************************************
361  *           DOSMEM_InitErrorTable
362  *
363  * Initialises the error tables (DOS 5+)
364  */
365 static void DOSMEM_InitErrorTable()
366 {
367 #if 0  /* no longer used */
368         DWORD           x;
369         char            *call;
370
371         /* We will use a snippet of real mode code that calls */
372         /* a WINE-only interrupt to handle moving the requested */
373         /* message into the buffer... */
374
375         /* FIXME - There is still something wrong... */
376
377         /* FIXME - Find hex values for opcodes...
378            
379            (On call, AX contains message number
380                      DI contains 'offset' (??)
381             Resturn, ES:DI points to counted string )
382
383            PUSH BX
384            MOV BX, AX
385            MOV AX, (arbitrary subfunction number)
386            INT (WINE-only interrupt)
387            POP BX
388            RET
389
390         */
391            
392         const int       code = 4;       
393         const int       buffer = 80; 
394         const int       SIZE_TO_ALLOCATE = code + buffer;
395
396         /* FIXME - Complete rewrite of the table system to save */
397         /* precious DOS space. Now, we return the 0001:???? as */
398         /* DOS 4+ (??, it seems to be the case in MS 7.10) treats that */
399         /* as a special case and programs will use the alternate */
400         /* interface (a farcall returned with INT 24 (AX = 0x122e, DL = */
401         /* 0x08) which lets us have a smaller memory footprint anyway. */
402  
403         x = GlobalDOSAlloc16(SIZE_TO_ALLOCATE);  
404
405         DOSMEM_ErrorCall = MAKELONG(0,(x>>16));
406         DOSMEM_ErrorBuffer = DOSMEM_ErrorCall + code;
407
408         call = DOSMEM_MapRealToLinear(DOSMEM_ErrorCall);
409
410         memset(call, 0, SIZE_TO_ALLOCATE);
411 #endif
412         /* Fixme - Copy assembly into buffer here */        
413 }
414
415 /***********************************************************************
416  *           DOSMEM_InitMemory
417  *
418  * Initialises the DOS memory structures.
419  */
420 static void DOSMEM_InitMemory(void)
421 {
422    /* Low 64Kb are reserved for DOS/BIOS so the useable area starts at
423     * 1000:0000 and ends at 9FFF:FFEF. */
424
425     dosmem_info*        info_block = DOSMEM_InfoBlock();
426     dosmem_entry*       root_block = DOSMEM_RootBlock();
427     dosmem_entry*       dm;
428
429     root_block->size = DOSMEM_MemoryTop() - (((char*)root_block) + sizeof(dosmem_entry));
430
431     info_block->blocks = 0;
432     info_block->free = root_block->size;
433
434     dm = NEXT_BLOCK(root_block);
435     dm->size = DM_BLOCK_TERMINAL;
436     root_block->size |= DM_BLOCK_FREE 
437 #ifdef __DOSMEM_DEBUG__
438                      | DM_BLOCK_DEBUG
439 #endif
440                      ;
441 }
442
443 /**********************************************************************
444  *              setup_dos_mem
445  *
446  * Setup the first megabyte for DOS memory access
447  */
448 static void setup_dos_mem( int dos_init )
449 {
450     int sys_offset = 0;
451     int page_size = getpagesize();
452     void *addr = wine_anon_mmap( (void *)page_size, 0x110000-page_size,
453                                  PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
454     if (addr == (void *)page_size)  /* we got what we wanted */
455     {
456         /* now map from address 0 */
457         addr = wine_anon_mmap( NULL, 0x110000, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_FIXED );
458         if (addr)
459         {
460             ERR("MAP_FIXED failed at address 0 for DOS address space\n" );
461             ExitProcess(1);
462         }
463
464         /* inform the memory manager that there is a mapping here */
465         VirtualAlloc( addr, 0x110000, MEM_RESERVE | MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
466
467         /* protect the first 64K to catch NULL pointers */
468         if (!dos_init)
469         {
470             VirtualProtect( addr, 0x10000, PAGE_NOACCESS, NULL );
471             /* move the BIOS and ISR area from 0x00000 to 0xf0000 */
472             sys_offset += 0xf0000;
473         }
474     }
475     else
476     {
477         ERR("Cannot use first megabyte for DOS address space, please report\n" );
478         if (dos_init) ExitProcess(1);
479         /* allocate the DOS area somewhere else */
480         addr = VirtualAlloc( NULL, 0x110000, MEM_COMMIT, PAGE_EXECUTE_READWRITE );
481         if (!addr)
482         {
483             ERR( "Cannot allocate DOS memory\n" );
484             ExitProcess(1);
485         }
486     }
487     DOSMEM_dosmem = addr;
488     DOSMEM_sysmem = (char*)addr + sys_offset;
489 }
490
491
492 /***********************************************************************
493  *           DOSMEM_Init
494  *
495  * Create the dos memory segments, and store them into the KERNEL
496  * exported values.
497  */
498 BOOL DOSMEM_Init(BOOL dos_init)
499 {
500     static int already_done, already_mapped;
501
502     if (!already_done)
503     {
504         setup_dos_mem( dos_init );
505
506         DOSMEM_0000H = GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_sysmem,
507                                            0x10000, 0, WINE_LDT_FLAGS_DATA );
508         DOSMEM_BiosDataSeg = GLOBAL_CreateBlock(GMEM_FIXED,DOSMEM_sysmem + 0x400,
509                                                 0x100, 0, WINE_LDT_FLAGS_DATA );
510         DOSMEM_BiosSysSeg = GLOBAL_CreateBlock(GMEM_FIXED,DOSMEM_dosmem+0xf0000,
511                                                0x10000, 0, WINE_LDT_FLAGS_DATA );
512         DOSMEM_FillBiosSegments();
513         DOSMEM_FillIsrTable();
514         DOSMEM_InitMemory();
515         DOSMEM_InitCollateTable();
516         DOSMEM_InitErrorTable();
517         DOSMEM_InitDPMI();
518         DOSDEV_InstallDOSDevices();
519         already_done = 1;
520     }
521     else if (dos_init && !already_mapped)
522     {
523         if (DOSMEM_dosmem)
524         {
525             ERR( "Needs access to the first megabyte for DOS mode\n" );
526             ExitProcess(1);
527         }
528         MESSAGE( "Warning: unprotecting the first 64KB of memory to allow real-mode calls.\n"
529                  "         NULL pointer accesses will no longer be caught.\n" );
530         VirtualProtect( NULL, 0x10000, PAGE_EXECUTE_READWRITE, NULL );
531         /* copy the BIOS and ISR area down */
532         memcpy( DOSMEM_dosmem, DOSMEM_sysmem, 0x400 + 0x100 );
533         DOSMEM_sysmem = DOSMEM_dosmem;
534         SetSelectorBase( DOSMEM_0000H, 0 );
535         SetSelectorBase( DOSMEM_BiosDataSeg, 0x400 );
536         /* we may now need the actual interrupt stubs, and since we've just moved the
537          * interrupt vector table away, we can fill the area with stubs instead... */
538         DOSMEM_MakeIsrStubs();
539         already_mapped = 1;
540     }
541     return TRUE;
542 }
543
544
545 /***********************************************************************
546  *           DOSMEM_Tick
547  *
548  * Increment the BIOS tick counter. Called by timer signal handler.
549  */
550 void DOSMEM_Tick( WORD timer )
551 {
552     BIOSDATA *pBiosData = DOSMEM_BiosData();
553     if (pBiosData) pBiosData->Ticks++;
554 }
555
556 /***********************************************************************
557  *           DOSMEM_GetBlock
558  *
559  * Carve a chunk of the DOS memory block (without selector).
560  */
561 LPVOID DOSMEM_GetBlock(UINT size, UINT16* pseg)
562 {
563    UINT          blocksize;
564    char         *block = NULL;
565    dosmem_info  *info_block = DOSMEM_InfoBlock();
566    dosmem_entry *dm;
567 #ifdef __DOSMEM_DEBUG_
568    dosmem_entry *prev = NULL;
569 #endif
570  
571    if( size > info_block->free ) return NULL;
572    dm = DOSMEM_RootBlock();
573
574    while (dm && dm->size != DM_BLOCK_TERMINAL)
575    {
576 #ifdef __DOSMEM_DEBUG__
577        if( (dm->size & DM_BLOCK_DEBUG) != DM_BLOCK_DEBUG )
578        {
579             WARN("MCB overrun! [prev = 0x%08x]\n", 4 + (UINT)prev);
580             return NULL;
581        }
582        prev = dm;
583 #endif
584        if( dm->size & DM_BLOCK_FREE )
585        {
586            dosmem_entry  *next = NEXT_BLOCK(dm);
587
588            while( next->size & DM_BLOCK_FREE ) /* collapse free blocks */
589            {
590                dm->size += sizeof(dosmem_entry) + (next->size & DM_BLOCK_MASK);
591                next->size = (DM_BLOCK_FREE | DM_BLOCK_TERMINAL);
592                next = NEXT_BLOCK(dm);
593            }
594
595            blocksize = dm->size & DM_BLOCK_MASK;
596            if( blocksize >= size )
597            {
598                block = ((char*)dm) + sizeof(dosmem_entry);
599                if( blocksize - size > 0x20 )
600                {
601                    /* split dm so that the next one stays
602                     * paragraph-aligned (and dm loses free bit) */
603
604                    dm->size = (((size + 0xf + sizeof(dosmem_entry)) & ~0xf) -
605                                               sizeof(dosmem_entry));
606                    next = (dosmem_entry*)(((char*)dm) + 
607                            sizeof(dosmem_entry) + dm->size);
608                    next->size = (blocksize - (dm->size + 
609                            sizeof(dosmem_entry))) | DM_BLOCK_FREE 
610 #ifdef __DOSMEM_DEBUG__
611                                                   | DM_BLOCK_DEBUG
612 #endif
613                                                   ;
614                } else dm->size &= DM_BLOCK_MASK;
615
616                info_block->blocks++;
617                info_block->free -= dm->size;
618                if( pseg ) *pseg = (block - DOSMEM_dosmem) >> 4;
619 #ifdef __DOSMEM_DEBUG__
620                dm->size |= DM_BLOCK_DEBUG;
621 #endif
622                break;
623            }
624            dm = next;
625        }
626        else dm = NEXT_BLOCK(dm);
627    }
628    return (LPVOID)block;
629 }
630
631 /***********************************************************************
632  *           DOSMEM_FreeBlock
633  */
634 BOOL DOSMEM_FreeBlock(void* ptr)
635 {
636    dosmem_info  *info_block = DOSMEM_InfoBlock();
637
638    if( ptr >= (void*)(((char*)DOSMEM_RootBlock()) + sizeof(dosmem_entry)) &&
639        ptr < (void*)DOSMEM_MemoryTop() && !((((char*)ptr)
640                   - DOSMEM_dosmem) & 0xf) )
641    {
642        dosmem_entry  *dm = (dosmem_entry*)(((char*)ptr) - sizeof(dosmem_entry));
643
644        if( !(dm->size & (DM_BLOCK_FREE | DM_BLOCK_TERMINAL))
645 #ifdef __DOSMEM_DEBUG__
646          && ((dm->size & DM_BLOCK_DEBUG) == DM_BLOCK_DEBUG )
647 #endif
648          )
649        {
650              info_block->blocks--;
651              info_block->free += dm->size;
652
653              dm->size |= DM_BLOCK_FREE;
654              return TRUE;
655        }
656    }
657    return FALSE;
658 }
659
660 /***********************************************************************
661  *           DOSMEM_ResizeBlock
662  */
663 LPVOID DOSMEM_ResizeBlock(void* ptr, UINT size, UINT16* pseg)
664 {
665    char         *block = NULL;
666    dosmem_info  *info_block = DOSMEM_InfoBlock();
667
668    if( ptr >= (void*)(((char*)DOSMEM_RootBlock()) + sizeof(dosmem_entry)) &&
669        ptr < (void*)DOSMEM_MemoryTop() && !((((char*)ptr)
670                   - DOSMEM_dosmem) & 0xf) )
671    {
672        dosmem_entry  *dm = (dosmem_entry*)(((char*)ptr) - sizeof(dosmem_entry));
673
674        if( pseg ) *pseg = ((char*)ptr - DOSMEM_dosmem) >> 4;
675
676        if( !(dm->size & (DM_BLOCK_FREE | DM_BLOCK_TERMINAL))
677          )
678        {
679              dosmem_entry  *next = NEXT_BLOCK(dm);
680              UINT blocksize, orgsize = dm->size & DM_BLOCK_MASK;
681
682              while( next->size & DM_BLOCK_FREE ) /* collapse free blocks */
683              {
684                  dm->size += sizeof(dosmem_entry) + (next->size & DM_BLOCK_MASK);
685                  next->size = (DM_BLOCK_FREE | DM_BLOCK_TERMINAL);
686                  next = NEXT_BLOCK(dm);
687              }
688
689              blocksize = dm->size & DM_BLOCK_MASK;
690              if (blocksize >= size)
691              {
692                  block = ((char*)dm) + sizeof(dosmem_entry);
693                  if( blocksize - size > 0x20 )
694                  {
695                      /* split dm so that the next one stays
696                       * paragraph-aligned (and next gains free bit) */
697
698                      dm->size = (((size + 0xf + sizeof(dosmem_entry)) & ~0xf) -
699                                                 sizeof(dosmem_entry));
700                      next = (dosmem_entry*)(((char*)dm) + 
701                              sizeof(dosmem_entry) + dm->size);
702                      next->size = (blocksize - (dm->size + 
703                              sizeof(dosmem_entry))) | DM_BLOCK_FREE 
704                                                     ;
705                  } else dm->size &= DM_BLOCK_MASK;
706
707                  info_block->free += orgsize - dm->size;
708              } else {
709                  /* the collapse didn't help, try getting a new block */
710                  block = DOSMEM_GetBlock(size, pseg);
711                  if (block) {
712                      /* we got one, copy the old data there (we do need to, right?) */
713                      memcpy(block, ((char*)dm) + sizeof(dosmem_entry),
714                                    (size<orgsize) ? size : orgsize);
715                      /* free old block */
716                      info_block->blocks--;
717                      info_block->free += dm->size;
718
719                      dm->size |= DM_BLOCK_FREE;
720                  } else {
721                      /* and Bill Gates said 640K should be enough for everyone... */
722
723                      /* need to split original and collapsed blocks apart again,
724                       * and free the collapsed blocks again, before exiting */
725                      if( blocksize - orgsize > 0x20 )
726                      {
727                          /* split dm so that the next one stays
728                           * paragraph-aligned (and next gains free bit) */
729
730                          dm->size = (((orgsize + 0xf + sizeof(dosmem_entry)) & ~0xf) -
731                                                        sizeof(dosmem_entry));
732                          next = (dosmem_entry*)(((char*)dm) + 
733                                  sizeof(dosmem_entry) + dm->size);
734                          next->size = (blocksize - (dm->size + 
735                                  sizeof(dosmem_entry))) | DM_BLOCK_FREE 
736                                                         ;
737                      } else dm->size &= DM_BLOCK_MASK;
738                  }
739              }
740        }
741    }
742    return (LPVOID)block;
743 }
744
745
746 /***********************************************************************
747  *           DOSMEM_Available
748  */
749 UINT DOSMEM_Available(void)
750 {
751    UINT          blocksize, available = 0;
752    dosmem_entry *dm;
753    
754    dm = DOSMEM_RootBlock();
755
756    while (dm && dm->size != DM_BLOCK_TERMINAL)
757    {
758 #ifdef __DOSMEM_DEBUG__
759        if( (dm->size & DM_BLOCK_DEBUG) != DM_BLOCK_DEBUG )
760        {
761             WARN("MCB overrun! [prev = 0x%08x]\n", 4 + (UINT)prev);
762             return NULL;
763        }
764        prev = dm;
765 #endif
766        if( dm->size & DM_BLOCK_FREE )
767        {
768            dosmem_entry  *next = NEXT_BLOCK(dm);
769
770            while( next->size & DM_BLOCK_FREE ) /* collapse free blocks */
771            {
772                dm->size += sizeof(dosmem_entry) + (next->size & DM_BLOCK_MASK);
773                next->size = (DM_BLOCK_FREE | DM_BLOCK_TERMINAL);
774                next = NEXT_BLOCK(dm);
775            }
776
777            blocksize = dm->size & DM_BLOCK_MASK;
778            if ( blocksize > available ) available = blocksize;
779            dm = next;
780        }
781        else dm = NEXT_BLOCK(dm);
782    }
783    return available;
784 }
785
786
787 /***********************************************************************
788  *           DOSMEM_MapLinearToDos
789  *
790  * Linear address to the DOS address space.
791  */
792 UINT DOSMEM_MapLinearToDos(LPVOID ptr)
793 {
794     if (((char*)ptr >= DOSMEM_dosmem) &&
795         ((char*)ptr < DOSMEM_dosmem + 0x100000))
796           return (UINT)ptr - (UINT)DOSMEM_dosmem;
797     return (UINT)ptr;
798 }
799
800
801 /***********************************************************************
802  *           DOSMEM_MapDosToLinear
803  *
804  * DOS linear address to the linear address space.
805  */
806 LPVOID DOSMEM_MapDosToLinear(UINT ptr)
807 {
808     if (ptr < 0x100000) return (LPVOID)(ptr + (UINT)DOSMEM_dosmem);
809     return (LPVOID)ptr;
810 }
811
812
813 /***********************************************************************
814  *           DOSMEM_MapRealToLinear
815  *
816  * Real mode DOS address into a linear pointer
817  */
818 LPVOID DOSMEM_MapRealToLinear(DWORD x)
819 {
820    LPVOID       lin;
821
822    lin=DOSMEM_dosmem+(x&0xffff)+(((x&0xffff0000)>>16)*16);
823    TRACE_(selector)("(0x%08lx) returns 0x%p.\n", x, lin );
824    return lin;
825 }
826
827 /***********************************************************************
828  *           DOSMEM_AllocSelector
829  *
830  * Allocates a protected mode selector for a realmode segment.
831  */
832 WORD DOSMEM_AllocSelector(WORD realsel)
833 {
834         HMODULE16 hModule = GetModuleHandle16("KERNEL");
835         WORD    sel;
836
837         sel=GLOBAL_CreateBlock( GMEM_FIXED, DOSMEM_dosmem+realsel*16, 0x10000,
838                                 hModule, WINE_LDT_FLAGS_DATA );
839         TRACE_(selector)("(0x%04x) returns 0x%04x.\n", realsel,sel);
840         return sel;
841 }
842