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