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