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