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