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