Yet another documentation/message text patch.
[wine] / memory / heap.c
1 /*
2  * Win32 heap functions
3  *
4  * Copyright 1996 Alexandre Julliard
5  * Copyright 1998 Ulrich Weigand
6  */
7
8 #include <assert.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include "config.h"
13 #include "wine/winbase16.h"
14 #include "wine/unicode.h"
15 #include "selectors.h"
16 #include "global.h"
17 #include "winbase.h"
18 #include "winerror.h"
19 #include "winnt.h"
20 #include "heap.h"
21 #include "toolhelp.h"
22 #include "debugtools.h"
23 #include "winnls.h"
24
25 DEFAULT_DEBUG_CHANNEL(heap);
26
27 /* Note: the heap data structures are based on what Pietrek describes in his
28  * book 'Windows 95 System Programming Secrets'. The layout is not exactly
29  * the same, but could be easily adapted if it turns out some programs
30  * require it.
31  */
32
33 typedef struct tagARENA_INUSE
34 {
35     DWORD  size;                    /* Block size; must be the first field */
36     WORD   magic;                   /* Magic number */
37     WORD   threadId;                /* Allocating thread id */
38     void  *callerEIP;               /* EIP of caller upon allocation */
39 } ARENA_INUSE;
40
41 typedef struct tagARENA_FREE
42 {
43     DWORD                 size;     /* Block size; must be the first field */
44     WORD                  magic;    /* Magic number */
45     WORD                  threadId; /* Freeing thread id */
46     struct tagARENA_FREE *next;     /* Next free arena */
47     struct tagARENA_FREE *prev;     /* Prev free arena */
48 } ARENA_FREE;
49
50 #define ARENA_FLAG_FREE        0x00000001  /* flags OR'ed with arena size */
51 #define ARENA_FLAG_PREV_FREE   0x00000002
52 #define ARENA_SIZE_MASK        0xfffffffc
53 #define ARENA_INUSE_MAGIC      0x4842      /* Value for arena 'magic' field */
54 #define ARENA_FREE_MAGIC       0x4846      /* Value for arena 'magic' field */
55
56 #define ARENA_INUSE_FILLER     0x55
57 #define ARENA_FREE_FILLER      0xaa
58
59 #define QUIET                  1           /* Suppress messages  */
60 #define NOISY                  0           /* Report all errors  */
61
62 #define HEAP_NB_FREE_LISTS   4   /* Number of free lists */
63
64 /* Max size of the blocks on the free lists */
65 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
66 {
67     0x20, 0x80, 0x200, 0xffffffff
68 };
69
70 typedef struct
71 {
72     DWORD       size;
73     ARENA_FREE  arena;
74 } FREE_LIST_ENTRY;
75
76 struct tagHEAP;
77
78 typedef struct tagSUBHEAP
79 {
80     DWORD               size;       /* Size of the whole sub-heap */
81     DWORD               commitSize; /* Committed size of the sub-heap */
82     DWORD               headerSize; /* Size of the heap header */
83     struct tagSUBHEAP  *next;       /* Next sub-heap */
84     struct tagHEAP     *heap;       /* Main heap structure */
85     DWORD               magic;      /* Magic number */
86     WORD                selector;   /* Selector for HEAP_WINE_SEGPTR heaps */
87 } SUBHEAP;
88
89 #define SUBHEAP_MAGIC    ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
90
91 typedef struct tagHEAP
92 {
93     SUBHEAP          subheap;       /* First sub-heap */
94     struct tagHEAP  *next;          /* Next heap for this process */
95     FREE_LIST_ENTRY  freeList[HEAP_NB_FREE_LISTS];  /* Free lists */
96     CRITICAL_SECTION critSection;   /* Critical section for serialization */
97     DWORD            flags;         /* Heap flags */
98     DWORD            magic;         /* Magic number */
99 } HEAP;
100
101 #define HEAP_MAGIC       ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
102
103 #define HEAP_DEF_SIZE        0x110000   /* Default heap size = 1Mb + 64Kb */
104 #define HEAP_MIN_BLOCK_SIZE  (8+sizeof(ARENA_FREE))  /* Min. heap block size */
105 #define COMMIT_MASK          0xffff  /* bitmask for commit/decommit granularity */
106
107 static HEAP *systemHeap;   /* globally shared heap */
108 static HEAP *processHeap;  /* main process heap */
109 static HEAP *segptrHeap;   /* main segptr heap */
110 static HEAP *firstHeap;    /* head of secondary heaps list */
111
112 /* address where we try to map the system heap */
113 #define SYSTEM_HEAP_BASE  ((void*)0x65430000)
114
115 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
116
117 #ifdef __GNUC__
118 #define GET_EIP()    (__builtin_return_address(0))
119 #define SET_EIP(ptr) ((ARENA_INUSE*)(ptr) - 1)->callerEIP = GET_EIP()
120 #else
121 #define GET_EIP()    0
122 #define SET_EIP(ptr) /* nothing */
123 #endif  /* __GNUC__ */
124
125 /***********************************************************************
126  *           HEAP_Dump
127  */
128 void HEAP_Dump( HEAP *heap )
129 {
130     int i;
131     SUBHEAP *subheap;
132     char *ptr;
133
134     DPRINTF( "Heap: %08lx\n", (DWORD)heap );
135     DPRINTF( "Next: %08lx  Sub-heaps: %08lx",
136           (DWORD)heap->next, (DWORD)&heap->subheap );
137     subheap = &heap->subheap;
138     while (subheap->next)
139     {
140         DPRINTF( " -> %08lx", (DWORD)subheap->next );
141         subheap = subheap->next;
142     }
143
144     DPRINTF( "\nFree lists:\n Block   Stat   Size    Id\n" );
145     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
146         DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
147               (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
148               heap->freeList[i].arena.threadId,
149               (DWORD)heap->freeList[i].arena.prev,
150               (DWORD)heap->freeList[i].arena.next );
151
152     subheap = &heap->subheap;
153     while (subheap)
154     {
155         DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
156         DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
157               (DWORD)subheap, subheap->size, subheap->commitSize );
158         
159         DPRINTF( "\n Block   Stat   Size    Id\n" );
160         ptr = (char*)subheap + subheap->headerSize;
161         while (ptr < (char *)subheap + subheap->size)
162         {
163             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
164             {
165                 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
166                 DPRINTF( "%08lx free %08lx %04x prev=%08lx next=%08lx\n",
167                       (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
168                       pArena->threadId, (DWORD)pArena->prev,
169                       (DWORD)pArena->next);
170                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
171                 arenaSize += sizeof(ARENA_FREE);
172                 freeSize += pArena->size & ARENA_SIZE_MASK;
173             }
174             else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
175             {
176                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
177                 DPRINTF( "%08lx Used %08lx %04x back=%08lx EIP=%p\n",
178                       (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
179                       pArena->threadId, *((DWORD *)pArena - 1),
180                       pArena->callerEIP );
181                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
182                 arenaSize += sizeof(ARENA_INUSE);
183                 usedSize += pArena->size & ARENA_SIZE_MASK;
184             }
185             else
186             {
187                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
188                 DPRINTF( "%08lx used %08lx %04x EIP=%p\n",
189                       (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
190                       pArena->threadId, pArena->callerEIP );
191                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
192                 arenaSize += sizeof(ARENA_INUSE);
193                 usedSize += pArena->size & ARENA_SIZE_MASK;
194             }
195         }
196         DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
197               subheap->size, subheap->commitSize, freeSize, usedSize,
198               arenaSize, (arenaSize * 100) / subheap->size );
199         subheap = subheap->next;
200     }
201 }
202
203
204 /***********************************************************************
205  *           HEAP_GetPtr
206  * RETURNS
207  *      Pointer to the heap
208  *      NULL: Failure
209  */
210 static HEAP *HEAP_GetPtr(
211              HANDLE heap /* [in] Handle to the heap */
212 ) {
213     HEAP *heapPtr = (HEAP *)heap;
214     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
215     {
216         ERR("Invalid heap %08x!\n", heap );
217         SetLastError( ERROR_INVALID_HANDLE );
218         return NULL;
219     }
220     if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
221     {
222         HEAP_Dump( heapPtr );
223         assert( FALSE );
224         SetLastError( ERROR_INVALID_HANDLE );
225         return NULL;
226     }
227     return heapPtr;
228 }
229
230
231 /***********************************************************************
232  *           HEAP_InsertFreeBlock
233  *
234  * Insert a free block into the free list.
235  */
236 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
237 {
238     FREE_LIST_ENTRY *pEntry = heap->freeList;
239     while (pEntry->size < pArena->size) pEntry++;
240     pArena->size      |= ARENA_FLAG_FREE;
241     pArena->next       = pEntry->arena.next;
242     pArena->next->prev = pArena;
243     pArena->prev       = &pEntry->arena;
244     pEntry->arena.next = pArena;
245 }
246
247
248 /***********************************************************************
249  *           HEAP_FindSubHeap
250  * Find the sub-heap containing a given address.
251  *
252  * RETURNS
253  *      Pointer: Success
254  *      NULL: Failure
255  */
256 static SUBHEAP *HEAP_FindSubHeap(
257                 HEAP *heap, /* [in] Heap pointer */
258                 LPCVOID ptr /* [in] Address */
259 ) {
260     SUBHEAP *sub = &heap->subheap;
261     while (sub)
262     {
263         if (((char *)ptr >= (char *)sub) &&
264             ((char *)ptr < (char *)sub + sub->size)) return sub;
265         sub = sub->next;
266     }
267     return NULL;
268 }
269
270
271 /***********************************************************************
272  *           HEAP_Commit
273  *
274  * Make sure the heap storage is committed up to (not including) ptr.
275  */
276 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
277 {
278     DWORD size = (DWORD)((char *)ptr - (char *)subheap);
279     size = (size + COMMIT_MASK) & ~COMMIT_MASK;
280     if (size > subheap->size) size = subheap->size;
281     if (size <= subheap->commitSize) return TRUE;
282     if (!VirtualAlloc( (char *)subheap + subheap->commitSize,
283                        size - subheap->commitSize, MEM_COMMIT,
284                        PAGE_EXECUTE_READWRITE))
285     {
286         WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
287                  size - subheap->commitSize,
288                  (DWORD)((char *)subheap + subheap->commitSize),
289                  (DWORD)subheap->heap );
290         return FALSE;
291     }
292     subheap->commitSize = size;
293     return TRUE;
294 }
295
296
297 /***********************************************************************
298  *           HEAP_Decommit
299  *
300  * If possible, decommit the heap storage from (including) 'ptr'.
301  */
302 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
303 {
304     DWORD size = (DWORD)((char *)ptr - (char *)subheap);
305     /* round to next block and add one full block */
306     size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
307     if (size >= subheap->commitSize) return TRUE;
308     if (!VirtualFree( (char *)subheap + size,
309                       subheap->commitSize - size, MEM_DECOMMIT ))
310     {
311         WARN("Could not decommit %08lx bytes at %08lx for heap %08lx\n",
312                  subheap->commitSize - size,
313                  (DWORD)((char *)subheap + size),
314                  (DWORD)subheap->heap );
315         return FALSE;
316     }
317     subheap->commitSize = size;
318     return TRUE;
319 }
320
321
322 /***********************************************************************
323  *           HEAP_CreateFreeBlock
324  *
325  * Create a free block at a specified address. 'size' is the size of the
326  * whole block, including the new arena.
327  */
328 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
329 {
330     ARENA_FREE *pFree;
331
332     /* Create a free arena */
333
334     pFree = (ARENA_FREE *)ptr;
335     pFree->threadId = GetCurrentTask();
336     pFree->magic = ARENA_FREE_MAGIC;
337
338     /* If debugging, erase the freed block content */
339
340     if (TRACE_ON(heap))
341     {
342         char *pEnd = (char *)ptr + size;
343         if (pEnd > (char *)subheap + subheap->commitSize)
344             pEnd = (char *)subheap + subheap->commitSize;
345         if (pEnd > (char *)(pFree + 1))
346             memset( pFree + 1, ARENA_FREE_FILLER, pEnd - (char *)(pFree + 1) );
347     }
348
349     /* Check if next block is free also */
350
351     if (((char *)ptr + size < (char *)subheap + subheap->size) &&
352         (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
353     {
354         /* Remove the next arena from the free list */
355         ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
356         pNext->next->prev = pNext->prev;
357         pNext->prev->next = pNext->next;
358         size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
359         if (TRACE_ON(heap))
360             memset( pNext, ARENA_FREE_FILLER, sizeof(ARENA_FREE) );
361     }
362
363     /* Set the next block PREV_FREE flag and pointer */
364
365     if ((char *)ptr + size < (char *)subheap + subheap->size)
366     {
367         DWORD *pNext = (DWORD *)((char *)ptr + size);
368         *pNext |= ARENA_FLAG_PREV_FREE;
369         *(ARENA_FREE **)(pNext - 1) = pFree;
370     }
371
372     /* Last, insert the new block into the free list */
373
374     pFree->size = size - sizeof(*pFree);
375     HEAP_InsertFreeBlock( subheap->heap, pFree );
376 }
377
378
379 /***********************************************************************
380  *           HEAP_MakeInUseBlockFree
381  *
382  * Turn an in-use block into a free block. Can also decommit the end of
383  * the heap, and possibly even free the sub-heap altogether.
384  */
385 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
386 {
387     ARENA_FREE *pFree;
388     DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
389
390     /* Check if we can merge with previous block */
391
392     if (pArena->size & ARENA_FLAG_PREV_FREE)
393     {
394         pFree = *((ARENA_FREE **)pArena - 1);
395         size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
396         /* Remove it from the free list */
397         pFree->next->prev = pFree->prev;
398         pFree->prev->next = pFree->next;
399     }
400     else pFree = (ARENA_FREE *)pArena;
401
402     /* Create a free block */
403
404     HEAP_CreateFreeBlock( subheap, pFree, size );
405     size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
406     if ((char *)pFree + size < (char *)subheap + subheap->size)
407         return;  /* Not the last block, so nothing more to do */
408
409     /* Free the whole sub-heap if it's empty and not the original one */
410
411     if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
412         (subheap != &subheap->heap->subheap))
413     {
414         SUBHEAP *pPrev = &subheap->heap->subheap;
415         /* Remove the free block from the list */
416         pFree->next->prev = pFree->prev;
417         pFree->prev->next = pFree->next;
418         /* Remove the subheap from the list */
419         while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
420         if (pPrev) pPrev->next = subheap->next;
421         /* Free the memory */
422         subheap->magic = 0;
423         if (subheap->selector) FreeSelector16( subheap->selector );
424         VirtualFree( subheap, 0, MEM_RELEASE );
425         return;
426     }
427     
428     /* Decommit the end of the heap */
429
430     if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
431 }
432
433
434 /***********************************************************************
435  *           HEAP_ShrinkBlock
436  *
437  * Shrink an in-use block.
438  */
439 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
440 {
441     if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
442     {
443         HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
444                               (pArena->size & ARENA_SIZE_MASK) - size );
445         /* assign size plus previous arena flags */
446         pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
447     }
448     else
449     {
450         /* Turn off PREV_FREE flag in next block */
451         char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
452         if (pNext < (char *)subheap + subheap->size)
453             *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
454     }
455 }
456
457 /***********************************************************************
458  *           HEAP_InitSubHeap
459  */
460 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
461                                 DWORD commitSize, DWORD totalSize )
462 {
463     SUBHEAP *subheap = (SUBHEAP *)address;
464     WORD selector = 0;
465     FREE_LIST_ENTRY *pEntry;
466     int i;
467
468     /* Commit memory */
469
470     if (flags & HEAP_SHARED)
471         commitSize = totalSize;  /* always commit everything in a shared heap */
472     if (!VirtualAlloc(address, commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
473     {
474         WARN("Could not commit %08lx bytes for sub-heap %08lx\n",
475                    commitSize, (DWORD)address );
476         return FALSE;
477     }
478
479     /* Allocate a selector if needed */
480
481     if (flags & HEAP_WINE_SEGPTR)
482     {
483         unsigned char selflags = WINE_LDT_FLAGS_DATA;
484
485         if (flags & (HEAP_WINE_CODESEG | HEAP_WINE_CODE16SEG))
486             selflags = WINE_LDT_FLAGS_CODE;
487         if (flags & HEAP_WINE_CODESEG)
488             selflags |= WINE_LDT_FLAGS_32BIT;
489         selector = SELECTOR_AllocBlock( address, totalSize, selflags );
490         if (!selector)
491         {
492             ERR("Could not allocate selector\n" );
493             return FALSE;
494         }
495     }
496
497     /* Fill the sub-heap structure */
498
499     subheap->heap       = heap;
500     subheap->selector   = selector;
501     subheap->size       = totalSize;
502     subheap->commitSize = commitSize;
503     subheap->magic      = SUBHEAP_MAGIC;
504
505     if ( subheap != (SUBHEAP *)heap )
506     {
507         /* If this is a secondary subheap, insert it into list */
508
509         subheap->headerSize = sizeof(SUBHEAP);
510         subheap->next       = heap->subheap.next;
511         heap->subheap.next  = subheap;
512     }
513     else
514     {
515         /* If this is a primary subheap, initialize main heap */
516
517         subheap->headerSize = sizeof(HEAP);
518         subheap->next       = NULL;
519         heap->next          = NULL;
520         heap->flags         = flags;
521         heap->magic         = HEAP_MAGIC;
522
523         /* Build the free lists */
524
525         for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
526         {
527             pEntry->size           = HEAP_freeListSizes[i];
528             pEntry->arena.size     = 0 | ARENA_FLAG_FREE;
529             pEntry->arena.next     = i < HEAP_NB_FREE_LISTS-1 ?
530                          &heap->freeList[i+1].arena : &heap->freeList[0].arena;
531             pEntry->arena.prev     = i ? &heap->freeList[i-1].arena : 
532                                    &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
533             pEntry->arena.threadId = 0;
534             pEntry->arena.magic    = ARENA_FREE_MAGIC;
535         }
536
537         /* Initialize critical section */
538
539         InitializeCriticalSection( &heap->critSection );
540     }
541
542     /* Create the first free block */
543
544     HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize, 
545                           subheap->size - subheap->headerSize );
546
547     return TRUE;
548 }
549
550 /***********************************************************************
551  *           HEAP_CreateSubHeap
552  *
553  * Create a sub-heap of the given size.
554  * If heap == NULL, creates a main heap.
555  */
556 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, DWORD flags, 
557                                     DWORD commitSize, DWORD totalSize )
558 {
559     LPVOID address;
560
561     /* Round-up sizes on a 64K boundary */
562
563     if (flags & HEAP_WINE_SEGPTR)
564     {
565         totalSize = commitSize = 0x10000;  /* Only 64K at a time for SEGPTRs */
566     }
567     else
568     {
569         totalSize  = (totalSize + 0xffff) & 0xffff0000;
570         commitSize = (commitSize + 0xffff) & 0xffff0000;
571         if (!commitSize) commitSize = 0x10000;
572         if (totalSize < commitSize) totalSize = commitSize;
573     }
574
575     /* Allocate the memory block */
576
577     if (!(address = VirtualAlloc( NULL, totalSize,
578                                   MEM_RESERVE, PAGE_EXECUTE_READWRITE )))
579     {
580         WARN("Could not VirtualAlloc %08lx bytes\n",
581                  totalSize );
582         return NULL;
583     }
584
585     /* Initialize subheap */
586
587     if (!HEAP_InitSubHeap( heap? heap : (HEAP *)address, 
588                            address, flags, commitSize, totalSize ))
589     {
590         VirtualFree( address, 0, MEM_RELEASE );
591         return NULL;
592     }
593
594     return (SUBHEAP *)address;
595 }
596
597
598 /***********************************************************************
599  *           HEAP_FindFreeBlock
600  *
601  * Find a free block at least as large as the requested size, and make sure
602  * the requested size is committed.
603  */
604 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
605                                        SUBHEAP **ppSubHeap )
606 {
607     SUBHEAP *subheap;
608     ARENA_FREE *pArena;
609     FREE_LIST_ENTRY *pEntry = heap->freeList;
610
611     /* Find a suitable free list, and in it find a block large enough */
612
613     while (pEntry->size < size) pEntry++;
614     pArena = pEntry->arena.next;
615     while (pArena != &heap->freeList[0].arena)
616     {
617         DWORD arena_size = (pArena->size & ARENA_SIZE_MASK) +
618                             sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
619         if (arena_size >= size)
620         {
621             subheap = HEAP_FindSubHeap( heap, pArena );
622             if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
623                                                + size + HEAP_MIN_BLOCK_SIZE))
624                 return NULL;
625             *ppSubHeap = subheap;
626             return pArena;
627         }
628         pArena = pArena->next;
629     }
630
631     /* If no block was found, attempt to grow the heap */
632
633     if (!(heap->flags & HEAP_GROWABLE))
634     {
635         WARN("Not enough space in heap %08lx for %08lx bytes\n",
636                  (DWORD)heap, size );
637         return NULL;
638     }
639     /* make sure that we have a big enough size *committed* to fit another
640      * last free arena in !
641      * So just one heap struct, one first free arena which will eventually
642      * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
643      * might get assigned all remaining free space in HEAP_ShrinkBlock() */
644     size += sizeof(SUBHEAP) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
645     if (!(subheap = HEAP_CreateSubHeap( heap, heap->flags, size,
646                                         max( HEAP_DEF_SIZE, size ) )))
647         return NULL;
648
649     TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
650                 (DWORD)subheap, size, (DWORD)heap );
651
652     *ppSubHeap = subheap;
653     return (ARENA_FREE *)(subheap + 1);
654 }
655
656
657 /***********************************************************************
658  *           HEAP_IsValidArenaPtr
659  *
660  * Check that the pointer is inside the range possible for arenas.
661  */
662 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
663 {
664     int i;
665     SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
666     if (!subheap) return FALSE;
667     if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
668     if (subheap != &heap->subheap) return FALSE;
669     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
670         if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
671     return FALSE;
672 }
673
674
675 /***********************************************************************
676  *           HEAP_ValidateFreeArena
677  */
678 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
679 {
680     char *heapEnd = (char *)subheap + subheap->size;
681
682 #if !defined(ALLOW_UNALIGNED_ACCESS)
683     /* Check for unaligned pointers */
684     if ( (long)pArena % sizeof(void *) != 0 )
685     {
686         ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
687              (DWORD)subheap->heap, (DWORD)pArena );
688         return FALSE;
689     }
690 #endif
691
692     /* Check magic number */
693     if (pArena->magic != ARENA_FREE_MAGIC)
694     {
695         ERR("Heap %08lx: invalid free arena magic for %08lx\n",
696                  (DWORD)subheap->heap, (DWORD)pArena );
697         return FALSE;
698     }
699     /* Check size flags */
700     if (!(pArena->size & ARENA_FLAG_FREE) ||
701         (pArena->size & ARENA_FLAG_PREV_FREE))
702     {
703         ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
704                  (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
705     }
706     /* Check arena size */
707     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
708     {
709         ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
710                  (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
711         return FALSE;
712     }
713     /* Check that next pointer is valid */
714     if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
715     {
716         ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
717                  (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
718         return FALSE;
719     }
720     /* Check that next arena is free */
721     if (!(pArena->next->size & ARENA_FLAG_FREE) ||
722         (pArena->next->magic != ARENA_FREE_MAGIC))
723     { 
724         ERR("Heap %08lx: next arena %08lx invalid for %08lx\n", 
725                  (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
726         return FALSE;
727     }
728     /* Check that prev pointer is valid */
729     if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
730     {
731         ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
732                  (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
733         return FALSE;
734     }
735     /* Check that prev arena is free */
736     if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
737         (pArena->prev->magic != ARENA_FREE_MAGIC))
738     { 
739         /* this often means that the prev arena got overwritten
740          * by a memory write before that prev arena */
741         ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n", 
742                  (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
743         return FALSE;
744     }
745     /* Check that next block has PREV_FREE flag */
746     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
747     {
748         if (!(*(DWORD *)((char *)(pArena + 1) +
749             (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
750         {
751             ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
752                      (DWORD)subheap->heap, (DWORD)pArena );
753             return FALSE;
754         }
755         /* Check next block back pointer */
756         if (*((ARENA_FREE **)((char *)(pArena + 1) +
757             (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
758         {
759             ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
760                      (DWORD)subheap->heap, (DWORD)pArena,
761                      *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
762             return FALSE;
763         }
764     }
765     return TRUE;
766 }
767
768
769 /***********************************************************************
770  *           HEAP_ValidateInUseArena
771  */
772 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
773 {
774     char *heapEnd = (char *)subheap + subheap->size;
775
776 #if !defined(ALLOW_UNALIGNED_ACCESS)
777     /* Check for unaligned pointers */
778     if ( (long)pArena % sizeof(void *) != 0 )
779     {
780         if ( quiet == NOISY )
781         {
782             ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
783                   (DWORD)subheap->heap, (DWORD)pArena );
784             if ( TRACE_ON(heap) )
785                 HEAP_Dump( subheap->heap );
786         }
787         else if ( WARN_ON(heap) )
788         {
789             WARN( "Heap %08lx: unaligned arena pointer %08lx\n",
790                   (DWORD)subheap->heap, (DWORD)pArena );
791             if ( TRACE_ON(heap) )
792                 HEAP_Dump( subheap->heap );
793         }
794         return FALSE;
795     }
796 #endif
797
798     /* Check magic number */
799     if (pArena->magic != ARENA_INUSE_MAGIC)
800     {
801         if (quiet == NOISY) {
802         ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
803                  (DWORD)subheap->heap, (DWORD)pArena );
804             if (TRACE_ON(heap))
805                HEAP_Dump( subheap->heap );
806         }  else if (WARN_ON(heap)) {
807             WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
808                  (DWORD)subheap->heap, (DWORD)pArena );
809             if (TRACE_ON(heap))
810                HEAP_Dump( subheap->heap );
811         }
812         return FALSE;
813     }
814     /* Check size flags */
815     if (pArena->size & ARENA_FLAG_FREE) 
816     {
817         ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
818                  (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
819     }
820     /* Check arena size */
821     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
822     {
823         ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
824                  (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
825         return FALSE;
826     }
827     /* Check next arena PREV_FREE flag */
828     if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
829         (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
830     {
831         ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
832                  (DWORD)subheap->heap, (DWORD)pArena );
833         return FALSE;
834     }
835     /* Check prev free arena */
836     if (pArena->size & ARENA_FLAG_PREV_FREE)
837     {
838         ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
839         /* Check prev pointer */
840         if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
841         {
842             ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
843                     (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
844             return FALSE;
845         }
846         /* Check that prev arena is free */
847         if (!(pPrev->size & ARENA_FLAG_FREE) ||
848             (pPrev->magic != ARENA_FREE_MAGIC))
849         { 
850             ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n", 
851                      (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
852             return FALSE;
853         }
854         /* Check that prev arena is really the previous block */
855         if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
856         {
857             ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
858                      (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
859             return FALSE;
860         }
861     }
862     return TRUE;
863 }
864
865
866 /***********************************************************************
867  *           HEAP_GetSegptr
868  *
869  * Transform a linear pointer into a SEGPTR. The pointer must have been
870  * allocated from a HEAP_WINE_SEGPTR heap.
871  */
872 SEGPTR HEAP_GetSegptr( HANDLE heap, DWORD flags, LPCVOID ptr )
873 {
874     HEAP *heapPtr = HEAP_GetPtr( heap );
875     SUBHEAP *subheap;
876     SEGPTR ret = 0;
877
878     /* Validate the parameters */
879
880     if (!heapPtr) return 0;
881     flags |= heapPtr->flags;
882     if (!(flags & HEAP_WINE_SEGPTR))
883     {
884         ERR("Heap %08x is not a SEGPTR heap\n",
885                  heap );
886         return 0;
887     }
888     if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
889
890     /* Get the subheap */
891
892     if ((subheap = HEAP_FindSubHeap( heapPtr, ptr )))
893         ret = MAKESEGPTR(subheap->selector, (char *)ptr - (char *)subheap);
894
895     if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
896     return ret;
897 }
898
899 /***********************************************************************
900  *           MapLS   (KERNEL32.@)
901  *           MapLS   (KERNEL.358)
902  *
903  * Maps linear pointer to segmented.
904  */
905 SEGPTR WINAPI MapLS( LPCVOID ptr )
906 {
907     SUBHEAP *subheap;
908     SEGPTR ret = 0;
909
910     if (!HIWORD(ptr)) return (SEGPTR)ptr;
911
912     /* check if the pointer is inside the segptr heap */
913     EnterCriticalSection( &segptrHeap->critSection );
914     if ((subheap = HEAP_FindSubHeap( segptrHeap, ptr )))
915         ret = MAKESEGPTR( subheap->selector, (char *)ptr - (char *)subheap );
916     LeaveCriticalSection( &segptrHeap->critSection );
917
918     /* otherwise, allocate a brand-new selector */
919     if (!ret)
920     {
921         WORD sel = SELECTOR_AllocBlock( ptr, 0x10000, WINE_LDT_FLAGS_DATA );
922         ret = MAKESEGPTR( sel, 0 );
923     }
924     return ret;
925 }
926
927
928 /***********************************************************************
929  *           UnMapLS   (KERNEL32.@)
930  *           UnMapLS   (KERNEL.359)
931  *
932  * Free mapped selector.
933  */
934 void WINAPI UnMapLS( SEGPTR sptr )
935 {
936     SUBHEAP *subheap;
937     if (!SELECTOROF(sptr)) return;
938
939     /* check if ptr is inside segptr heap */
940     EnterCriticalSection( &segptrHeap->critSection );
941     subheap = HEAP_FindSubHeap( segptrHeap, MapSL(sptr) );
942     if ((subheap) && (subheap->selector != SELECTOROF(sptr))) subheap = NULL;
943     LeaveCriticalSection( &segptrHeap->critSection );
944     /* if not inside heap, free the selector */
945     if (!subheap) FreeSelector16( SELECTOROF(sptr) );
946 }
947
948 /***********************************************************************
949  *           HEAP_IsRealArena  [Internal]
950  * Validates a block is a valid arena.
951  *
952  * RETURNS
953  *      TRUE: Success
954  *      FALSE: Failure
955  */
956 static BOOL HEAP_IsRealArena( HEAP *heapPtr,   /* [in] ptr to the heap */
957               DWORD flags,   /* [in] Bit flags that control access during operation */
958               LPCVOID block, /* [in] Optional pointer to memory block to validate */
959               BOOL quiet )   /* [in] Flag - if true, HEAP_ValidateInUseArena
960                               *             does not complain    */
961 {
962     SUBHEAP *subheap;
963     BOOL ret = TRUE;
964
965     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
966     {
967         ERR("Invalid heap %p!\n", heapPtr );
968         return FALSE;
969     }
970
971     flags &= HEAP_NO_SERIALIZE;
972     flags |= heapPtr->flags;
973     /* calling HeapLock may result in infinite recursion, so do the critsect directly */
974     if (!(flags & HEAP_NO_SERIALIZE))
975         EnterCriticalSection( &heapPtr->critSection );
976
977     if (block)
978     {
979         /* Only check this single memory block */
980
981         if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
982             ((char *)block < (char *)subheap + subheap->headerSize
983                               + sizeof(ARENA_INUSE)))
984         {
985             if (quiet == NOISY) 
986                 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
987             else if (WARN_ON(heap)) 
988                 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
989             ret = FALSE;
990         } else
991             ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
992
993         if (!(flags & HEAP_NO_SERIALIZE))
994             LeaveCriticalSection( &heapPtr->critSection );
995         return ret;
996     }
997
998     subheap = &heapPtr->subheap;
999     while (subheap && ret)
1000     {
1001         char *ptr = (char *)subheap + subheap->headerSize;
1002         while (ptr < (char *)subheap + subheap->size)
1003         {
1004             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1005             {
1006                 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1007                     ret = FALSE;
1008                     break;
1009                 }
1010                 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1011             }
1012             else
1013             {
1014                 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1015                     ret = FALSE;
1016                     break;
1017                 }
1018                 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1019             }
1020         }
1021         subheap = subheap->next;
1022     }
1023
1024     if (!(flags & HEAP_NO_SERIALIZE))
1025         LeaveCriticalSection( &heapPtr->critSection );
1026     return ret;
1027 }
1028
1029
1030 /***********************************************************************
1031  *           HEAP_CreateSystemHeap
1032  *
1033  * Create the system heap.
1034  */
1035 static HANDLE HEAP_CreateSystemHeap(void)
1036 {
1037     int created;
1038
1039     HANDLE map = CreateFileMappingA( INVALID_HANDLE_VALUE, NULL, SEC_COMMIT | PAGE_READWRITE,
1040                                      0, HEAP_DEF_SIZE, "__SystemHeap" );
1041     if (!map) return 0;
1042     created = (GetLastError() != ERROR_ALREADY_EXISTS);
1043
1044     if (!(systemHeap = MapViewOfFileEx( map, FILE_MAP_ALL_ACCESS, 0, 0, 0, SYSTEM_HEAP_BASE )))
1045     {
1046         /* pre-defined address not available, use any one */
1047         ERR( "system heap base address %p not available\n", SYSTEM_HEAP_BASE );
1048         return 0;
1049     }
1050
1051     if (created)  /* newly created heap */
1052     {
1053         HEAP_InitSubHeap( systemHeap, systemHeap, HEAP_SHARED, 0, HEAP_DEF_SIZE );
1054         MakeCriticalSectionGlobal( &systemHeap->critSection );
1055     }
1056     else
1057     {
1058         /* wait for the heap to be initialized */
1059         while (!systemHeap->critSection.LockSemaphore) Sleep(1);
1060     }
1061     CloseHandle( map );
1062     return (HANDLE)systemHeap;
1063 }
1064
1065
1066 /***********************************************************************
1067  *           HeapCreate   (KERNEL32.@)
1068  * RETURNS
1069  *      Handle of heap: Success
1070  *      NULL: Failure
1071  */
1072 HANDLE WINAPI HeapCreate(
1073                 DWORD flags,       /* [in] Heap allocation flag */
1074                 DWORD initialSize, /* [in] Initial heap size */
1075                 DWORD maxSize      /* [in] Maximum heap size */
1076 ) {
1077     SUBHEAP *subheap;
1078
1079     if ( flags & HEAP_SHARED ) {
1080         if (!systemHeap) HEAP_CreateSystemHeap();
1081         else WARN( "Shared Heap requested, returning system heap.\n" );
1082         return (HANDLE)systemHeap;
1083     }
1084
1085     /* Allocate the heap block */
1086
1087     if (!maxSize)
1088     {
1089         maxSize = HEAP_DEF_SIZE;
1090         flags |= HEAP_GROWABLE;
1091     }
1092     if (!(subheap = HEAP_CreateSubHeap( NULL, flags, initialSize, maxSize )))
1093     {
1094         SetLastError( ERROR_OUTOFMEMORY );
1095         return 0;
1096     }
1097
1098     /* link it into the per-process heap list */
1099     if (processHeap)
1100     {
1101         HEAP *heapPtr = subheap->heap;
1102         EnterCriticalSection( &processHeap->critSection );
1103         heapPtr->next = firstHeap;
1104         firstHeap = heapPtr;
1105         LeaveCriticalSection( &processHeap->critSection );
1106     }
1107     else  /* assume the first heap we create is the process main heap */
1108     {
1109         SUBHEAP *segptr;
1110         processHeap = subheap->heap;
1111         /* create the SEGPTR heap */
1112         if (!(segptr = HEAP_CreateSubHeap( NULL, flags|HEAP_WINE_SEGPTR|HEAP_GROWABLE, 0, 0 )))
1113         {
1114             SetLastError( ERROR_OUTOFMEMORY );
1115             return 0;
1116         }
1117         segptrHeap = segptr->heap;
1118     }
1119     return (HANDLE)subheap;
1120 }
1121
1122 /***********************************************************************
1123  *           HeapDestroy   (KERNEL32.@)
1124  * RETURNS
1125  *      TRUE: Success
1126  *      FALSE: Failure
1127  */
1128 BOOL WINAPI HeapDestroy( HANDLE heap /* [in] Handle of heap */ )
1129 {
1130     HEAP *heapPtr = HEAP_GetPtr( heap );
1131     SUBHEAP *subheap;
1132
1133     TRACE("%08x\n", heap );
1134     if (!heapPtr) return FALSE;
1135
1136     if (heapPtr == systemHeap)
1137     {
1138         WARN( "attempt to destroy system heap, returning TRUE!\n" );
1139         return TRUE;
1140     }
1141     if (heapPtr == processHeap)  /* cannot delete the main process heap */
1142     {
1143         SetLastError( ERROR_INVALID_PARAMETER );
1144         return FALSE;
1145     }
1146     else /* remove it from the per-process list */
1147     {
1148         HEAP **pptr;
1149         EnterCriticalSection( &processHeap->critSection );
1150         pptr = &firstHeap;
1151         while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1152         if (*pptr) *pptr = (*pptr)->next;
1153         LeaveCriticalSection( &processHeap->critSection );
1154     }
1155
1156     DeleteCriticalSection( &heapPtr->critSection );
1157     subheap = &heapPtr->subheap;
1158     while (subheap)
1159     {
1160         SUBHEAP *next = subheap->next;
1161         if (subheap->selector) FreeSelector16( subheap->selector );
1162         VirtualFree( subheap, 0, MEM_RELEASE );
1163         subheap = next;
1164     }
1165     return TRUE;
1166 }
1167
1168
1169 /***********************************************************************
1170  *           HeapAlloc   (KERNEL32.@)
1171  * RETURNS
1172  *      Pointer to allocated memory block
1173  *      NULL: Failure
1174  */
1175 LPVOID WINAPI HeapAlloc(
1176               HANDLE heap, /* [in] Handle of private heap block */
1177               DWORD flags,   /* [in] Heap allocation control flags */
1178               DWORD size     /* [in] Number of bytes to allocate */
1179 ) {
1180     ARENA_FREE *pArena;
1181     ARENA_INUSE *pInUse;
1182     SUBHEAP *subheap;
1183     HEAP *heapPtr = HEAP_GetPtr( heap );
1184
1185     /* Validate the parameters */
1186
1187     if ((flags & HEAP_WINE_SEGPTR) && size < 0x10000) heapPtr = segptrHeap;
1188     if (!heapPtr) return NULL;
1189     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1190     flags |= heapPtr->flags;
1191     size = (size + 3) & ~3;
1192     if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1193
1194     if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1195     /* Locate a suitable free block */
1196
1197     if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1198     {
1199         TRACE("(%08x,%08lx,%08lx): returning NULL\n",
1200                   heap, flags, size  );
1201         if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1202         SetLastError( ERROR_COMMITMENT_LIMIT );
1203         return NULL;
1204     }
1205
1206     /* Remove the arena from the free list */
1207
1208     pArena->next->prev = pArena->prev;
1209     pArena->prev->next = pArena->next;
1210
1211     /* Build the in-use arena */
1212
1213     pInUse = (ARENA_INUSE *)pArena;
1214
1215     /* in-use arena is smaller than free arena,
1216      * so we have to add the difference to the size */
1217     pInUse->size      = (pInUse->size & ~ARENA_FLAG_FREE)
1218                         + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1219     pInUse->callerEIP = GET_EIP();
1220     pInUse->threadId  = GetCurrentTask();
1221     pInUse->magic     = ARENA_INUSE_MAGIC;
1222
1223     /* Shrink the block */
1224
1225     HEAP_ShrinkBlock( subheap, pInUse, size );
1226
1227     if (flags & HEAP_ZERO_MEMORY)
1228         memset( pInUse + 1, 0, pInUse->size & ARENA_SIZE_MASK );
1229     else if (TRACE_ON(heap))
1230         memset( pInUse + 1, ARENA_INUSE_FILLER, pInUse->size & ARENA_SIZE_MASK );
1231
1232     if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1233
1234     TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1235                   heap, flags, size, (DWORD)(pInUse + 1) );
1236     return (LPVOID)(pInUse + 1);
1237 }
1238
1239
1240 /***********************************************************************
1241  *           HeapFree   (KERNEL32.@)
1242  * RETURNS
1243  *      TRUE: Success
1244  *      FALSE: Failure
1245  */
1246 BOOL WINAPI HeapFree(
1247               HANDLE heap, /* [in] Handle of heap */
1248               DWORD flags,   /* [in] Heap freeing flags */
1249               LPVOID ptr     /* [in] Address of memory to free */
1250 ) {
1251     ARENA_INUSE *pInUse;
1252     SUBHEAP *subheap;
1253     HEAP *heapPtr = HEAP_GetPtr( heap );
1254
1255     /* Validate the parameters */
1256
1257     if (!ptr) return TRUE;  /* freeing a NULL ptr isn't an error in Win2k */
1258     if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1259     if (!heapPtr) return FALSE;
1260
1261     flags &= HEAP_NO_SERIALIZE;
1262     flags |= heapPtr->flags;
1263     if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1264     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1265     {
1266         if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1267         SetLastError( ERROR_INVALID_PARAMETER );
1268         TRACE("(%08x,%08lx,%08lx): returning FALSE\n",
1269                       heap, flags, (DWORD)ptr );
1270         return FALSE;
1271     }
1272
1273     /* Turn the block into a free block */
1274
1275     pInUse  = (ARENA_INUSE *)ptr - 1;
1276     subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1277     HEAP_MakeInUseBlockFree( subheap, pInUse );
1278
1279     if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1280
1281     TRACE("(%08x,%08lx,%08lx): returning TRUE\n",
1282                   heap, flags, (DWORD)ptr );
1283     return TRUE;
1284 }
1285
1286
1287 /***********************************************************************
1288  *           HeapReAlloc   (KERNEL32.@)
1289  * RETURNS
1290  *      Pointer to reallocated memory block
1291  *      NULL: Failure
1292  */
1293 LPVOID WINAPI HeapReAlloc(
1294               HANDLE heap, /* [in] Handle of heap block */
1295               DWORD flags,   /* [in] Heap reallocation flags */
1296               LPVOID ptr,    /* [in] Address of memory to reallocate */
1297               DWORD size     /* [in] Number of bytes to reallocate */
1298 ) {
1299     ARENA_INUSE *pArena;
1300     DWORD oldSize;
1301     HEAP *heapPtr;
1302     SUBHEAP *subheap;
1303
1304     if (!ptr) return HeapAlloc( heap, flags, size );  /* FIXME: correct? */
1305     if ((flags & HEAP_WINE_SEGPTR) && size < 0x10000) heapPtr = segptrHeap;
1306     if (!(heapPtr = HEAP_GetPtr( heap ))) return FALSE;
1307
1308     /* Validate the parameters */
1309
1310     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1311              HEAP_REALLOC_IN_PLACE_ONLY;
1312     flags |= heapPtr->flags;
1313     size = (size + 3) & ~3;
1314     if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1315
1316     if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1317     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1318     {
1319         if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1320         SetLastError( ERROR_INVALID_PARAMETER );
1321         TRACE("(%08x,%08lx,%08lx,%08lx): returning NULL\n",
1322                       heap, flags, (DWORD)ptr, size );
1323         return NULL;
1324     }
1325
1326     /* Check if we need to grow the block */
1327
1328     pArena = (ARENA_INUSE *)ptr - 1;
1329     pArena->threadId = GetCurrentTask();
1330     subheap = HEAP_FindSubHeap( heapPtr, pArena );
1331     oldSize = (pArena->size & ARENA_SIZE_MASK);
1332     if (size > oldSize)
1333     {
1334         char *pNext = (char *)(pArena + 1) + oldSize;
1335         if ((pNext < (char *)subheap + subheap->size) &&
1336             (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1337             (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1338         {
1339             /* The next block is free and large enough */
1340             ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1341             pFree->next->prev = pFree->prev;
1342             pFree->prev->next = pFree->next;
1343             pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1344             if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1345                                                + size + HEAP_MIN_BLOCK_SIZE))
1346             {
1347                 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1348                 SetLastError( ERROR_OUTOFMEMORY );
1349                 return NULL;
1350             }
1351             HEAP_ShrinkBlock( subheap, pArena, size );
1352         }
1353         else  /* Do it the hard way */
1354         {
1355             ARENA_FREE *pNew;
1356             ARENA_INUSE *pInUse;
1357             SUBHEAP *newsubheap;
1358
1359             if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1360                 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1361             {
1362                 if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1363                 SetLastError( ERROR_OUTOFMEMORY );
1364                 return NULL;
1365             }
1366
1367             /* Build the in-use arena */
1368
1369             pNew->next->prev = pNew->prev;
1370             pNew->prev->next = pNew->next;
1371             pInUse = (ARENA_INUSE *)pNew;
1372             pInUse->size     = (pInUse->size & ~ARENA_FLAG_FREE)
1373                                + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1374             pInUse->threadId = GetCurrentTask();
1375             pInUse->magic    = ARENA_INUSE_MAGIC;
1376             HEAP_ShrinkBlock( newsubheap, pInUse, size );
1377             memcpy( pInUse + 1, pArena + 1, oldSize );
1378
1379             /* Free the previous block */
1380
1381             HEAP_MakeInUseBlockFree( subheap, pArena );
1382             subheap = newsubheap;
1383             pArena  = pInUse;
1384         }
1385     }
1386     else HEAP_ShrinkBlock( subheap, pArena, size );  /* Shrink the block */
1387
1388     /* Clear the extra bytes if needed */
1389
1390     if (size > oldSize)
1391     {
1392         if (flags & HEAP_ZERO_MEMORY)
1393             memset( (char *)(pArena + 1) + oldSize, 0,
1394                     (pArena->size & ARENA_SIZE_MASK) - oldSize );
1395         else if (TRACE_ON(heap))
1396             memset( (char *)(pArena + 1) + oldSize, ARENA_INUSE_FILLER,
1397                     (pArena->size & ARENA_SIZE_MASK) - oldSize );
1398     }
1399
1400     /* Return the new arena */
1401
1402     pArena->callerEIP = GET_EIP();
1403     if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1404
1405     TRACE("(%08x,%08lx,%08lx,%08lx): returning %08lx\n",
1406                   heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1407     return (LPVOID)(pArena + 1);
1408 }
1409
1410
1411 /***********************************************************************
1412  *           HeapCompact   (KERNEL32.@)
1413  */
1414 DWORD WINAPI HeapCompact( HANDLE heap, DWORD flags )
1415 {
1416     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1417     return 0;
1418 }
1419
1420
1421 /***********************************************************************
1422  *           HeapLock   (KERNEL32.@)
1423  * Attempts to acquire the critical section object for a specified heap.
1424  *
1425  * RETURNS
1426  *      TRUE: Success
1427  *      FALSE: Failure
1428  */
1429 BOOL WINAPI HeapLock(
1430               HANDLE heap /* [in] Handle of heap to lock for exclusive access */
1431 ) {
1432     HEAP *heapPtr = HEAP_GetPtr( heap );
1433     if (!heapPtr) return FALSE;
1434     EnterCriticalSection( &heapPtr->critSection );
1435     return TRUE;
1436 }
1437
1438
1439 /***********************************************************************
1440  *           HeapUnlock   (KERNEL32.@)
1441  * Releases ownership of the critical section object.
1442  *
1443  * RETURNS
1444  *      TRUE: Success
1445  *      FALSE: Failure
1446  */
1447 BOOL WINAPI HeapUnlock(
1448               HANDLE heap /* [in] Handle to the heap to unlock */
1449 ) {
1450     HEAP *heapPtr = HEAP_GetPtr( heap );
1451     if (!heapPtr) return FALSE;
1452     LeaveCriticalSection( &heapPtr->critSection );
1453     return TRUE;
1454 }
1455
1456
1457 /***********************************************************************
1458  *           HeapSize   (KERNEL32.@)
1459  * RETURNS
1460  *      Size in bytes of allocated memory
1461  *      0xffffffff: Failure
1462  */
1463 DWORD WINAPI HeapSize(
1464              HANDLE heap, /* [in] Handle of heap */
1465              DWORD flags,   /* [in] Heap size control flags */
1466              LPVOID ptr     /* [in] Address of memory to return size for */
1467 ) {
1468     DWORD ret;
1469     HEAP *heapPtr = HEAP_GetPtr( heap );
1470
1471     if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1472     if (!heapPtr) return FALSE;
1473     flags &= HEAP_NO_SERIALIZE;
1474     flags |= heapPtr->flags;
1475     if (!(flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1476     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1477     {
1478         SetLastError( ERROR_INVALID_PARAMETER );
1479         ret = 0xffffffff;
1480     }
1481     else
1482     {
1483         ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1484         ret = pArena->size & ARENA_SIZE_MASK;
1485     }
1486     if (!(flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1487
1488     TRACE("(%08x,%08lx,%08lx): returning %08lx\n",
1489                   heap, flags, (DWORD)ptr, ret );
1490     return ret;
1491 }
1492
1493
1494 /***********************************************************************
1495  *           HeapValidate   (KERNEL32.@)
1496  * Validates a specified heap.
1497  *
1498  * NOTES
1499  *      Flags is ignored.
1500  *
1501  * RETURNS
1502  *      TRUE: Success
1503  *      FALSE: Failure
1504  */
1505 BOOL WINAPI HeapValidate(
1506               HANDLE heap, /* [in] Handle to the heap */
1507               DWORD flags,   /* [in] Bit flags that control access during operation */
1508               LPCVOID block  /* [in] Optional pointer to memory block to validate */
1509 ) {
1510     HEAP *heapPtr = HEAP_GetPtr( heap );
1511     if (flags & HEAP_WINE_SEGPTR) heapPtr = segptrHeap;
1512     if (!heapPtr) return FALSE;
1513     return HEAP_IsRealArena( heapPtr, flags, block, QUIET );
1514 }
1515
1516
1517 /***********************************************************************
1518  *           HeapWalk   (KERNEL32.@)
1519  * Enumerates the memory blocks in a specified heap.
1520  * See HEAP_Dump() for info on heap structure.
1521  *
1522  * TODO
1523  *   - handling of PROCESS_HEAP_ENTRY_MOVEABLE and
1524  *     PROCESS_HEAP_ENTRY_DDESHARE (needs heap.c support)
1525  *
1526  * RETURNS
1527  *      TRUE: Success
1528  *      FALSE: Failure
1529  */
1530 BOOL WINAPI HeapWalk(
1531               HANDLE heap,               /* [in]  Handle to heap to enumerate */
1532               LPPROCESS_HEAP_ENTRY entry /* [out] Pointer to structure of enumeration info */
1533 ) {
1534     HEAP *heapPtr = HEAP_GetPtr(heap);
1535     SUBHEAP *sub, *currentheap = NULL;
1536     BOOL ret = FALSE;
1537     char *ptr;
1538     int region_index = 0;
1539
1540     if (!heapPtr || !entry)
1541     {
1542         SetLastError(ERROR_INVALID_PARAMETER);
1543         return FALSE;
1544     }
1545
1546     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) EnterCriticalSection( &heapPtr->critSection );
1547
1548     /* set ptr to the next arena to be examined */
1549
1550     if (!entry->lpData) /* first call (init) ? */
1551     {
1552         TRACE("begin walking of heap 0x%08x.\n", heap);
1553         /*HEAP_Dump(heapPtr);*/
1554         currentheap = &heapPtr->subheap;
1555         ptr = (char*)currentheap + currentheap->headerSize;
1556     }
1557     else
1558     {
1559         ptr = entry->lpData;
1560         sub = &heapPtr->subheap;
1561         while (sub)
1562         {
1563             if (((char *)ptr >= (char *)sub) &&
1564                 ((char *)ptr < (char *)sub + sub->size))
1565             {
1566                 currentheap = sub;
1567                 break;
1568             }
1569             sub = sub->next;
1570             region_index++;
1571         }
1572         if (currentheap == NULL)
1573         {
1574             ERR("no matching subheap found, shouldn't happen !\n");
1575             SetLastError(ERROR_NO_MORE_ITEMS);
1576             goto HW_end;
1577         }
1578
1579         ptr += entry->cbData; /* point to next arena */
1580         if (ptr > (char *)currentheap + currentheap->size - 1)
1581         {   /* proceed with next subheap */
1582             if (!(currentheap = currentheap->next))
1583             {  /* successfully finished */
1584                 TRACE("end reached.\n");
1585                 SetLastError(ERROR_NO_MORE_ITEMS);
1586                 goto HW_end;
1587             }
1588             ptr = (char*)currentheap + currentheap->headerSize;
1589         }
1590     }
1591
1592     entry->wFlags = 0;
1593     if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1594     {
1595         ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1596
1597         /*TRACE("free, magic: %04x\n", pArena->magic);*/
1598
1599         entry->lpData = pArena + 1;
1600         entry->cbData = pArena->size & ARENA_SIZE_MASK;
1601         entry->cbOverhead = sizeof(ARENA_FREE);
1602         entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1603     }
1604     else
1605     {
1606         ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1607
1608         /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1609         
1610         entry->lpData = pArena + 1;
1611         entry->cbData = pArena->size & ARENA_SIZE_MASK;
1612         entry->cbOverhead = sizeof(ARENA_INUSE);
1613         entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1614         /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1615         and PROCESS_HEAP_ENTRY_DDESHARE yet */
1616     }
1617
1618     entry->iRegionIndex = region_index;
1619
1620     /* first element of heap ? */
1621     if (ptr == (char *)(currentheap + currentheap->headerSize))
1622     {
1623         entry->wFlags |= PROCESS_HEAP_REGION;
1624         entry->u.Region.dwCommittedSize = currentheap->commitSize;
1625         entry->u.Region.dwUnCommittedSize =
1626                 currentheap->size - currentheap->commitSize;
1627         entry->u.Region.lpFirstBlock = /* first valid block */
1628                 currentheap + currentheap->headerSize;
1629         entry->u.Region.lpLastBlock  = /* first invalid block */
1630                 currentheap + currentheap->size;
1631     }
1632     ret = TRUE;
1633
1634 HW_end:
1635     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) LeaveCriticalSection( &heapPtr->critSection );
1636
1637     return ret;
1638 }
1639
1640
1641 /***********************************************************************
1642  *           GetProcessHeap    (KERNEL32.@)
1643  */
1644 HANDLE WINAPI GetProcessHeap(void)
1645 {
1646     return (HANDLE)processHeap;
1647 }
1648
1649
1650 /***********************************************************************
1651  *           GetProcessHeaps    (KERNEL32.@)
1652  */
1653 DWORD WINAPI GetProcessHeaps( DWORD count, HANDLE *heaps )
1654 {
1655     DWORD total;
1656     HEAP *ptr;
1657
1658     if (!processHeap) return 0;  /* should never happen */
1659     total = 1;  /* main heap */
1660     EnterCriticalSection( &processHeap->critSection );
1661     for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1662     if (total <= count)
1663     {
1664         *heaps++ = (HANDLE)processHeap;
1665         for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1666     }
1667     LeaveCriticalSection( &processHeap->critSection );
1668     return total;
1669 }
1670
1671
1672 /***********************************************************************
1673  * 32-bit local heap functions (Win95; undocumented)
1674  */
1675
1676 #define HTABLE_SIZE      0x10000
1677 #define HTABLE_PAGESIZE  0x1000
1678 #define HTABLE_NPAGES    (HTABLE_SIZE / HTABLE_PAGESIZE)
1679
1680 #include "pshpack1.h"
1681 typedef struct _LOCAL32HEADER
1682 {
1683     WORD     freeListFirst[HTABLE_NPAGES];
1684     WORD     freeListSize[HTABLE_NPAGES];
1685     WORD     freeListLast[HTABLE_NPAGES];
1686
1687     DWORD    selectorTableOffset;
1688     WORD     selectorTableSize;
1689     WORD     selectorDelta;
1690
1691     DWORD    segment;
1692     LPBYTE   base;
1693
1694     DWORD    limit;
1695     DWORD    flags;
1696
1697     DWORD    magic;
1698     HANDLE heap;
1699
1700 } LOCAL32HEADER;
1701 #include "poppack.h"
1702
1703 #define LOCAL32_MAGIC    ((DWORD)('L' | ('H'<<8) | ('3'<<16) | ('2'<<24)))
1704
1705 /***********************************************************************
1706  *           K208   (KERNEL.208)
1707  */
1708 HANDLE WINAPI Local32Init16( WORD segment, DWORD tableSize,
1709                              DWORD heapSize, DWORD flags )
1710 {
1711     DWORD totSize, segSize = 0;
1712     LPBYTE base;
1713     LOCAL32HEADER *header;
1714     HEAP *heap;
1715     WORD *selectorTable;
1716     WORD selectorEven, selectorOdd;
1717     int i, nrBlocks;
1718
1719     /* Determine new heap size */
1720
1721     if ( segment )
1722     {
1723         if ( (segSize = GetSelectorLimit16( segment )) == 0 )
1724             return 0;
1725         else
1726             segSize++;
1727     }
1728
1729     if ( heapSize == -1L )
1730         heapSize = 1024L*1024L;   /* FIXME */
1731
1732     heapSize = (heapSize + 0xffff) & 0xffff0000;
1733     segSize  = (segSize  + 0x0fff) & 0xfffff000;
1734     totSize  = segSize + HTABLE_SIZE + heapSize;
1735
1736
1737     /* Allocate memory and initialize heap */
1738
1739     if ( !(base = VirtualAlloc( NULL, totSize, MEM_RESERVE, PAGE_READWRITE )) )
1740         return 0;
1741
1742     if ( !VirtualAlloc( base, segSize + HTABLE_PAGESIZE, 
1743                         MEM_COMMIT, PAGE_READWRITE ) )
1744     {
1745         VirtualFree( base, 0, MEM_RELEASE );
1746         return 0;
1747     }
1748
1749     heap = (HEAP *)(base + segSize + HTABLE_SIZE);
1750     if ( !HEAP_InitSubHeap( heap, (LPVOID)heap, 0, 0x10000, heapSize ) )
1751     {
1752         VirtualFree( base, 0, MEM_RELEASE );
1753         return 0;
1754     }
1755
1756
1757     /* Set up header and handle table */
1758     
1759     header = (LOCAL32HEADER *)(base + segSize);
1760     header->base    = base;
1761     header->limit   = HTABLE_PAGESIZE-1;
1762     header->flags   = 0;
1763     header->magic   = LOCAL32_MAGIC;
1764     header->heap    = (HANDLE)heap;
1765
1766     header->freeListFirst[0] = sizeof(LOCAL32HEADER);
1767     header->freeListLast[0]  = HTABLE_PAGESIZE - 4;
1768     header->freeListSize[0]  = (HTABLE_PAGESIZE - sizeof(LOCAL32HEADER)) / 4;
1769
1770     for (i = header->freeListFirst[0]; i < header->freeListLast[0]; i += 4)
1771         *(DWORD *)((LPBYTE)header + i) = i+4;
1772
1773     header->freeListFirst[1] = 0xffff;
1774
1775
1776     /* Set up selector table */
1777   
1778     nrBlocks      = (totSize + 0x7fff) >> 15; 
1779     selectorTable = (LPWORD) HeapAlloc( header->heap,  0, nrBlocks * 2 );
1780     selectorEven  = SELECTOR_AllocBlock( base, totSize, WINE_LDT_FLAGS_DATA );
1781     selectorOdd   = SELECTOR_AllocBlock( base + 0x8000, totSize - 0x8000, WINE_LDT_FLAGS_DATA );
1782     if ( !selectorTable || !selectorEven || !selectorOdd )
1783     {
1784         if ( selectorTable ) HeapFree( header->heap, 0, selectorTable );
1785         if ( selectorEven  ) SELECTOR_FreeBlock( selectorEven );
1786         if ( selectorOdd   ) SELECTOR_FreeBlock( selectorOdd );
1787         HeapDestroy( header->heap );
1788         VirtualFree( base, 0, MEM_RELEASE );
1789         return 0;
1790     }
1791
1792     header->selectorTableOffset = (LPBYTE)selectorTable - header->base;
1793     header->selectorTableSize   = nrBlocks * 4;  /* ??? Win95 does it this way! */
1794     header->selectorDelta       = selectorEven - selectorOdd;
1795     header->segment             = segment? segment : selectorEven;
1796
1797     for (i = 0; i < nrBlocks; i++)
1798         selectorTable[i] = (i & 1)? selectorOdd  + ((i >> 1) << __AHSHIFT)
1799                                   : selectorEven + ((i >> 1) << __AHSHIFT);
1800
1801     /* Move old segment */
1802
1803     if ( segment )
1804     {
1805         /* FIXME: This is somewhat ugly and relies on implementation
1806                   details about 16-bit global memory handles ... */
1807
1808         LPBYTE oldBase = (LPBYTE)GetSelectorBase( segment );
1809         memcpy( base, oldBase, segSize );
1810         GLOBAL_MoveBlock( segment, base, totSize );
1811         HeapFree( GetProcessHeap(), 0, oldBase );
1812     }
1813     
1814     return (HANDLE)header;
1815 }
1816
1817 /***********************************************************************
1818  *           Local32_SearchHandle
1819  */
1820 static LPDWORD Local32_SearchHandle( LOCAL32HEADER *header, DWORD addr )
1821 {
1822     LPDWORD handle;
1823
1824     for ( handle = (LPDWORD)((LPBYTE)header + sizeof(LOCAL32HEADER));
1825           handle < (LPDWORD)((LPBYTE)header + header->limit);
1826           handle++)
1827     {
1828         if (*handle == addr)
1829             return handle;
1830     }
1831
1832     return NULL;
1833 }
1834
1835 /***********************************************************************
1836  *           Local32_ToHandle
1837  */
1838 static VOID Local32_ToHandle( LOCAL32HEADER *header, INT16 type, 
1839                               DWORD addr, LPDWORD *handle, LPBYTE *ptr )
1840 {
1841     *handle = NULL;
1842     *ptr    = NULL;
1843
1844     switch (type)
1845     {
1846         case -2:    /* 16:16 pointer, no handles */
1847             *ptr    = MapSL( addr );
1848             *handle = (LPDWORD)*ptr;
1849             break;
1850
1851         case -1:    /* 32-bit offset, no handles */
1852             *ptr    = header->base + addr;
1853             *handle = (LPDWORD)*ptr;
1854             break;
1855
1856         case 0:     /* handle */
1857             if (    addr >= sizeof(LOCAL32HEADER) 
1858                  && addr <  header->limit && !(addr & 3) 
1859                  && *(LPDWORD)((LPBYTE)header + addr) >= HTABLE_SIZE )
1860             {
1861                 *handle = (LPDWORD)((LPBYTE)header + addr);
1862                 *ptr    = header->base + **handle;
1863             }
1864             break;
1865
1866         case 1:     /* 16:16 pointer */
1867             *ptr    = MapSL( addr );
1868             *handle = Local32_SearchHandle( header, *ptr - header->base );
1869             break;
1870
1871         case 2:     /* 32-bit offset */
1872             *ptr    = header->base + addr;
1873             *handle = Local32_SearchHandle( header, *ptr - header->base );
1874             break;
1875     }
1876 }
1877
1878 /***********************************************************************
1879  *           Local32_FromHandle
1880  */
1881 static VOID Local32_FromHandle( LOCAL32HEADER *header, INT16 type, 
1882                                 DWORD *addr, LPDWORD handle, LPBYTE ptr )
1883 {
1884     switch (type)
1885     {
1886         case -2:    /* 16:16 pointer */
1887         case  1:
1888         {
1889             WORD *selTable = (LPWORD)(header->base + header->selectorTableOffset);
1890             DWORD offset   = (LPBYTE)ptr - header->base;
1891             *addr = MAKELONG( offset & 0x7fff, selTable[offset >> 15] ); 
1892         }
1893         break;
1894
1895         case -1:    /* 32-bit offset */
1896         case  2:
1897             *addr = ptr - header->base;
1898             break;
1899
1900         case  0:    /* handle */
1901             *addr = (LPBYTE)handle - (LPBYTE)header;
1902             break;
1903     }
1904 }
1905
1906 /***********************************************************************
1907  *           K209   (KERNEL.209)
1908  */
1909 DWORD WINAPI Local32Alloc16( HANDLE heap, DWORD size, INT16 type, DWORD flags )
1910 {
1911     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1912     LPDWORD handle;
1913     LPBYTE ptr;
1914     DWORD addr;
1915
1916     /* Allocate memory */
1917     ptr = HeapAlloc( header->heap, 
1918                      (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, size );
1919     if (!ptr) return 0;
1920
1921
1922     /* Allocate handle if requested */
1923     if (type >= 0)
1924     {
1925         int page, i;
1926
1927         /* Find first page of handle table with free slots */
1928         for (page = 0; page < HTABLE_NPAGES; page++)
1929             if (header->freeListFirst[page] != 0)
1930                 break;
1931         if (page == HTABLE_NPAGES)
1932         {
1933             WARN("Out of handles!\n" );
1934             HeapFree( header->heap, 0, ptr );
1935             return 0;
1936         }
1937
1938         /* If virgin page, initialize it */
1939         if (header->freeListFirst[page] == 0xffff)
1940         {
1941             if ( !VirtualAlloc( (LPBYTE)header + (page << 12), 
1942                                 0x1000, MEM_COMMIT, PAGE_READWRITE ) )
1943             {
1944                 WARN("Cannot grow handle table!\n" );
1945                 HeapFree( header->heap, 0, ptr );
1946                 return 0;
1947             }
1948             
1949             header->limit += HTABLE_PAGESIZE;
1950
1951             header->freeListFirst[page] = 0;
1952             header->freeListLast[page]  = HTABLE_PAGESIZE - 4;
1953             header->freeListSize[page]  = HTABLE_PAGESIZE / 4;
1954            
1955             for (i = 0; i < HTABLE_PAGESIZE; i += 4)
1956                 *(DWORD *)((LPBYTE)header + i) = i+4;
1957
1958             if (page < HTABLE_NPAGES-1) 
1959                 header->freeListFirst[page+1] = 0xffff;
1960         }
1961
1962         /* Allocate handle slot from page */
1963         handle = (LPDWORD)((LPBYTE)header + header->freeListFirst[page]);
1964         if (--header->freeListSize[page] == 0)
1965             header->freeListFirst[page] = header->freeListLast[page] = 0;
1966         else
1967             header->freeListFirst[page] = *handle;
1968
1969         /* Store 32-bit offset in handle slot */
1970         *handle = ptr - header->base;
1971     }
1972     else
1973     {
1974         handle = (LPDWORD)ptr;
1975         header->flags |= 1;
1976     }
1977
1978
1979     /* Convert handle to requested output type */
1980     Local32_FromHandle( header, type, &addr, handle, ptr );
1981     return addr;
1982 }
1983
1984 /***********************************************************************
1985  *           K210   (KERNEL.210)
1986  */
1987 DWORD WINAPI Local32ReAlloc16( HANDLE heap, DWORD addr, INT16 type,
1988                              DWORD size, DWORD flags )
1989 {
1990     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
1991     LPDWORD handle;
1992     LPBYTE ptr;
1993
1994     if (!addr)
1995         return Local32Alloc16( heap, size, type, flags );
1996
1997     /* Retrieve handle and pointer */
1998     Local32_ToHandle( header, type, addr, &handle, &ptr );
1999     if (!handle) return FALSE;
2000
2001     /* Reallocate memory block */
2002     ptr = HeapReAlloc( header->heap, 
2003                        (flags & LMEM_MOVEABLE)? HEAP_ZERO_MEMORY : 0, 
2004                        ptr, size );
2005     if (!ptr) return 0;
2006
2007     /* Modify handle */
2008     if (type >= 0)
2009         *handle = ptr - header->base;
2010     else
2011         handle = (LPDWORD)ptr;
2012
2013     /* Convert handle to requested output type */
2014     Local32_FromHandle( header, type, &addr, handle, ptr );
2015     return addr;
2016 }
2017
2018 /***********************************************************************
2019  *           K211   (KERNEL.211)
2020  */
2021 BOOL WINAPI Local32Free16( HANDLE heap, DWORD addr, INT16 type )
2022 {
2023     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2024     LPDWORD handle;
2025     LPBYTE ptr;
2026
2027     /* Retrieve handle and pointer */
2028     Local32_ToHandle( header, type, addr, &handle, &ptr );
2029     if (!handle) return FALSE;
2030
2031     /* Free handle if necessary */
2032     if (type >= 0)
2033     {
2034         int offset = (LPBYTE)handle - (LPBYTE)header;
2035         int page   = offset >> 12;
2036
2037         /* Return handle slot to page free list */
2038         if (header->freeListSize[page]++ == 0)
2039             header->freeListFirst[page] = header->freeListLast[page]  = offset;
2040         else
2041             *(LPDWORD)((LPBYTE)header + header->freeListLast[page]) = offset,
2042             header->freeListLast[page] = offset;
2043
2044         *handle = 0;
2045
2046         /* Shrink handle table when possible */
2047         while (page > 0 && header->freeListSize[page] == HTABLE_PAGESIZE / 4)
2048         {
2049             if ( VirtualFree( (LPBYTE)header + 
2050                               (header->limit & ~(HTABLE_PAGESIZE-1)),
2051                               HTABLE_PAGESIZE, MEM_DECOMMIT ) )
2052                 break;
2053
2054             header->limit -= HTABLE_PAGESIZE;
2055             header->freeListFirst[page] = 0xffff;
2056             page--;
2057         }
2058     }
2059
2060     /* Free memory */
2061     return HeapFree( header->heap, 0, ptr );
2062 }
2063
2064 /***********************************************************************
2065  *           K213   (KERNEL.213)
2066  */
2067 DWORD WINAPI Local32Translate16( HANDLE heap, DWORD addr, INT16 type1, INT16 type2 )
2068 {
2069     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2070     LPDWORD handle;
2071     LPBYTE ptr;
2072
2073     Local32_ToHandle( header, type1, addr, &handle, &ptr );
2074     if (!handle) return 0;
2075
2076     Local32_FromHandle( header, type2, &addr, handle, ptr );
2077     return addr;
2078 }
2079
2080 /***********************************************************************
2081  *           K214   (KERNEL.214)
2082  */
2083 DWORD WINAPI Local32Size16( HANDLE heap, DWORD addr, INT16 type )
2084 {
2085     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2086     LPDWORD handle;
2087     LPBYTE ptr;
2088
2089     Local32_ToHandle( header, type, addr, &handle, &ptr );
2090     if (!handle) return 0;
2091
2092     return HeapSize( header->heap, 0, ptr );
2093 }
2094
2095 /***********************************************************************
2096  *           K215   (KERNEL.215)
2097  */
2098 BOOL WINAPI Local32ValidHandle16( HANDLE heap, WORD addr )
2099 {
2100     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2101     LPDWORD handle;
2102     LPBYTE ptr;
2103
2104     Local32_ToHandle( header, 0, addr, &handle, &ptr );
2105     return handle != NULL;
2106 }
2107
2108 /***********************************************************************
2109  *           K229   (KERNEL.229)
2110  */
2111 WORD WINAPI Local32GetSegment16( HANDLE heap )
2112 {
2113     LOCAL32HEADER *header = (LOCAL32HEADER *)heap;
2114     return header->segment;
2115 }
2116
2117 /***********************************************************************
2118  *           Local32_GetHeap
2119  */
2120 static LOCAL32HEADER *Local32_GetHeap( HGLOBAL16 handle )
2121 {
2122     WORD selector = GlobalHandleToSel16( handle );
2123     DWORD base  = GetSelectorBase( selector ); 
2124     DWORD limit = GetSelectorLimit16( selector ); 
2125
2126     /* Hmmm. This is a somewhat stupid heuristic, but Windows 95 does
2127        it this way ... */
2128
2129     if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2130         return (LOCAL32HEADER *)base;
2131
2132     base  += 0x10000;
2133     limit -= 0x10000;
2134
2135     if ( limit > 0x10000 && ((LOCAL32HEADER *)base)->magic == LOCAL32_MAGIC )
2136         return (LOCAL32HEADER *)base;
2137
2138     return NULL;
2139 }
2140
2141 /***********************************************************************
2142  *           Local32Info   (KERNEL.444)
2143  *           Local32Info   (TOOLHELP.84)
2144  */
2145 BOOL16 WINAPI Local32Info16( LOCAL32INFO *pLocal32Info, HGLOBAL16 handle )
2146 {
2147     SUBHEAP *heapPtr;
2148     LPBYTE ptr;
2149     int i;
2150
2151     LOCAL32HEADER *header = Local32_GetHeap( handle );
2152     if ( !header ) return FALSE;
2153
2154     if ( !pLocal32Info || pLocal32Info->dwSize < sizeof(LOCAL32INFO) )
2155         return FALSE;
2156
2157     heapPtr = (SUBHEAP *)HEAP_GetPtr( header->heap );
2158     pLocal32Info->dwMemReserved = heapPtr->size;
2159     pLocal32Info->dwMemCommitted = heapPtr->commitSize;
2160     pLocal32Info->dwTotalFree = 0L;
2161     pLocal32Info->dwLargestFreeBlock = 0L;
2162
2163     /* Note: Local32 heaps always have only one subheap! */
2164     ptr = (LPBYTE)heapPtr + heapPtr->headerSize;
2165     while ( ptr < (LPBYTE)heapPtr + heapPtr->size )
2166     {
2167         if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2168         {
2169             ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2170             DWORD size = (pArena->size & ARENA_SIZE_MASK);
2171             ptr += sizeof(*pArena) + size;
2172
2173             pLocal32Info->dwTotalFree += size;
2174             if ( size > pLocal32Info->dwLargestFreeBlock )
2175                 pLocal32Info->dwLargestFreeBlock = size;
2176         }
2177         else
2178         {
2179             ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2180             DWORD size = (pArena->size & ARENA_SIZE_MASK);
2181             ptr += sizeof(*pArena) + size;
2182         }
2183     }
2184
2185     pLocal32Info->dwcFreeHandles = 0;
2186     for ( i = 0; i < HTABLE_NPAGES; i++ )
2187     {
2188         if ( header->freeListFirst[i] == 0xffff ) break;
2189         pLocal32Info->dwcFreeHandles += header->freeListSize[i];
2190     }
2191     pLocal32Info->dwcFreeHandles += (HTABLE_NPAGES - i) * HTABLE_PAGESIZE/4;
2192
2193     return TRUE;
2194 }
2195
2196 /***********************************************************************
2197  *           Local32First   (KERNEL.445)
2198  *           Local32First   (TOOLHELP.85)
2199  */
2200 BOOL16 WINAPI Local32First16( LOCAL32ENTRY *pLocal32Entry, HGLOBAL16 handle )
2201 {
2202     FIXME("(%p, %04X): stub!\n", pLocal32Entry, handle );
2203     return FALSE;
2204 }
2205
2206 /***********************************************************************
2207  *           Local32Next   (KERNEL.446)
2208  *           Local32Next   (TOOLHELP.86)
2209  */
2210 BOOL16 WINAPI Local32Next16( LOCAL32ENTRY *pLocal32Entry )
2211 {
2212     FIXME("(%p): stub!\n", pLocal32Entry );
2213     return FALSE;
2214 }
2215