Implement NtQueryVolumeInformationFile for type
[wine] / dlls / ntdll / heap.c
1 /*
2  * Win32 heap functions
3  *
4  * Copyright 1996 Alexandre Julliard
5  * Copyright 1998 Ulrich Weigand
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23
24 #include <assert.h>
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <string.h>
29 #ifdef HAVE_VALGRIND_MEMCHECK_H
30 #include <valgrind/memcheck.h>
31 #endif
32
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
35 #include "ntstatus.h"
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winreg.h"
39 #include "winternl.h"
40 #include "winerror.h"
41 #include "winnt.h"
42 #include "thread.h"
43 #include "wine/debug.h"
44 #include "winternl.h"
45 #include "wine/server_protocol.h"
46
47 WINE_DEFAULT_DEBUG_CHANNEL(heap);
48
49 /* Note: the heap data structures are based on what Pietrek describes in his
50  * book 'Windows 95 System Programming Secrets'. The layout is not exactly
51  * the same, but could be easily adapted if it turns out some programs
52  * require it.
53  */
54
55 typedef struct tagARENA_INUSE
56 {
57     DWORD  size;                    /* Block size; must be the first field */
58     DWORD  magic;                   /* Magic number */
59 } ARENA_INUSE;
60
61 typedef struct tagARENA_FREE
62 {
63     DWORD                 size;     /* Block size; must be the first field */
64     DWORD                 magic;    /* Magic number */
65     struct tagARENA_FREE *next;     /* Next free arena */
66     struct tagARENA_FREE *prev;     /* Prev free arena */
67 } ARENA_FREE;
68
69 #define ARENA_FLAG_FREE        0x00000001  /* flags OR'ed with arena size */
70 #define ARENA_FLAG_PREV_FREE   0x00000002
71 #define ARENA_SIZE_MASK        (~3)
72 #define ARENA_INUSE_MAGIC      0x44455355      /* Value for arena 'magic' field */
73 #define ARENA_FREE_MAGIC       0x45455246      /* Value for arena 'magic' field */
74
75 #define ARENA_INUSE_FILLER     0x55
76 #define ARENA_FREE_FILLER      0xaa
77
78 #define ALIGNMENT              8   /* everything is aligned on 8 byte boundaries */
79 #define ROUND_SIZE(size)       (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
80
81 #define QUIET                  1           /* Suppress messages  */
82 #define NOISY                  0           /* Report all errors  */
83
84 #define HEAP_NB_FREE_LISTS   4   /* Number of free lists */
85
86 /* Max size of the blocks on the free lists */
87 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
88 {
89     0x20, 0x80, 0x200, ~0UL
90 };
91
92 typedef struct
93 {
94     DWORD       size;
95     ARENA_FREE  arena;
96 } FREE_LIST_ENTRY;
97
98 struct tagHEAP;
99
100 typedef struct tagSUBHEAP
101 {
102     DWORD               size;       /* Size of the whole sub-heap */
103     DWORD               commitSize; /* Committed size of the sub-heap */
104     DWORD               headerSize; /* Size of the heap header */
105     struct tagSUBHEAP  *next;       /* Next sub-heap */
106     struct tagHEAP     *heap;       /* Main heap structure */
107     DWORD               magic;      /* Magic number */
108 } SUBHEAP;
109
110 #define SUBHEAP_MAGIC    ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
111
112 typedef struct tagHEAP
113 {
114     SUBHEAP          subheap;       /* First sub-heap */
115     struct tagHEAP  *next;          /* Next heap for this process */
116     CRITICAL_SECTION critSection;   /* Critical section for serialization */
117     FREE_LIST_ENTRY  freeList[HEAP_NB_FREE_LISTS];  /* Free lists */
118     DWORD            flags;         /* Heap flags */
119     DWORD            magic;         /* Magic number */
120 } HEAP;
121
122 #define HEAP_MAGIC       ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
123
124 #define HEAP_DEF_SIZE        0x110000   /* Default heap size = 1Mb + 64Kb */
125 #define HEAP_MIN_BLOCK_SIZE  (8+sizeof(ARENA_FREE))  /* Min. heap block size */
126 #define COMMIT_MASK          0xffff  /* bitmask for commit/decommit granularity */
127
128 static HANDLE processHeap;  /* main process heap */
129
130 static HEAP *firstHeap;     /* head of secondary heaps list */
131
132 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
133
134 /* mark a block of memory as free for debugging purposes */
135 static inline void mark_block_free( void *ptr, size_t size )
136 {
137     if (TRACE_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
138 #ifdef VALGRIND_MAKE_NOACCESS
139     VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
140 #endif
141 }
142
143 /* mark a block of memory as initialized for debugging purposes */
144 static inline void mark_block_initialized( void *ptr, size_t size )
145 {
146 #ifdef VALGRIND_MAKE_READABLE
147     VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
148 #endif
149 }
150
151 /* mark a block of memory as uninitialized for debugging purposes */
152 static inline void mark_block_uninitialized( void *ptr, size_t size )
153 {
154 #ifdef VALGRIND_MAKE_WRITABLE
155     VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
156 #endif
157     if (TRACE_ON(heap))
158     {
159         memset( ptr, ARENA_INUSE_FILLER, size );
160 #ifdef VALGRIND_MAKE_WRITABLE
161         /* make it uninitialized to valgrind again */
162         VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
163 #endif
164     }
165 }
166
167 /* clear contents of a block of memory */
168 static inline void clear_block( void *ptr, size_t size )
169 {
170     mark_block_initialized( ptr, size );
171     memset( ptr, 0, size );
172 }
173
174 /***********************************************************************
175  *           HEAP_Dump
176  */
177 void HEAP_Dump( HEAP *heap )
178 {
179     int i;
180     SUBHEAP *subheap;
181     char *ptr;
182
183     DPRINTF( "Heap: %08lx\n", (DWORD)heap );
184     DPRINTF( "Next: %08lx  Sub-heaps: %08lx",
185           (DWORD)heap->next, (DWORD)&heap->subheap );
186     subheap = &heap->subheap;
187     while (subheap->next)
188     {
189         DPRINTF( " -> %08lx", (DWORD)subheap->next );
190         subheap = subheap->next;
191     }
192
193     DPRINTF( "\nFree lists:\n Block   Stat   Size    Id\n" );
194     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
195         DPRINTF( "%08lx free %08lx prev=%08lx next=%08lx\n",
196               (DWORD)&heap->freeList[i].arena, heap->freeList[i].size,
197               (DWORD)heap->freeList[i].arena.prev,
198               (DWORD)heap->freeList[i].arena.next );
199
200     subheap = &heap->subheap;
201     while (subheap)
202     {
203         DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
204         DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
205               (DWORD)subheap, subheap->size, subheap->commitSize );
206
207         DPRINTF( "\n Block   Stat   Size    Id\n" );
208         ptr = (char*)subheap + subheap->headerSize;
209         while (ptr < (char *)subheap + subheap->size)
210         {
211             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
212             {
213                 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
214                 DPRINTF( "%08lx free %08lx prev=%08lx next=%08lx\n",
215                       (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
216                       (DWORD)pArena->prev, (DWORD)pArena->next);
217                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
218                 arenaSize += sizeof(ARENA_FREE);
219                 freeSize += pArena->size & ARENA_SIZE_MASK;
220             }
221             else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
222             {
223                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
224                 DPRINTF( "%08lx Used %08lx back=%08lx\n",
225                          (DWORD)pArena, pArena->size & ARENA_SIZE_MASK, *((DWORD *)pArena - 1) );
226                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
227                 arenaSize += sizeof(ARENA_INUSE);
228                 usedSize += pArena->size & ARENA_SIZE_MASK;
229             }
230             else
231             {
232                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
233                 DPRINTF( "%08lx used %08lx\n",
234                       (DWORD)pArena, pArena->size & ARENA_SIZE_MASK );
235                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
236                 arenaSize += sizeof(ARENA_INUSE);
237                 usedSize += pArena->size & ARENA_SIZE_MASK;
238             }
239         }
240         DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
241               subheap->size, subheap->commitSize, freeSize, usedSize,
242               arenaSize, (arenaSize * 100) / subheap->size );
243         subheap = subheap->next;
244     }
245 }
246
247
248 void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
249 {
250     WORD rem_flags;
251     TRACE( "Dumping entry %p\n", entry );
252     TRACE( "lpData\t\t: %p\n", entry->lpData );
253     TRACE( "cbData\t\t: %08lx\n", entry->cbData);
254     TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
255     TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
256     TRACE( "WFlags\t\t: ");
257     if (entry->wFlags & PROCESS_HEAP_REGION)
258         TRACE( "PROCESS_HEAP_REGION ");
259     if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
260         TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
261     if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
262         TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
263     if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
264         TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
265     if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
266         TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
267     rem_flags = entry->wFlags &
268         ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
269           PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
270           PROCESS_HEAP_ENTRY_DDESHARE);
271     if (rem_flags)
272         TRACE( "Unknown %08x", rem_flags);
273     TRACE( "\n");
274     if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
275         && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
276     {
277         /* Treat as block */
278         TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
279     }
280     if (entry->wFlags & PROCESS_HEAP_REGION)
281     {
282         TRACE( "Region.dwCommittedSize\t:%08lx\n",entry->u.Region.dwCommittedSize);
283         TRACE( "Region.dwUnCommittedSize\t:%08lx\n",entry->u.Region.dwUnCommittedSize);
284         TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
285         TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
286     }
287 }
288
289 /***********************************************************************
290  *           HEAP_GetPtr
291  * RETURNS
292  *      Pointer to the heap
293  *      NULL: Failure
294  */
295 static HEAP *HEAP_GetPtr(
296              HANDLE heap /* [in] Handle to the heap */
297 ) {
298     HEAP *heapPtr = (HEAP *)heap;
299     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
300     {
301         ERR("Invalid heap %p!\n", heap );
302         return NULL;
303     }
304     if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
305     {
306         HEAP_Dump( heapPtr );
307         assert( FALSE );
308         return NULL;
309     }
310     return heapPtr;
311 }
312
313
314 /***********************************************************************
315  *           HEAP_InsertFreeBlock
316  *
317  * Insert a free block into the free list.
318  */
319 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
320 {
321     FREE_LIST_ENTRY *pEntry = heap->freeList;
322     while (pEntry->size < pArena->size) pEntry++;
323     if (last)
324     {
325         /* insert at end of free list, i.e. before the next free list entry */
326         pEntry++;
327         if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
328         pArena->prev       = pEntry->arena.prev;
329         pArena->prev->next = pArena;
330         pArena->next       = &pEntry->arena;
331         pEntry->arena.prev = pArena;
332     }
333     else
334     {
335         /* insert at head of free list */
336         pArena->next       = pEntry->arena.next;
337         pArena->next->prev = pArena;
338         pArena->prev       = &pEntry->arena;
339         pEntry->arena.next = pArena;
340     }
341     pArena->size |= ARENA_FLAG_FREE;
342 }
343
344
345 /***********************************************************************
346  *           HEAP_FindSubHeap
347  * Find the sub-heap containing a given address.
348  *
349  * RETURNS
350  *      Pointer: Success
351  *      NULL: Failure
352  */
353 static SUBHEAP *HEAP_FindSubHeap(
354                 const HEAP *heap, /* [in] Heap pointer */
355                 LPCVOID ptr /* [in] Address */
356 ) {
357     const SUBHEAP *sub = &heap->subheap;
358     while (sub)
359     {
360         if (((const char *)ptr >= (const char *)sub) &&
361             ((const char *)ptr < (const char *)sub + sub->size)) return (SUBHEAP*)sub;
362         sub = sub->next;
363     }
364     return NULL;
365 }
366
367
368 /***********************************************************************
369  *           HEAP_Commit
370  *
371  * Make sure the heap storage is committed up to (not including) ptr.
372  */
373 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
374 {
375     DWORD size = (DWORD)((char *)ptr - (char *)subheap);
376     size = (size + COMMIT_MASK) & ~COMMIT_MASK;
377     if (size > subheap->size) size = subheap->size;
378     if (size <= subheap->commitSize) return TRUE;
379     size -= subheap->commitSize;
380     ptr = (char *)subheap + subheap->commitSize;
381     if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
382                                  &size, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
383     {
384         WARN("Could not commit %08lx bytes at %p for heap %p\n",
385                  size, ptr, subheap->heap );
386         return FALSE;
387     }
388     subheap->commitSize += size;
389     return TRUE;
390 }
391
392
393 /***********************************************************************
394  *           HEAP_Decommit
395  *
396  * If possible, decommit the heap storage from (including) 'ptr'.
397  */
398 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
399 {
400     void *addr;
401     ULONG decommit_size;
402
403     DWORD size = (DWORD)((char *)ptr - (char *)subheap);
404     /* round to next block and add one full block */
405     size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
406     if (size >= subheap->commitSize) return TRUE;
407     decommit_size = subheap->commitSize - size;
408     addr = (char *)subheap + size;
409
410     if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
411     {
412         WARN("Could not decommit %08lx bytes at %08lx for heap %p\n",
413                  decommit_size, (DWORD)((char *)subheap + size), subheap->heap );
414         return FALSE;
415     }
416     subheap->commitSize -= decommit_size;
417     return TRUE;
418 }
419
420
421 /***********************************************************************
422  *           HEAP_CreateFreeBlock
423  *
424  * Create a free block at a specified address. 'size' is the size of the
425  * whole block, including the new arena.
426  */
427 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
428 {
429     ARENA_FREE *pFree;
430     char *pEnd;
431     BOOL last;
432
433     /* Create a free arena */
434     mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
435     pFree = (ARENA_FREE *)ptr;
436     pFree->magic = ARENA_FREE_MAGIC;
437
438     /* If debugging, erase the freed block content */
439
440     pEnd = (char *)ptr + size;
441     if (pEnd > (char *)subheap + subheap->commitSize) pEnd = (char *)subheap + subheap->commitSize;
442     if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
443
444     /* Check if next block is free also */
445
446     if (((char *)ptr + size < (char *)subheap + subheap->size) &&
447         (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
448     {
449         /* Remove the next arena from the free list */
450         ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
451         pNext->next->prev = pNext->prev;
452         pNext->prev->next = pNext->next;
453         size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
454         mark_block_free( pNext, sizeof(ARENA_FREE) );
455     }
456
457     /* Set the next block PREV_FREE flag and pointer */
458
459     last = ((char *)ptr + size >= (char *)subheap + subheap->size);
460     if (!last)
461     {
462         DWORD *pNext = (DWORD *)((char *)ptr + size);
463         *pNext |= ARENA_FLAG_PREV_FREE;
464         mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
465         *(ARENA_FREE **)(pNext - 1) = pFree;
466     }
467
468     /* Last, insert the new block into the free list */
469
470     pFree->size = size - sizeof(*pFree);
471     HEAP_InsertFreeBlock( subheap->heap, pFree, last );
472 }
473
474
475 /***********************************************************************
476  *           HEAP_MakeInUseBlockFree
477  *
478  * Turn an in-use block into a free block. Can also decommit the end of
479  * the heap, and possibly even free the sub-heap altogether.
480  */
481 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
482 {
483     ARENA_FREE *pFree;
484     DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
485
486     /* Check if we can merge with previous block */
487
488     if (pArena->size & ARENA_FLAG_PREV_FREE)
489     {
490         pFree = *((ARENA_FREE **)pArena - 1);
491         size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
492         /* Remove it from the free list */
493         pFree->next->prev = pFree->prev;
494         pFree->prev->next = pFree->next;
495     }
496     else pFree = (ARENA_FREE *)pArena;
497
498     /* Create a free block */
499
500     HEAP_CreateFreeBlock( subheap, pFree, size );
501     size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
502     if ((char *)pFree + size < (char *)subheap + subheap->size)
503         return;  /* Not the last block, so nothing more to do */
504
505     /* Free the whole sub-heap if it's empty and not the original one */
506
507     if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
508         (subheap != &subheap->heap->subheap))
509     {
510         ULONG size = 0;
511         SUBHEAP *pPrev = &subheap->heap->subheap;
512         /* Remove the free block from the list */
513         pFree->next->prev = pFree->prev;
514         pFree->prev->next = pFree->next;
515         /* Remove the subheap from the list */
516         while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
517         if (pPrev) pPrev->next = subheap->next;
518         /* Free the memory */
519         subheap->magic = 0;
520         NtFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap, &size, MEM_RELEASE );
521         return;
522     }
523
524     /* Decommit the end of the heap */
525
526     if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
527 }
528
529
530 /***********************************************************************
531  *           HEAP_ShrinkBlock
532  *
533  * Shrink an in-use block.
534  */
535 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
536 {
537     if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
538     {
539         HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
540                               (pArena->size & ARENA_SIZE_MASK) - size );
541         /* assign size plus previous arena flags */
542         pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
543     }
544     else
545     {
546         /* Turn off PREV_FREE flag in next block */
547         char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
548         if (pNext < (char *)subheap + subheap->size)
549             *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
550     }
551 }
552
553 /***********************************************************************
554  *           HEAP_InitSubHeap
555  */
556 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
557                                 DWORD commitSize, DWORD totalSize )
558 {
559     SUBHEAP *subheap;
560     FREE_LIST_ENTRY *pEntry;
561     int i;
562
563     /* Commit memory */
564
565     if (flags & HEAP_SHARED)
566         commitSize = totalSize;  /* always commit everything in a shared heap */
567     if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
568                                  &commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
569     {
570         WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
571         return FALSE;
572     }
573
574     /* Fill the sub-heap structure */
575
576     subheap = (SUBHEAP *)address;
577     subheap->heap       = heap;
578     subheap->size       = totalSize;
579     subheap->commitSize = commitSize;
580     subheap->magic      = SUBHEAP_MAGIC;
581
582     if ( subheap != (SUBHEAP *)heap )
583     {
584         /* If this is a secondary subheap, insert it into list */
585
586         subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
587         subheap->next       = heap->subheap.next;
588         heap->subheap.next  = subheap;
589     }
590     else
591     {
592         /* If this is a primary subheap, initialize main heap */
593
594         subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
595         subheap->next       = NULL;
596         heap->next          = NULL;
597         heap->flags         = flags;
598         heap->magic         = HEAP_MAGIC;
599
600         /* Build the free lists */
601
602         for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
603         {
604             pEntry->size       = HEAP_freeListSizes[i];
605             pEntry->arena.size = 0 | ARENA_FLAG_FREE;
606             pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
607                                  &heap->freeList[i+1].arena : &heap->freeList[0].arena;
608             pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
609                                   &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
610             pEntry->arena.magic = ARENA_FREE_MAGIC;
611         }
612
613         /* Initialize critical section */
614
615         RtlInitializeCriticalSection( &heap->critSection );
616         if (flags & HEAP_SHARED)
617         {
618             /* let's assume that only one thread at a time will try to do this */
619             HANDLE sem = heap->critSection.LockSemaphore;
620             if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
621
622             NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
623                                DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
624             heap->critSection.LockSemaphore = sem;
625         }
626     }
627
628     /* Create the first free block */
629
630     HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
631                           subheap->size - subheap->headerSize );
632
633     return TRUE;
634 }
635
636 /***********************************************************************
637  *           HEAP_CreateSubHeap
638  *
639  * Create a sub-heap of the given size.
640  * If heap == NULL, creates a main heap.
641  */
642 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
643                                     DWORD commitSize, DWORD totalSize )
644 {
645     LPVOID address = base;
646
647     /* round-up sizes on a 64K boundary */
648     totalSize  = (totalSize + 0xffff) & 0xffff0000;
649     commitSize = (commitSize + 0xffff) & 0xffff0000;
650     if (!commitSize) commitSize = 0x10000;
651     if (totalSize < commitSize) totalSize = commitSize;
652
653     if (!address)
654     {
655         /* allocate the memory block */
656         if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
657                                      MEM_RESERVE, PAGE_EXECUTE_READWRITE ))
658         {
659             WARN("Could not allocate %08lx bytes\n", totalSize );
660             return NULL;
661         }
662     }
663
664     /* Initialize subheap */
665
666     if (!HEAP_InitSubHeap( heap ? heap : (HEAP *)address,
667                            address, flags, commitSize, totalSize ))
668     {
669         ULONG size = 0;
670         if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
671         return NULL;
672     }
673
674     return (SUBHEAP *)address;
675 }
676
677
678 /***********************************************************************
679  *           HEAP_FindFreeBlock
680  *
681  * Find a free block at least as large as the requested size, and make sure
682  * the requested size is committed.
683  */
684 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
685                                        SUBHEAP **ppSubHeap )
686 {
687     SUBHEAP *subheap;
688     ARENA_FREE *pArena;
689     FREE_LIST_ENTRY *pEntry = heap->freeList;
690
691     /* Find a suitable free list, and in it find a block large enough */
692
693     while (pEntry->size < size) pEntry++;
694     pArena = pEntry->arena.next;
695     while (pArena != &heap->freeList[0].arena)
696     {
697         DWORD arena_size = (pArena->size & ARENA_SIZE_MASK) +
698                             sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
699         if (arena_size >= size)
700         {
701             subheap = HEAP_FindSubHeap( heap, pArena );
702             if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
703                                                + size + HEAP_MIN_BLOCK_SIZE))
704                 return NULL;
705             *ppSubHeap = subheap;
706             return pArena;
707         }
708         pArena = pArena->next;
709     }
710
711     /* If no block was found, attempt to grow the heap */
712
713     if (!(heap->flags & HEAP_GROWABLE))
714     {
715         WARN("Not enough space in heap %08lx for %08lx bytes\n",
716                  (DWORD)heap, size );
717         return NULL;
718     }
719     /* make sure that we have a big enough size *committed* to fit another
720      * last free arena in !
721      * So just one heap struct, one first free arena which will eventually
722      * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
723      * might get assigned all remaining free space in HEAP_ShrinkBlock() */
724     size += ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
725     if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, size,
726                                         max( HEAP_DEF_SIZE, size ) )))
727         return NULL;
728
729     TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
730                 (DWORD)subheap, size, (DWORD)heap );
731
732     *ppSubHeap = subheap;
733     return (ARENA_FREE *)(subheap + 1);
734 }
735
736
737 /***********************************************************************
738  *           HEAP_IsValidArenaPtr
739  *
740  * Check that the pointer is inside the range possible for arenas.
741  */
742 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const void *ptr )
743 {
744     int i;
745     const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
746     if (!subheap) return FALSE;
747     if ((const char *)ptr >= (const char *)subheap + subheap->headerSize) return TRUE;
748     if (subheap != &heap->subheap) return FALSE;
749     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
750         if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
751     return FALSE;
752 }
753
754
755 /***********************************************************************
756  *           HEAP_ValidateFreeArena
757  */
758 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
759 {
760     char *heapEnd = (char *)subheap + subheap->size;
761
762     /* Check for unaligned pointers */
763     if ( (long)pArena % ALIGNMENT != 0 )
764     {
765         ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
766              (DWORD)subheap->heap, (DWORD)pArena );
767         return FALSE;
768     }
769
770     /* Check magic number */
771     if (pArena->magic != ARENA_FREE_MAGIC)
772     {
773         ERR("Heap %08lx: invalid free arena magic for %08lx\n",
774                  (DWORD)subheap->heap, (DWORD)pArena );
775         return FALSE;
776     }
777     /* Check size flags */
778     if (!(pArena->size & ARENA_FLAG_FREE) ||
779         (pArena->size & ARENA_FLAG_PREV_FREE))
780     {
781         ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
782                  (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
783     }
784     /* Check arena size */
785     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
786     {
787         ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
788                  (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
789         return FALSE;
790     }
791     /* Check that next pointer is valid */
792     if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
793     {
794         ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
795                  (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
796         return FALSE;
797     }
798     /* Check that next arena is free */
799     if (!(pArena->next->size & ARENA_FLAG_FREE) ||
800         (pArena->next->magic != ARENA_FREE_MAGIC))
801     {
802         ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
803                  (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
804         return FALSE;
805     }
806     /* Check that prev pointer is valid */
807     if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
808     {
809         ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
810                  (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
811         return FALSE;
812     }
813     /* Check that prev arena is free */
814     if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
815         (pArena->prev->magic != ARENA_FREE_MAGIC))
816     {
817         /* this often means that the prev arena got overwritten
818          * by a memory write before that prev arena */
819         ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
820                  (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
821         return FALSE;
822     }
823     /* Check that next block has PREV_FREE flag */
824     if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
825     {
826         if (!(*(DWORD *)((char *)(pArena + 1) +
827             (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
828         {
829             ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
830                      (DWORD)subheap->heap, (DWORD)pArena );
831             return FALSE;
832         }
833         /* Check next block back pointer */
834         if (*((ARENA_FREE **)((char *)(pArena + 1) +
835             (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
836         {
837             ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
838                      (DWORD)subheap->heap, (DWORD)pArena,
839                      *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
840             return FALSE;
841         }
842     }
843     return TRUE;
844 }
845
846
847 /***********************************************************************
848  *           HEAP_ValidateInUseArena
849  */
850 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
851 {
852     const char *heapEnd = (const char *)subheap + subheap->size;
853
854     /* Check for unaligned pointers */
855     if ( (long)pArena % ALIGNMENT != 0 )
856     {
857         if ( quiet == NOISY )
858         {
859             ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
860                   (DWORD)subheap->heap, (DWORD)pArena );
861             if ( TRACE_ON(heap) )
862                 HEAP_Dump( subheap->heap );
863         }
864         else if ( WARN_ON(heap) )
865         {
866             WARN( "Heap %08lx: unaligned arena pointer %08lx\n",
867                   (DWORD)subheap->heap, (DWORD)pArena );
868             if ( TRACE_ON(heap) )
869                 HEAP_Dump( subheap->heap );
870         }
871         return FALSE;
872     }
873
874     /* Check magic number */
875     if (pArena->magic != ARENA_INUSE_MAGIC)
876     {
877         if (quiet == NOISY) {
878         ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
879                  (DWORD)subheap->heap, (DWORD)pArena );
880             if (TRACE_ON(heap))
881                HEAP_Dump( subheap->heap );
882         }  else if (WARN_ON(heap)) {
883             WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
884                  (DWORD)subheap->heap, (DWORD)pArena );
885             if (TRACE_ON(heap))
886                HEAP_Dump( subheap->heap );
887         }
888         return FALSE;
889     }
890     /* Check size flags */
891     if (pArena->size & ARENA_FLAG_FREE)
892     {
893         ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
894                  (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
895         return FALSE;
896     }
897     /* Check arena size */
898     if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
899     {
900         ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
901                  (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
902         return FALSE;
903     }
904     /* Check next arena PREV_FREE flag */
905     if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
906         (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
907     {
908         ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
909                  (DWORD)subheap->heap, (DWORD)pArena );
910         return FALSE;
911     }
912     /* Check prev free arena */
913     if (pArena->size & ARENA_FLAG_PREV_FREE)
914     {
915         const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
916         /* Check prev pointer */
917         if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
918         {
919             ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
920                     (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
921             return FALSE;
922         }
923         /* Check that prev arena is free */
924         if (!(pPrev->size & ARENA_FLAG_FREE) ||
925             (pPrev->magic != ARENA_FREE_MAGIC))
926         {
927             ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
928                      (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
929             return FALSE;
930         }
931         /* Check that prev arena is really the previous block */
932         if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
933         {
934             ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
935                      (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
936             return FALSE;
937         }
938     }
939     return TRUE;
940 }
941
942
943 /***********************************************************************
944  *           HEAP_IsRealArena  [Internal]
945  * Validates a block is a valid arena.
946  *
947  * RETURNS
948  *      TRUE: Success
949  *      FALSE: Failure
950  */
951 static BOOL HEAP_IsRealArena( HEAP *heapPtr,   /* [in] ptr to the heap */
952               DWORD flags,   /* [in] Bit flags that control access during operation */
953               LPCVOID block, /* [in] Optional pointer to memory block to validate */
954               BOOL quiet )   /* [in] Flag - if true, HEAP_ValidateInUseArena
955                               *             does not complain    */
956 {
957     SUBHEAP *subheap;
958     BOOL ret = TRUE;
959
960     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
961     {
962         ERR("Invalid heap %p!\n", heapPtr );
963         return FALSE;
964     }
965
966     flags &= HEAP_NO_SERIALIZE;
967     flags |= heapPtr->flags;
968     /* calling HeapLock may result in infinite recursion, so do the critsect directly */
969     if (!(flags & HEAP_NO_SERIALIZE))
970         RtlEnterCriticalSection( &heapPtr->critSection );
971
972     if (block)
973     {
974         /* Only check this single memory block */
975
976         if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
977             ((const char *)block < (char *)subheap + subheap->headerSize
978                                    + sizeof(ARENA_INUSE)))
979         {
980             if (quiet == NOISY)
981                 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
982             else if (WARN_ON(heap))
983                 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
984             ret = FALSE;
985         } else
986             ret = HEAP_ValidateInUseArena( subheap, (const ARENA_INUSE *)block - 1, quiet );
987
988         if (!(flags & HEAP_NO_SERIALIZE))
989             RtlLeaveCriticalSection( &heapPtr->critSection );
990         return ret;
991     }
992
993     subheap = &heapPtr->subheap;
994     while (subheap && ret)
995     {
996         char *ptr = (char *)subheap + subheap->headerSize;
997         while (ptr < (char *)subheap + subheap->size)
998         {
999             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1000             {
1001                 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1002                     ret = FALSE;
1003                     break;
1004                 }
1005                 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1006             }
1007             else
1008             {
1009                 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1010                     ret = FALSE;
1011                     break;
1012                 }
1013                 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1014             }
1015         }
1016         subheap = subheap->next;
1017     }
1018
1019     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1020     return ret;
1021 }
1022
1023
1024 /***********************************************************************
1025  *           RtlCreateHeap   (NTDLL.@)
1026  *
1027  * Create a new Heap.
1028  *
1029  * PARAMS
1030  *  flags      [I] HEAP_ flags from "winnt.h"
1031  *  addr       [I] Desired base address
1032  *  totalSize  [I] Total size of the heap, or 0 for a growable heap
1033  *  commitSize [I] Amount of heap space to commit
1034  *  unknown    [I] Not yet understood
1035  *  definition [I] Heap definition
1036  *
1037  * RETURNS
1038  *  Success: A HANDLE to the newly created heap.
1039  *  Failure: a NULL HANDLE.
1040  */
1041 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, ULONG totalSize, ULONG commitSize,
1042                              PVOID unknown, PRTL_HEAP_DEFINITION definition )
1043 {
1044     SUBHEAP *subheap;
1045
1046     /* Allocate the heap block */
1047
1048     if (!totalSize)
1049     {
1050         totalSize = HEAP_DEF_SIZE;
1051         flags |= HEAP_GROWABLE;
1052     }
1053
1054     if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1055
1056     /* link it into the per-process heap list */
1057     if (processHeap)
1058     {
1059         HEAP *heapPtr = subheap->heap;
1060         RtlLockHeap( processHeap );
1061         heapPtr->next = firstHeap;
1062         firstHeap = heapPtr;
1063         RtlUnlockHeap( processHeap );
1064     }
1065     else processHeap = subheap->heap;  /* assume the first heap we create is the process main heap */
1066
1067     return (HANDLE)subheap;
1068 }
1069
1070
1071 /***********************************************************************
1072  *           RtlDestroyHeap   (NTDLL.@)
1073  *
1074  * Destroy a Heap created with RtlCreateHeap().
1075  *
1076  * PARAMS
1077  *  heap [I] Heap to destroy.
1078  *
1079  * RETURNS
1080  *  Success: A NULL HANDLE, if heap is NULL or it was destroyed
1081  *  Failure: The Heap handle, if heap is the process heap.
1082  */
1083 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1084 {
1085     HEAP *heapPtr = HEAP_GetPtr( heap );
1086     SUBHEAP *subheap;
1087
1088     TRACE("%p\n", heap );
1089     if (!heapPtr) return heap;
1090
1091     if (heap == processHeap) return heap; /* cannot delete the main process heap */
1092     else /* remove it from the per-process list */
1093     {
1094         HEAP **pptr;
1095         RtlLockHeap( processHeap );
1096         pptr = &firstHeap;
1097         while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1098         if (*pptr) *pptr = (*pptr)->next;
1099         RtlUnlockHeap( processHeap );
1100     }
1101
1102     RtlDeleteCriticalSection( &heapPtr->critSection );
1103     subheap = &heapPtr->subheap;
1104     while (subheap)
1105     {
1106         SUBHEAP *next = subheap->next;
1107         ULONG size = 0;
1108         void *addr = subheap;
1109         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1110         subheap = next;
1111     }
1112     return 0;
1113 }
1114
1115
1116 /***********************************************************************
1117  *           RtlAllocateHeap   (NTDLL.@)
1118  *
1119  * Allocate a memory block from a Heap.
1120  *
1121  * PARAMS
1122  *  heap  [I] Heap to allocate block from
1123  *  flags [I] HEAP_ flags from "winnt.h"
1124  *  size  [I] Size of the memory block to allocate
1125  *
1126  * RETURNS
1127  *  Success: A pointer to the newly allocated block
1128  *  Failure: NULL.
1129  *
1130  * NOTES
1131  *  This call does not SetLastError().
1132  */
1133 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, ULONG size )
1134 {
1135     ARENA_FREE *pArena;
1136     ARENA_INUSE *pInUse;
1137     SUBHEAP *subheap;
1138     HEAP *heapPtr = HEAP_GetPtr( heap );
1139
1140     /* Validate the parameters */
1141
1142     if (!heapPtr) return NULL;
1143     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1144     flags |= heapPtr->flags;
1145     size = ROUND_SIZE(size);
1146     if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1147
1148     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1149     /* Locate a suitable free block */
1150
1151     if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1152     {
1153         TRACE("(%p,%08lx,%08lx): returning NULL\n",
1154                   heap, flags, size  );
1155         if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1156         if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1157         return NULL;
1158     }
1159
1160     /* Remove the arena from the free list */
1161
1162     pArena->next->prev = pArena->prev;
1163     pArena->prev->next = pArena->next;
1164
1165     /* Build the in-use arena */
1166
1167     pInUse = (ARENA_INUSE *)pArena;
1168
1169     /* in-use arena is smaller than free arena,
1170      * so we have to add the difference to the size */
1171     pInUse->size  = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1172     pInUse->magic = ARENA_INUSE_MAGIC;
1173
1174     /* Shrink the block */
1175
1176     HEAP_ShrinkBlock( subheap, pInUse, size );
1177
1178     if (flags & HEAP_ZERO_MEMORY)
1179         clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1180     else
1181         mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1182
1183     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1184
1185     TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1186                   heap, flags, size, (DWORD)(pInUse + 1) );
1187     return (LPVOID)(pInUse + 1);
1188 }
1189
1190
1191 /***********************************************************************
1192  *           RtlFreeHeap   (NTDLL.@)
1193  *
1194  * Free a memory block allocated with RtlAllocateHeap().
1195  *
1196  * PARAMS
1197  *  heap  [I] Heap that block was allocated from
1198  *  flags [I] HEAP_ flags from "winnt.h"
1199  *  ptr   [I] Block to free
1200  *
1201  * RETURNS
1202  *  Success: TRUE, if ptr is NULL or was freed successfully.
1203  *  Failure: FALSE.
1204  */
1205 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1206 {
1207     ARENA_INUSE *pInUse;
1208     SUBHEAP *subheap;
1209     HEAP *heapPtr;
1210
1211     /* Validate the parameters */
1212
1213     if (!ptr) return TRUE;  /* freeing a NULL ptr isn't an error in Win2k */
1214
1215     heapPtr = HEAP_GetPtr( heap );
1216     if (!heapPtr)
1217     {
1218         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1219         return FALSE;
1220     }
1221
1222     flags &= HEAP_NO_SERIALIZE;
1223     flags |= heapPtr->flags;
1224     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1225     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1226     {
1227         if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1228         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1229         TRACE("(%p,%08lx,%08lx): returning FALSE\n",
1230                       heap, flags, (DWORD)ptr );
1231         return FALSE;
1232     }
1233
1234     /* Turn the block into a free block */
1235
1236     pInUse  = (ARENA_INUSE *)ptr - 1;
1237     subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1238     HEAP_MakeInUseBlockFree( subheap, pInUse );
1239
1240     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1241
1242     TRACE("(%p,%08lx,%08lx): returning TRUE\n",
1243                   heap, flags, (DWORD)ptr );
1244     return TRUE;
1245 }
1246
1247
1248 /***********************************************************************
1249  *           RtlReAllocateHeap   (NTDLL.@)
1250  *
1251  * Change the size of a memory block allocated with RtlAllocateHeap().
1252  *
1253  * PARAMS
1254  *  heap  [I] Heap that block was allocated from
1255  *  flags [I] HEAP_ flags from "winnt.h"
1256  *  ptr   [I] Block to resize
1257  *  size  [I] Size of the memory block to allocate
1258  *
1259  * RETURNS
1260  *  Success: A pointer to the resized block (which may be different).
1261  *  Failure: NULL.
1262  */
1263 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, ULONG size )
1264 {
1265     ARENA_INUSE *pArena;
1266     DWORD oldSize;
1267     HEAP *heapPtr;
1268     SUBHEAP *subheap;
1269
1270     if (!ptr) return NULL;
1271     if (!(heapPtr = HEAP_GetPtr( heap )))
1272     {
1273         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1274         return NULL;
1275     }
1276
1277     /* Validate the parameters */
1278
1279     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1280              HEAP_REALLOC_IN_PLACE_ONLY;
1281     flags |= heapPtr->flags;
1282     size = ROUND_SIZE(size);
1283     if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1284
1285     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1286     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1287     {
1288         if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1289         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1290         TRACE("(%p,%08lx,%08lx,%08lx): returning NULL\n",
1291                       heap, flags, (DWORD)ptr, size );
1292         return NULL;
1293     }
1294
1295     /* Check if we need to grow the block */
1296
1297     pArena = (ARENA_INUSE *)ptr - 1;
1298     subheap = HEAP_FindSubHeap( heapPtr, pArena );
1299     oldSize = (pArena->size & ARENA_SIZE_MASK);
1300     if (size > oldSize)
1301     {
1302         char *pNext = (char *)(pArena + 1) + oldSize;
1303         if ((pNext < (char *)subheap + subheap->size) &&
1304             (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1305             (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1306         {
1307             /* The next block is free and large enough */
1308             ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1309             pFree->next->prev = pFree->prev;
1310             pFree->prev->next = pFree->next;
1311             pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1312             if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1313                                                + size + HEAP_MIN_BLOCK_SIZE))
1314             {
1315                 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1316                 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1317                 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1318                 return NULL;
1319             }
1320             HEAP_ShrinkBlock( subheap, pArena, size );
1321         }
1322         else  /* Do it the hard way */
1323         {
1324             ARENA_FREE *pNew;
1325             ARENA_INUSE *pInUse;
1326             SUBHEAP *newsubheap;
1327
1328             if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1329                 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1330             {
1331                 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1332                 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1333                 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1334                 return NULL;
1335             }
1336
1337             /* Build the in-use arena */
1338
1339             pNew->next->prev = pNew->prev;
1340             pNew->prev->next = pNew->next;
1341             pInUse = (ARENA_INUSE *)pNew;
1342             pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1343                            + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1344             pInUse->magic = ARENA_INUSE_MAGIC;
1345             HEAP_ShrinkBlock( newsubheap, pInUse, size );
1346             mark_block_initialized( pInUse + 1, oldSize );
1347             memcpy( pInUse + 1, pArena + 1, oldSize );
1348
1349             /* Free the previous block */
1350
1351             HEAP_MakeInUseBlockFree( subheap, pArena );
1352             subheap = newsubheap;
1353             pArena  = pInUse;
1354         }
1355     }
1356     else HEAP_ShrinkBlock( subheap, pArena, size );  /* Shrink the block */
1357
1358     /* Clear the extra bytes if needed */
1359
1360     if (size > oldSize)
1361     {
1362         if (flags & HEAP_ZERO_MEMORY)
1363             clear_block( (char *)(pArena + 1) + oldSize,
1364                          (pArena->size & ARENA_SIZE_MASK) - oldSize );
1365         else
1366             mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1367                                       (pArena->size & ARENA_SIZE_MASK) - oldSize );
1368     }
1369
1370     /* Return the new arena */
1371
1372     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1373
1374     TRACE("(%p,%08lx,%08lx,%08lx): returning %08lx\n",
1375                   heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1376     return (LPVOID)(pArena + 1);
1377 }
1378
1379
1380 /***********************************************************************
1381  *           RtlCompactHeap   (NTDLL.@)
1382  *
1383  * Compact the free space in a Heap.
1384  *
1385  * PARAMS
1386  *  heap  [I] Heap that block was allocated from
1387  *  flags [I] HEAP_ flags from "winnt.h"
1388  *
1389  * RETURNS
1390  *  The number of bytes compacted.
1391  *
1392  * NOTES
1393  *  This function is a harmless stub.
1394  */
1395 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1396 {
1397     FIXME( "stub\n" );
1398     return 0;
1399 }
1400
1401
1402 /***********************************************************************
1403  *           RtlLockHeap   (NTDLL.@)
1404  *
1405  * Lock a Heap.
1406  *
1407  * PARAMS
1408  *  heap  [I] Heap to lock
1409  *
1410  * RETURNS
1411  *  Success: TRUE. The Heap is locked.
1412  *  Failure: FALSE, if heap is invalid.
1413  */
1414 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1415 {
1416     HEAP *heapPtr = HEAP_GetPtr( heap );
1417     if (!heapPtr) return FALSE;
1418     RtlEnterCriticalSection( &heapPtr->critSection );
1419     return TRUE;
1420 }
1421
1422
1423 /***********************************************************************
1424  *           RtlUnlockHeap   (NTDLL.@)
1425  *
1426  * Unlock a Heap.
1427  *
1428  * PARAMS
1429  *  heap  [I] Heap to unlock
1430  *
1431  * RETURNS
1432  *  Success: TRUE. The Heap is unlocked.
1433  *  Failure: FALSE, if heap is invalid.
1434  */
1435 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1436 {
1437     HEAP *heapPtr = HEAP_GetPtr( heap );
1438     if (!heapPtr) return FALSE;
1439     RtlLeaveCriticalSection( &heapPtr->critSection );
1440     return TRUE;
1441 }
1442
1443
1444 /***********************************************************************
1445  *           RtlSizeHeap   (NTDLL.@)
1446  *
1447  * Get the actual size of a memory block allocated from a Heap.
1448  *
1449  * PARAMS
1450  *  heap  [I] Heap that block was allocated from
1451  *  flags [I] HEAP_ flags from "winnt.h"
1452  *  ptr   [I] Block to get the size of
1453  *
1454  * RETURNS
1455  *  Success: The size of the block.
1456  *  Failure: -1, heap or ptr are invalid.
1457  *
1458  * NOTES
1459  *  The size may be bigger than what was passed to RtlAllocateHeap().
1460  */
1461 ULONG WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1462 {
1463     DWORD ret;
1464     HEAP *heapPtr = HEAP_GetPtr( heap );
1465
1466     if (!heapPtr)
1467     {
1468         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1469         return (ULONG)-1;
1470     }
1471     flags &= HEAP_NO_SERIALIZE;
1472     flags |= heapPtr->flags;
1473     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1474     if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1475     {
1476         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1477         ret = (ULONG)-1;
1478     }
1479     else
1480     {
1481         ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1482         ret = pArena->size & ARENA_SIZE_MASK;
1483     }
1484     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1485
1486     TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1487                   heap, flags, (DWORD)ptr, ret );
1488     return ret;
1489 }
1490
1491
1492 /***********************************************************************
1493  *           RtlValidateHeap   (NTDLL.@)
1494  *
1495  * Determine if a block is a valid allocation from a heap.
1496  *
1497  * PARAMS
1498  *  heap  [I] Heap that block was allocated from
1499  *  flags [I] HEAP_ flags from "winnt.h"
1500  *  ptr   [I] Block to check
1501  *
1502  * RETURNS
1503  *  Success: TRUE. The block was allocated from heap.
1504  *  Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1505  */
1506 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1507 {
1508     HEAP *heapPtr = HEAP_GetPtr( heap );
1509     if (!heapPtr) return FALSE;
1510     return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1511 }
1512
1513
1514 /***********************************************************************
1515  *           RtlWalkHeap    (NTDLL.@)
1516  *
1517  * FIXME
1518  *  The PROCESS_HEAP_ENTRY flag values seem different between this
1519  *  function and HeapWalk(). To be checked.
1520  */
1521 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1522 {
1523     LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1524     HEAP *heapPtr = HEAP_GetPtr(heap);
1525     SUBHEAP *sub, *currentheap = NULL;
1526     NTSTATUS ret;
1527     char *ptr;
1528     int region_index = 0;
1529
1530     if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1531
1532     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1533
1534     /* set ptr to the next arena to be examined */
1535
1536     if (!entry->lpData) /* first call (init) ? */
1537     {
1538         TRACE("begin walking of heap %p.\n", heap);
1539         currentheap = &heapPtr->subheap;
1540         ptr = (char*)currentheap + currentheap->headerSize;
1541     }
1542     else
1543     {
1544         ptr = entry->lpData;
1545         sub = &heapPtr->subheap;
1546         while (sub)
1547         {
1548             if (((char *)ptr >= (char *)sub) &&
1549                 ((char *)ptr < (char *)sub + sub->size))
1550             {
1551                 currentheap = sub;
1552                 break;
1553             }
1554             sub = sub->next;
1555             region_index++;
1556         }
1557         if (currentheap == NULL)
1558         {
1559             ERR("no matching subheap found, shouldn't happen !\n");
1560             ret = STATUS_NO_MORE_ENTRIES;
1561             goto HW_end;
1562         }
1563
1564         ptr += entry->cbData; /* point to next arena */
1565         if (ptr > (char *)currentheap + currentheap->size - 1)
1566         {   /* proceed with next subheap */
1567             if (!(currentheap = currentheap->next))
1568             {  /* successfully finished */
1569                 TRACE("end reached.\n");
1570                 ret = STATUS_NO_MORE_ENTRIES;
1571                 goto HW_end;
1572             }
1573             ptr = (char*)currentheap + currentheap->headerSize;
1574         }
1575     }
1576
1577     entry->wFlags = 0;
1578     if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1579     {
1580         ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1581
1582         /*TRACE("free, magic: %04x\n", pArena->magic);*/
1583
1584         entry->lpData = pArena + 1;
1585         entry->cbData = pArena->size & ARENA_SIZE_MASK;
1586         entry->cbOverhead = sizeof(ARENA_FREE);
1587         entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1588     }
1589     else
1590     {
1591         ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1592
1593         /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1594
1595         entry->lpData = pArena + 1;
1596         entry->cbData = pArena->size & ARENA_SIZE_MASK;
1597         entry->cbOverhead = sizeof(ARENA_INUSE);
1598         entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1599         /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1600         and PROCESS_HEAP_ENTRY_DDESHARE yet */
1601     }
1602
1603     entry->iRegionIndex = region_index;
1604
1605     /* first element of heap ? */
1606     if (ptr == (char *)(currentheap + currentheap->headerSize))
1607     {
1608         entry->wFlags |= PROCESS_HEAP_REGION;
1609         entry->u.Region.dwCommittedSize = currentheap->commitSize;
1610         entry->u.Region.dwUnCommittedSize =
1611                 currentheap->size - currentheap->commitSize;
1612         entry->u.Region.lpFirstBlock = /* first valid block */
1613                 currentheap + currentheap->headerSize;
1614         entry->u.Region.lpLastBlock  = /* first invalid block */
1615                 currentheap + currentheap->size;
1616     }
1617     ret = STATUS_SUCCESS;
1618     if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1619
1620 HW_end:
1621     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1622     return ret;
1623 }
1624
1625
1626 /***********************************************************************
1627  *           RtlGetProcessHeaps    (NTDLL.@)
1628  *
1629  * Get the Heaps belonging to the current process.
1630  *
1631  * PARAMS
1632  *  count [I] size of heaps
1633  *  heaps [O] Destination array for heap HANDLE's
1634  *
1635  * RETURNS
1636  *  Success: The number of Heaps allocated by the process.
1637  *  Failure: 0.
1638  */
1639 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1640 {
1641     DWORD total;
1642     HEAP *ptr;
1643
1644     if (!processHeap) return 0;  /* should never happen */
1645     total = 1;  /* main heap */
1646     RtlLockHeap( processHeap );
1647     for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1648     if (total <= count)
1649     {
1650         *heaps++ = (HANDLE)processHeap;
1651         for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1652     }
1653     RtlUnlockHeap( processHeap );
1654     return total;
1655 }