msvcrt: Added basic _popen tests.
[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 #include "wine/port.h"
24
25 #include <assert.h>
26 #include <stdlib.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <string.h>
30 #ifdef HAVE_VALGRIND_MEMCHECK_H
31 #include <valgrind/memcheck.h>
32 #else
33 #define RUNNING_ON_VALGRIND 0
34 #endif
35
36 #define NONAMELESSUNION
37 #define NONAMELESSSTRUCT
38 #include "ntstatus.h"
39 #define WIN32_NO_STATUS
40 #include "windef.h"
41 #include "winnt.h"
42 #include "winternl.h"
43 #include "ntdll_misc.h"
44 #include "wine/list.h"
45 #include "wine/debug.h"
46 #include "wine/server.h"
47
48 WINE_DEFAULT_DEBUG_CHANNEL(heap);
49
50 /* Note: the heap data structures are loosely based on what Pietrek describes in his
51  * book 'Windows 95 System Programming Secrets', with some adaptations for
52  * better compatibility with NT.
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 typedef struct
70 {
71     struct list           entry;      /* entry in heap large blocks list */
72     SIZE_T                data_size;  /* size of user data */
73     SIZE_T                block_size; /* total size of virtual memory block */
74     DWORD                 pad[2];     /* padding to ensure 16-byte alignment of data */
75     DWORD                 size;       /* fields for compatibility with normal arenas */
76     DWORD                 magic;      /* these must remain at the end of the structure */
77 } ARENA_LARGE;
78
79 #define ARENA_FLAG_FREE        0x00000001  /* flags OR'ed with arena size */
80 #define ARENA_FLAG_PREV_FREE   0x00000002
81 #define ARENA_SIZE_MASK        (~3)
82 #define ARENA_LARGE_SIZE       0xfedcba90  /* magic value for 'size' field in large blocks */
83
84 /* Value for arena 'magic' field */
85 #define ARENA_INUSE_MAGIC      0x455355
86 #define ARENA_PENDING_MAGIC    0xbedead
87 #define ARENA_FREE_MAGIC       0x45455246
88 #define ARENA_LARGE_MAGIC      0x6752614c
89
90 #define ARENA_INUSE_FILLER     0x55
91 #define ARENA_TAIL_FILLER      0xab
92 #define ARENA_FREE_FILLER      0xfeeefeee
93
94 /* everything is aligned on 8 byte boundaries (16 for Win64) */
95 #define ALIGNMENT              (2*sizeof(void*))
96 #define LARGE_ALIGNMENT        16  /* large blocks have stricter alignment */
97 #define ARENA_OFFSET           (ALIGNMENT - sizeof(ARENA_INUSE))
98
99 C_ASSERT( sizeof(ARENA_LARGE) % LARGE_ALIGNMENT == 0 );
100
101 #define ROUND_SIZE(size)       ((((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1)) + ARENA_OFFSET)
102
103 #define QUIET                  1           /* Suppress messages  */
104 #define NOISY                  0           /* Report all errors  */
105
106 /* minimum data size (without arenas) of an allocated block */
107 /* make sure that it's larger than a free list entry */
108 #define HEAP_MIN_DATA_SIZE    ROUND_SIZE(2 * sizeof(struct list))
109 /* minimum size that must remain to shrink an allocated block */
110 #define HEAP_MIN_SHRINK_SIZE  (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
111 /* minimum size to start allocating large blocks */
112 #define HEAP_MIN_LARGE_BLOCK_SIZE  0x7f000
113 /* extra size to add at the end of block for tail checking */
114 #define HEAP_TAIL_EXTRA_SIZE(flags) \
115     ((flags & HEAP_TAIL_CHECKING_ENABLED) || RUNNING_ON_VALGRIND ? ALIGNMENT : 0)
116
117 /* Max size of the blocks on the free lists */
118 static const SIZE_T HEAP_freeListSizes[] =
119 {
120     0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
121 };
122 #define HEAP_NB_FREE_LISTS  (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
123
124 typedef union
125 {
126     ARENA_FREE  arena;
127     void       *alignment[4];
128 } FREE_LIST_ENTRY;
129
130 struct tagHEAP;
131
132 typedef struct tagSUBHEAP
133 {
134     void               *base;       /* Base address of the sub-heap memory block */
135     SIZE_T              size;       /* Size of the whole sub-heap */
136     SIZE_T              min_commit; /* Minimum committed size */
137     SIZE_T              commitSize; /* Committed size of the sub-heap */
138     struct list         entry;      /* Entry in sub-heap list */
139     struct tagHEAP     *heap;       /* Main heap structure */
140     DWORD               headerSize; /* Size of the heap header */
141     DWORD               magic;      /* Magic number */
142 } SUBHEAP;
143
144 #define SUBHEAP_MAGIC    ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
145
146 typedef struct tagHEAP
147 {
148     DWORD_PTR        unknown1[2];
149     DWORD            unknown2;
150     DWORD            flags;         /* Heap flags */
151     DWORD            force_flags;   /* Forced heap flags for debugging */
152     SUBHEAP          subheap;       /* First sub-heap */
153     struct list      entry;         /* Entry in process heap list */
154     struct list      subheap_list;  /* Sub-heap list */
155     struct list      large_list;    /* Large blocks list */
156     SIZE_T           grow_size;     /* Size of next subheap for growing heap */
157     DWORD            magic;         /* Magic number */
158     DWORD            pending_pos;   /* Position in pending free requests ring */
159     ARENA_INUSE    **pending_free;  /* Ring buffer for pending free requests */
160     RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
161     FREE_LIST_ENTRY *freeList;      /* Free lists */
162 } HEAP;
163
164 #define HEAP_MAGIC       ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
165
166 #define HEAP_DEF_SIZE        0x110000   /* Default heap size = 1Mb + 64Kb */
167 #define COMMIT_MASK          0xffff  /* bitmask for commit/decommit granularity */
168 #define MAX_FREE_PENDING     1024    /* max number of free requests to delay */
169
170 /* some undocumented flags (names are made up) */
171 #define HEAP_PAGE_ALLOCS      0x01000000
172 #define HEAP_VALIDATE         0x10000000
173 #define HEAP_VALIDATE_ALL     0x20000000
174 #define HEAP_VALIDATE_PARAMS  0x40000000
175
176 static HEAP *processHeap;  /* main process heap */
177
178 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
179
180 /* mark a block of memory as free for debugging purposes */
181 static inline void mark_block_free( void *ptr, SIZE_T size, DWORD flags )
182 {
183     if (flags & HEAP_FREE_CHECKING_ENABLED)
184     {
185         SIZE_T i;
186         for (i = 0; i < size / sizeof(DWORD); i++) ((DWORD *)ptr)[i] = ARENA_FREE_FILLER;
187     }
188 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
189     VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
190 #elif defined( VALGRIND_MAKE_NOACCESS)
191     VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
192 #endif
193 }
194
195 /* mark a block of memory as initialized for debugging purposes */
196 static inline void mark_block_initialized( void *ptr, SIZE_T size )
197 {
198 #if defined(VALGRIND_MAKE_MEM_DEFINED)
199     VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
200 #elif defined(VALGRIND_MAKE_READABLE)
201     VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
202 #endif
203 }
204
205 /* mark a block of memory as uninitialized for debugging purposes */
206 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
207 {
208 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
209     VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
210 #elif defined(VALGRIND_MAKE_WRITABLE)
211     VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
212 #endif
213 }
214
215 /* mark a block of memory as a tail block */
216 static inline void mark_block_tail( void *ptr, SIZE_T size, DWORD flags )
217 {
218     if (flags & HEAP_TAIL_CHECKING_ENABLED)
219     {
220         mark_block_uninitialized( ptr, size );
221         memset( ptr, ARENA_TAIL_FILLER, size );
222     }
223 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
224     VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
225 #elif defined( VALGRIND_MAKE_NOACCESS)
226     VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
227 #endif
228 }
229
230 /* initialize contents of a newly created block of memory */
231 static inline void initialize_block( void *ptr, SIZE_T size, SIZE_T unused, DWORD flags )
232 {
233     if (flags & HEAP_ZERO_MEMORY)
234     {
235         mark_block_initialized( ptr, size );
236         memset( ptr, 0, size );
237     }
238     else
239     {
240         mark_block_uninitialized( ptr, size );
241         if (flags & HEAP_FREE_CHECKING_ENABLED)
242         {
243             memset( ptr, ARENA_INUSE_FILLER, size );
244             mark_block_uninitialized( ptr, size );
245         }
246     }
247
248     mark_block_tail( (char *)ptr + size, unused, flags );
249 }
250
251 /* notify that a new block of memory has been allocated for debugging purposes */
252 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
253 {
254 #ifdef VALGRIND_MALLOCLIKE_BLOCK
255     VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
256 #endif
257 }
258
259 /* notify that a block of memory has been freed for debugging purposes */
260 static inline void notify_free( void const *ptr )
261 {
262 #ifdef VALGRIND_FREELIKE_BLOCK
263     VALGRIND_FREELIKE_BLOCK( ptr, 0 );
264 #endif
265 }
266
267 static inline void notify_realloc( void const *ptr, SIZE_T size_old, SIZE_T size_new )
268 {
269 #ifdef VALGRIND_RESIZEINPLACE_BLOCK
270     VALGRIND_RESIZEINPLACE_BLOCK( ptr, size_old, size_new, 0 );
271 #endif
272 }
273
274 static void subheap_notify_free_all(SUBHEAP const *subheap)
275 {
276 #ifdef VALGRIND_FREELIKE_BLOCK
277     char const *ptr = (char const *)subheap->base + subheap->headerSize;
278
279     if (!RUNNING_ON_VALGRIND) return;
280
281     while (ptr < (char const *)subheap->base + subheap->size)
282     {
283         if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
284         {
285             ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
286             if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
287             ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
288         }
289         else
290         {
291             ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
292             if (pArena->magic == ARENA_INUSE_MAGIC) notify_free(pArena + 1);
293             else if (pArena->magic != ARENA_PENDING_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
294             ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
295         }
296     }
297 #endif
298 }
299
300 /* locate a free list entry of the appropriate size */
301 /* size is the size of the whole block including the arena header */
302 static inline unsigned int get_freelist_index( SIZE_T size )
303 {
304     unsigned int i;
305
306     size -= sizeof(ARENA_FREE);
307     for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
308     return i;
309 }
310
311 /* get the memory protection type to use for a given heap */
312 static inline ULONG get_protection_type( DWORD flags )
313 {
314     return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
315 }
316
317 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
318 {
319     0, 0, NULL,  /* will be set later */
320     { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
321       0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
322 };
323
324
325 /***********************************************************************
326  *           HEAP_Dump
327  */
328 static void HEAP_Dump( HEAP *heap )
329 {
330     unsigned int i;
331     SUBHEAP *subheap;
332     char *ptr;
333
334     DPRINTF( "Heap: %p\n", heap );
335     DPRINTF( "Next: %p  Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
336     LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
337
338     DPRINTF( "\nFree lists:\n Block   Stat   Size    Id\n" );
339     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
340         DPRINTF( "%p free %08lx prev=%p next=%p\n",
341                  &heap->freeList[i].arena, HEAP_freeListSizes[i],
342                  LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
343                  LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
344
345     LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
346     {
347         SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
348         DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
349                  subheap, subheap->base, subheap->size, subheap->commitSize );
350
351         DPRINTF( "\n Block    Arena   Stat   Size    Id\n" );
352         ptr = (char *)subheap->base + subheap->headerSize;
353         while (ptr < (char *)subheap->base + subheap->size)
354         {
355             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
356             {
357                 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
358                 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
359                          pArena, pArena->magic,
360                          pArena->size & ARENA_SIZE_MASK,
361                          LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
362                          LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
363                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
364                 arenaSize += sizeof(ARENA_FREE);
365                 freeSize += pArena->size & ARENA_SIZE_MASK;
366             }
367             else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
368             {
369                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
370                 DPRINTF( "%p %08x Used %08x back=%p\n",
371                         pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
372                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
373                 arenaSize += sizeof(ARENA_INUSE);
374                 usedSize += pArena->size & ARENA_SIZE_MASK;
375             }
376             else
377             {
378                 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
379                 DPRINTF( "%p %08x %s %08x\n",
380                          pArena, pArena->magic, pArena->magic == ARENA_INUSE_MAGIC ? "used" : "pend",
381                          pArena->size & ARENA_SIZE_MASK );
382                 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
383                 arenaSize += sizeof(ARENA_INUSE);
384                 usedSize += pArena->size & ARENA_SIZE_MASK;
385             }
386         }
387         DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
388               subheap->size, subheap->commitSize, freeSize, usedSize,
389               arenaSize, (arenaSize * 100) / subheap->size );
390     }
391 }
392
393
394 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
395 {
396     WORD rem_flags;
397     TRACE( "Dumping entry %p\n", entry );
398     TRACE( "lpData\t\t: %p\n", entry->lpData );
399     TRACE( "cbData\t\t: %08x\n", entry->cbData);
400     TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
401     TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
402     TRACE( "WFlags\t\t: ");
403     if (entry->wFlags & PROCESS_HEAP_REGION)
404         TRACE( "PROCESS_HEAP_REGION ");
405     if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
406         TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
407     if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
408         TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
409     if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
410         TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
411     if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
412         TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
413     rem_flags = entry->wFlags &
414         ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
415           PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
416           PROCESS_HEAP_ENTRY_DDESHARE);
417     if (rem_flags)
418         TRACE( "Unknown %08x", rem_flags);
419     TRACE( "\n");
420     if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
421         && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
422     {
423         /* Treat as block */
424         TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
425     }
426     if (entry->wFlags & PROCESS_HEAP_REGION)
427     {
428         TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
429         TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
430         TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
431         TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
432     }
433 }
434
435 /***********************************************************************
436  *           HEAP_GetPtr
437  * RETURNS
438  *      Pointer to the heap
439  *      NULL: Failure
440  */
441 static HEAP *HEAP_GetPtr(
442              HANDLE heap /* [in] Handle to the heap */
443 ) {
444     HEAP *heapPtr = heap;
445     if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
446     {
447         ERR("Invalid heap %p!\n", heap );
448         return NULL;
449     }
450     if ((heapPtr->flags & HEAP_VALIDATE_ALL) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
451     {
452         if (TRACE_ON(heap))
453         {
454             HEAP_Dump( heapPtr );
455             assert( FALSE );
456         }
457         return NULL;
458     }
459     return heapPtr;
460 }
461
462
463 /***********************************************************************
464  *           HEAP_InsertFreeBlock
465  *
466  * Insert a free block into the free list.
467  */
468 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
469 {
470     FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
471     if (last)
472     {
473         /* insert at end of free list, i.e. before the next free list entry */
474         pEntry++;
475         if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
476         list_add_before( &pEntry->arena.entry, &pArena->entry );
477     }
478     else
479     {
480         /* insert at head of free list */
481         list_add_after( &pEntry->arena.entry, &pArena->entry );
482     }
483     pArena->size |= ARENA_FLAG_FREE;
484 }
485
486
487 /***********************************************************************
488  *           HEAP_FindSubHeap
489  * Find the sub-heap containing a given address.
490  *
491  * RETURNS
492  *      Pointer: Success
493  *      NULL: Failure
494  */
495 static SUBHEAP *HEAP_FindSubHeap(
496                 const HEAP *heap, /* [in] Heap pointer */
497                 LPCVOID ptr ) /* [in] Address */
498 {
499     SUBHEAP *sub;
500     LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
501         if ((ptr >= sub->base) &&
502             ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
503             return sub;
504     return NULL;
505 }
506
507
508 /***********************************************************************
509  *           HEAP_Commit
510  *
511  * Make sure the heap storage is committed for a given size in the specified arena.
512  */
513 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
514 {
515     void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
516     SIZE_T size = (char *)ptr - (char *)subheap->base;
517     size = (size + COMMIT_MASK) & ~COMMIT_MASK;
518     if (size > subheap->size) size = subheap->size;
519     if (size <= subheap->commitSize) return TRUE;
520     size -= subheap->commitSize;
521     ptr = (char *)subheap->base + subheap->commitSize;
522     if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
523                                  &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
524     {
525         WARN("Could not commit %08lx bytes at %p for heap %p\n",
526                  size, ptr, subheap->heap );
527         return FALSE;
528     }
529     subheap->commitSize += size;
530     return TRUE;
531 }
532
533
534 /***********************************************************************
535  *           HEAP_Decommit
536  *
537  * If possible, decommit the heap storage from (including) 'ptr'.
538  */
539 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
540 {
541     void *addr;
542     SIZE_T decommit_size;
543     SIZE_T size = (char *)ptr - (char *)subheap->base;
544
545     /* round to next block and add one full block */
546     size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
547     size = max( size, subheap->min_commit );
548     if (size >= subheap->commitSize) return TRUE;
549     decommit_size = subheap->commitSize - size;
550     addr = (char *)subheap->base + size;
551
552     if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
553     {
554         WARN("Could not decommit %08lx bytes at %p for heap %p\n",
555              decommit_size, (char *)subheap->base + size, subheap->heap );
556         return FALSE;
557     }
558     subheap->commitSize -= decommit_size;
559     return TRUE;
560 }
561
562
563 /***********************************************************************
564  *           HEAP_CreateFreeBlock
565  *
566  * Create a free block at a specified address. 'size' is the size of the
567  * whole block, including the new arena.
568  */
569 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
570 {
571     ARENA_FREE *pFree;
572     char *pEnd;
573     BOOL last;
574     DWORD flags = subheap->heap->flags;
575
576     /* Create a free arena */
577     mark_block_uninitialized( ptr, sizeof(ARENA_FREE) );
578     pFree = ptr;
579     pFree->magic = ARENA_FREE_MAGIC;
580
581     /* If debugging, erase the freed block content */
582
583     pEnd = (char *)ptr + size;
584     if (pEnd > (char *)subheap->base + subheap->commitSize)
585         pEnd = (char *)subheap->base + subheap->commitSize;
586     if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1), flags );
587
588     /* Check if next block is free also */
589
590     if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
591         (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
592     {
593         /* Remove the next arena from the free list */
594         ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
595         list_remove( &pNext->entry );
596         size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
597         mark_block_free( pNext, sizeof(ARENA_FREE), flags );
598     }
599
600     /* Set the next block PREV_FREE flag and pointer */
601
602     last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
603     if (!last)
604     {
605         DWORD *pNext = (DWORD *)((char *)ptr + size);
606         *pNext |= ARENA_FLAG_PREV_FREE;
607         mark_block_initialized( (ARENA_FREE **)pNext - 1, sizeof( ARENA_FREE * ) );
608         *((ARENA_FREE **)pNext - 1) = pFree;
609     }
610
611     /* Last, insert the new block into the free list */
612
613     pFree->size = size - sizeof(*pFree);
614     HEAP_InsertFreeBlock( subheap->heap, pFree, last );
615 }
616
617
618 /***********************************************************************
619  *           HEAP_MakeInUseBlockFree
620  *
621  * Turn an in-use block into a free block. Can also decommit the end of
622  * the heap, and possibly even free the sub-heap altogether.
623  */
624 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
625 {
626     HEAP *heap = subheap->heap;
627     ARENA_FREE *pFree;
628     SIZE_T size;
629
630     if (heap->pending_free)
631     {
632         ARENA_INUSE *prev = heap->pending_free[heap->pending_pos];
633         heap->pending_free[heap->pending_pos] = pArena;
634         heap->pending_pos = (heap->pending_pos + 1) % MAX_FREE_PENDING;
635         pArena->magic = ARENA_PENDING_MAGIC;
636         mark_block_free( pArena + 1, pArena->size & ARENA_SIZE_MASK, heap->flags );
637         if (!prev) return;
638         pArena = prev;
639         subheap = HEAP_FindSubHeap( heap, pArena );
640     }
641
642     /* Check if we can merge with previous block */
643
644     size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
645     if (pArena->size & ARENA_FLAG_PREV_FREE)
646     {
647         pFree = *((ARENA_FREE **)pArena - 1);
648         size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
649         /* Remove it from the free list */
650         list_remove( &pFree->entry );
651     }
652     else pFree = (ARENA_FREE *)pArena;
653
654     /* Create a free block */
655
656     HEAP_CreateFreeBlock( subheap, pFree, size );
657     size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
658     if ((char *)pFree + size < (char *)subheap->base + subheap->size)
659         return;  /* Not the last block, so nothing more to do */
660
661     /* Free the whole sub-heap if it's empty and not the original one */
662
663     if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
664         (subheap != &subheap->heap->subheap))
665     {
666         void *addr = subheap->base;
667
668         size = 0;
669         /* Remove the free block from the list */
670         list_remove( &pFree->entry );
671         /* Remove the subheap from the list */
672         list_remove( &subheap->entry );
673         /* Free the memory */
674         subheap->magic = 0;
675         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
676         return;
677     }
678
679     /* Decommit the end of the heap */
680
681     if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
682 }
683
684
685 /***********************************************************************
686  *           HEAP_ShrinkBlock
687  *
688  * Shrink an in-use block.
689  */
690 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
691 {
692     if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
693     {
694         HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
695                               (pArena->size & ARENA_SIZE_MASK) - size );
696         /* assign size plus previous arena flags */
697         pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
698     }
699     else
700     {
701         /* Turn off PREV_FREE flag in next block */
702         char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
703         if (pNext < (char *)subheap->base + subheap->size)
704             *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
705     }
706 }
707
708
709 /***********************************************************************
710  *           allocate_large_block
711  */
712 static void *allocate_large_block( HEAP *heap, DWORD flags, SIZE_T size )
713 {
714     ARENA_LARGE *arena;
715     SIZE_T block_size = sizeof(*arena) + ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE(flags);
716     LPVOID address = NULL;
717
718     if (block_size < size) return NULL;  /* overflow */
719     if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 5,
720                                  &block_size, MEM_COMMIT, get_protection_type( flags ) ))
721     {
722         WARN("Could not allocate block for %08lx bytes\n", size );
723         return NULL;
724     }
725     arena = address;
726     arena->data_size = size;
727     arena->block_size = block_size;
728     arena->size = ARENA_LARGE_SIZE;
729     arena->magic = ARENA_LARGE_MAGIC;
730     mark_block_tail( (char *)(arena + 1) + size, block_size - sizeof(*arena) - size, flags );
731     list_add_tail( &heap->large_list, &arena->entry );
732     notify_alloc( arena + 1, size, flags & HEAP_ZERO_MEMORY );
733     return arena + 1;
734 }
735
736
737 /***********************************************************************
738  *           free_large_block
739  */
740 static void free_large_block( HEAP *heap, DWORD flags, void *ptr )
741 {
742     ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
743     LPVOID address = arena;
744     SIZE_T size = 0;
745
746     list_remove( &arena->entry );
747     NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
748 }
749
750
751 /***********************************************************************
752  *           realloc_large_block
753  */
754 static void *realloc_large_block( HEAP *heap, DWORD flags, void *ptr, SIZE_T size )
755 {
756     ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
757     void *new_ptr;
758
759     if (arena->block_size - sizeof(*arena) >= size)
760     {
761         SIZE_T unused = arena->block_size - sizeof(*arena) - size;
762
763         /* FIXME: we could remap zero-pages instead */
764 #ifdef VALGRIND_RESIZEINPLACE_BLOCK
765         if (RUNNING_ON_VALGRIND)
766             notify_realloc( arena + 1, arena->data_size, size );
767         else
768 #endif
769         if (size > arena->data_size)
770             initialize_block( (char *)ptr + arena->data_size, size - arena->data_size, unused, flags );
771         else
772             mark_block_tail( (char *)ptr + size, unused, flags );
773         arena->data_size = size;
774         return ptr;
775     }
776     if (flags & HEAP_REALLOC_IN_PLACE_ONLY) return NULL;
777     if (!(new_ptr = allocate_large_block( heap, flags, size )))
778     {
779         WARN("Could not allocate block for %08lx bytes\n", size );
780         return NULL;
781     }
782     memcpy( new_ptr, ptr, arena->data_size );
783     free_large_block( heap, flags, ptr );
784     notify_free( ptr );
785     return new_ptr;
786 }
787
788
789 /***********************************************************************
790  *           find_large_block
791  */
792 static ARENA_LARGE *find_large_block( HEAP *heap, const void *ptr )
793 {
794     ARENA_LARGE *arena;
795
796     LIST_FOR_EACH_ENTRY( arena, &heap->large_list, ARENA_LARGE, entry )
797         if (ptr == arena + 1) return arena;
798
799     return NULL;
800 }
801
802
803 /***********************************************************************
804  *           validate_large_arena
805  */
806 static BOOL validate_large_arena( HEAP *heap, const ARENA_LARGE *arena, BOOL quiet )
807 {
808     DWORD flags = heap->flags;
809
810     if ((ULONG_PTR)arena % page_size)
811     {
812         if (quiet == NOISY)
813         {
814             ERR( "Heap %p: invalid large arena pointer %p\n", heap, arena );
815             if (TRACE_ON(heap)) HEAP_Dump( heap );
816         }
817         else if (WARN_ON(heap))
818         {
819             WARN( "Heap %p: unaligned arena pointer %p\n", heap, arena );
820             if (TRACE_ON(heap)) HEAP_Dump( heap );
821         }
822         return FALSE;
823     }
824     if (arena->size != ARENA_LARGE_SIZE || arena->magic != ARENA_LARGE_MAGIC)
825     {
826         if (quiet == NOISY)
827         {
828             ERR( "Heap %p: invalid large arena %p values %x/%x\n",
829                  heap, arena, arena->size, arena->magic );
830             if (TRACE_ON(heap)) HEAP_Dump( heap );
831         }
832         else if (WARN_ON(heap))
833         {
834             WARN( "Heap %p: invalid large arena %p values %x/%x\n",
835                   heap, arena, arena->size, arena->magic );
836             if (TRACE_ON(heap)) HEAP_Dump( heap );
837         }
838         return FALSE;
839     }
840     if (arena->data_size > arena->block_size - sizeof(*arena))
841     {
842         ERR( "Heap %p: invalid large arena %p size %lx/%lx\n",
843              heap, arena, arena->data_size, arena->block_size );
844         return FALSE;
845     }
846     if (flags & HEAP_TAIL_CHECKING_ENABLED)
847     {
848         SIZE_T i, unused = arena->block_size - sizeof(*arena) - arena->data_size;
849         const unsigned char *data = (const unsigned char *)(arena + 1) + arena->data_size;
850
851         for (i = 0; i < unused; i++)
852         {
853             if (data[i] == ARENA_TAIL_FILLER) continue;
854             ERR("Heap %p: block %p tail overwritten at %p (byte %lu/%lu == 0x%02x)\n",
855                 heap, arena + 1, data + i, i, unused, data[i] );
856             return FALSE;
857         }
858     }
859     return TRUE;
860 }
861
862
863 /***********************************************************************
864  *           HEAP_CreateSubHeap
865  */
866 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, LPVOID address, DWORD flags,
867                                     SIZE_T commitSize, SIZE_T totalSize )
868 {
869     SUBHEAP *subheap;
870     FREE_LIST_ENTRY *pEntry;
871     unsigned int i;
872
873     if (!address)
874     {
875         if (!commitSize) commitSize = COMMIT_MASK + 1;
876         totalSize = min( totalSize, 0xffff0000 );  /* don't allow a heap larger than 4Gb */
877         if (totalSize < commitSize) totalSize = commitSize;
878         if (flags & HEAP_SHARED) commitSize = totalSize;  /* always commit everything in a shared heap */
879         commitSize = min( totalSize, (commitSize + COMMIT_MASK) & ~COMMIT_MASK );
880
881         /* allocate the memory block */
882         if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 5, &totalSize,
883                                      MEM_RESERVE, get_protection_type( flags ) ))
884         {
885             WARN("Could not allocate %08lx bytes\n", totalSize );
886             return NULL;
887         }
888         if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
889                                      &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
890         {
891             WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
892             return NULL;
893         }
894     }
895
896     if (heap)
897     {
898         /* If this is a secondary subheap, insert it into list */
899
900         subheap = address;
901         subheap->base       = address;
902         subheap->heap       = heap;
903         subheap->size       = totalSize;
904         subheap->min_commit = 0x10000;
905         subheap->commitSize = commitSize;
906         subheap->magic      = SUBHEAP_MAGIC;
907         subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
908         list_add_head( &heap->subheap_list, &subheap->entry );
909     }
910     else
911     {
912         /* If this is a primary subheap, initialize main heap */
913
914         heap = address;
915         heap->flags         = flags;
916         heap->magic         = HEAP_MAGIC;
917         heap->grow_size     = max( HEAP_DEF_SIZE, totalSize );
918         list_init( &heap->subheap_list );
919         list_init( &heap->large_list );
920
921         subheap = &heap->subheap;
922         subheap->base       = address;
923         subheap->heap       = heap;
924         subheap->size       = totalSize;
925         subheap->min_commit = commitSize;
926         subheap->commitSize = commitSize;
927         subheap->magic      = SUBHEAP_MAGIC;
928         subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
929         list_add_head( &heap->subheap_list, &subheap->entry );
930
931         /* Build the free lists */
932
933         heap->freeList = (FREE_LIST_ENTRY *)((char *)heap + subheap->headerSize);
934         subheap->headerSize += HEAP_NB_FREE_LISTS * sizeof(FREE_LIST_ENTRY);
935         list_init( &heap->freeList[0].arena.entry );
936         for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
937         {
938             pEntry->arena.size = 0 | ARENA_FLAG_FREE;
939             pEntry->arena.magic = ARENA_FREE_MAGIC;
940             if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
941         }
942
943         /* Initialize critical section */
944
945         if (!processHeap)  /* do it by hand to avoid memory allocations */
946         {
947             heap->critSection.DebugInfo      = &process_heap_critsect_debug;
948             heap->critSection.LockCount      = -1;
949             heap->critSection.RecursionCount = 0;
950             heap->critSection.OwningThread   = 0;
951             heap->critSection.LockSemaphore  = 0;
952             heap->critSection.SpinCount      = 0;
953             process_heap_critsect_debug.CriticalSection = &heap->critSection;
954         }
955         else
956         {
957             RtlInitializeCriticalSection( &heap->critSection );
958             heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
959         }
960
961         if (flags & HEAP_SHARED)
962         {
963             /* let's assume that only one thread at a time will try to do this */
964             HANDLE sem = heap->critSection.LockSemaphore;
965             if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
966
967             NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
968                                DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
969             heap->critSection.LockSemaphore = sem;
970             RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
971             heap->critSection.DebugInfo = NULL;
972         }
973     }
974
975     /* Create the first free block */
976
977     HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
978                           subheap->size - subheap->headerSize );
979
980     return subheap;
981 }
982
983
984 /***********************************************************************
985  *           HEAP_FindFreeBlock
986  *
987  * Find a free block at least as large as the requested size, and make sure
988  * the requested size is committed.
989  */
990 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
991                                        SUBHEAP **ppSubHeap )
992 {
993     SUBHEAP *subheap;
994     struct list *ptr;
995     SIZE_T total_size;
996     FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
997
998     /* Find a suitable free list, and in it find a block large enough */
999
1000     ptr = &pEntry->arena.entry;
1001     while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
1002     {
1003         ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
1004         SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
1005                             sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1006         if (arena_size >= size)
1007         {
1008             subheap = HEAP_FindSubHeap( heap, pArena );
1009             if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
1010             *ppSubHeap = subheap;
1011             return pArena;
1012         }
1013     }
1014
1015     /* If no block was found, attempt to grow the heap */
1016
1017     if (!(heap->flags & HEAP_GROWABLE))
1018     {
1019         WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
1020         return NULL;
1021     }
1022     /* make sure that we have a big enough size *committed* to fit another
1023      * last free arena in !
1024      * So just one heap struct, one first free arena which will eventually
1025      * get used, and a second free arena that might get assigned all remaining
1026      * free space in HEAP_ShrinkBlock() */
1027     total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
1028     if (total_size < size) return NULL;  /* overflow */
1029
1030     if ((subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
1031                                        max( heap->grow_size, total_size ) )))
1032     {
1033         if (heap->grow_size < 128 * 1024 * 1024) heap->grow_size *= 2;
1034     }
1035     else while (!subheap)  /* shrink the grow size again if we are running out of space */
1036     {
1037         if (heap->grow_size <= total_size || heap->grow_size <= 4 * 1024 * 1024) return NULL;
1038         heap->grow_size /= 2;
1039         subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
1040                                       max( heap->grow_size, total_size ) );
1041     }
1042
1043     TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
1044           subheap, subheap->size, heap );
1045
1046     *ppSubHeap = subheap;
1047     return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
1048 }
1049
1050
1051 /***********************************************************************
1052  *           HEAP_IsValidArenaPtr
1053  *
1054  * Check that the pointer is inside the range possible for arenas.
1055  */
1056 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
1057 {
1058     unsigned int i;
1059     const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
1060     if (!subheap) return FALSE;
1061     if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
1062     if (subheap != &heap->subheap) return FALSE;
1063     for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
1064         if (ptr == &heap->freeList[i].arena) return TRUE;
1065     return FALSE;
1066 }
1067
1068
1069 /***********************************************************************
1070  *           HEAP_ValidateFreeArena
1071  */
1072 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
1073 {
1074     DWORD flags = subheap->heap->flags;
1075     SIZE_T size;
1076     ARENA_FREE *prev, *next;
1077     char *heapEnd = (char *)subheap->base + subheap->size;
1078
1079     /* Check for unaligned pointers */
1080     if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1081     {
1082         ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1083         return FALSE;
1084     }
1085
1086     /* Check magic number */
1087     if (pArena->magic != ARENA_FREE_MAGIC)
1088     {
1089         ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1090         return FALSE;
1091     }
1092     /* Check size flags */
1093     if (!(pArena->size & ARENA_FLAG_FREE) ||
1094         (pArena->size & ARENA_FLAG_PREV_FREE))
1095     {
1096         ERR("Heap %p: bad flags %08x for free arena %p\n",
1097             subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1098         return FALSE;
1099     }
1100     /* Check arena size */
1101     size = pArena->size & ARENA_SIZE_MASK;
1102     if ((char *)(pArena + 1) + size > heapEnd)
1103     {
1104         ERR("Heap %p: bad size %08lx for free arena %p\n", subheap->heap, size, pArena );
1105         return FALSE;
1106     }
1107     /* Check that next pointer is valid */
1108     next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
1109     if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
1110     {
1111         ERR("Heap %p: bad next ptr %p for arena %p\n",
1112             subheap->heap, next, pArena );
1113         return FALSE;
1114     }
1115     /* Check that next arena is free */
1116     if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1117     {
1118         ERR("Heap %p: next arena %p invalid for %p\n",
1119             subheap->heap, next, pArena );
1120         return FALSE;
1121     }
1122     /* Check that prev pointer is valid */
1123     prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1124     if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1125     {
1126         ERR("Heap %p: bad prev ptr %p for arena %p\n",
1127             subheap->heap, prev, pArena );
1128         return FALSE;
1129     }
1130     /* Check that prev arena is free */
1131     if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1132     {
1133         /* this often means that the prev arena got overwritten
1134          * by a memory write before that prev arena */
1135         ERR("Heap %p: prev arena %p invalid for %p\n",
1136             subheap->heap, prev, pArena );
1137         return FALSE;
1138     }
1139     /* Check that next block has PREV_FREE flag */
1140     if ((char *)(pArena + 1) + size < heapEnd)
1141     {
1142         if (!(*(DWORD *)((char *)(pArena + 1) + size) & ARENA_FLAG_PREV_FREE))
1143         {
1144             ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1145                 subheap->heap, pArena );
1146             return FALSE;
1147         }
1148         /* Check next block back pointer */
1149         if (*((ARENA_FREE **)((char *)(pArena + 1) + size) - 1) != pArena)
1150         {
1151             ERR("Heap %p: arena %p has wrong back ptr %p\n",
1152                 subheap->heap, pArena,
1153                 *((ARENA_FREE **)((char *)(pArena+1) + size) - 1));
1154             return FALSE;
1155         }
1156     }
1157     if (flags & HEAP_FREE_CHECKING_ENABLED)
1158     {
1159         DWORD *ptr = (DWORD *)(pArena + 1);
1160         char *end = (char *)(pArena + 1) + size;
1161
1162         if (end >= heapEnd) end = (char *)subheap->base + subheap->commitSize;
1163         else end -= sizeof(ARENA_FREE *);
1164         while (ptr < (DWORD *)end)
1165         {
1166             if (*ptr != ARENA_FREE_FILLER)
1167             {
1168                 ERR("Heap %p: free block %p overwritten at %p by %08x\n",
1169                     subheap->heap, (ARENA_INUSE *)pArena + 1, ptr, *ptr );
1170                 return FALSE;
1171             }
1172             ptr++;
1173         }
1174     }
1175     return TRUE;
1176 }
1177
1178
1179 /***********************************************************************
1180  *           HEAP_ValidateInUseArena
1181  */
1182 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1183 {
1184     SIZE_T size;
1185     DWORD i, flags = subheap->heap->flags;
1186     const char *heapEnd = (const char *)subheap->base + subheap->size;
1187
1188     /* Check for unaligned pointers */
1189     if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1190     {
1191         if ( quiet == NOISY )
1192         {
1193             ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1194             if ( TRACE_ON(heap) )
1195                 HEAP_Dump( subheap->heap );
1196         }
1197         else if ( WARN_ON(heap) )
1198         {
1199             WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1200             if ( TRACE_ON(heap) )
1201                 HEAP_Dump( subheap->heap );
1202         }
1203         return FALSE;
1204     }
1205
1206     /* Check magic number */
1207     if (pArena->magic != ARENA_INUSE_MAGIC && pArena->magic != ARENA_PENDING_MAGIC)
1208     {
1209         if (quiet == NOISY) {
1210             ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1211             if (TRACE_ON(heap))
1212                HEAP_Dump( subheap->heap );
1213         }  else if (WARN_ON(heap)) {
1214             WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1215             if (TRACE_ON(heap))
1216                HEAP_Dump( subheap->heap );
1217         }
1218         return FALSE;
1219     }
1220     /* Check size flags */
1221     if (pArena->size & ARENA_FLAG_FREE)
1222     {
1223         ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1224             subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1225         return FALSE;
1226     }
1227     /* Check arena size */
1228     size = pArena->size & ARENA_SIZE_MASK;
1229     if ((const char *)(pArena + 1) + size > heapEnd ||
1230         (const char *)(pArena + 1) + size < (const char *)(pArena + 1))
1231     {
1232         ERR("Heap %p: bad size %08lx for in-use arena %p\n", subheap->heap, size, pArena );
1233         return FALSE;
1234     }
1235     /* Check next arena PREV_FREE flag */
1236     if (((const char *)(pArena + 1) + size < heapEnd) &&
1237         (*(const DWORD *)((const char *)(pArena + 1) + size) & ARENA_FLAG_PREV_FREE))
1238     {
1239         ERR("Heap %p: in-use arena %p next block %p has PREV_FREE flag %x\n",
1240             subheap->heap, pArena, (const char *)(pArena + 1) + size,*(const DWORD *)((const char *)(pArena + 1) + size) );
1241         return FALSE;
1242     }
1243     /* Check prev free arena */
1244     if (pArena->size & ARENA_FLAG_PREV_FREE)
1245     {
1246         const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1247         /* Check prev pointer */
1248         if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1249         {
1250             ERR("Heap %p: bad back ptr %p for arena %p\n",
1251                 subheap->heap, pPrev, pArena );
1252             return FALSE;
1253         }
1254         /* Check that prev arena is free */
1255         if (!(pPrev->size & ARENA_FLAG_FREE) ||
1256             (pPrev->magic != ARENA_FREE_MAGIC))
1257         {
1258             ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1259                 subheap->heap, pPrev, pArena );
1260             return FALSE;
1261         }
1262         /* Check that prev arena is really the previous block */
1263         if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1264         {
1265             ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1266                 subheap->heap, pPrev, pArena );
1267             return FALSE;
1268         }
1269     }
1270     /* Check unused size */
1271     if (pArena->unused_bytes > size)
1272     {
1273         ERR("Heap %p: invalid unused size %08x/%08lx\n", subheap->heap, pArena->unused_bytes, size );
1274         return FALSE;
1275     }
1276     /* Check unused bytes */
1277     if (pArena->magic == ARENA_PENDING_MAGIC)
1278     {
1279         const DWORD *ptr = (const DWORD *)(pArena + 1);
1280         const DWORD *end = (const DWORD *)((const char *)ptr + size);
1281
1282         while (ptr < end)
1283         {
1284             if (*ptr != ARENA_FREE_FILLER)
1285             {
1286                 ERR("Heap %p: free block %p overwritten at %p by %08x\n",
1287                     subheap->heap, (const ARENA_INUSE *)pArena + 1, ptr, *ptr );
1288                 if (!*ptr) { HEAP_Dump( subheap->heap ); DbgBreakPoint(); }
1289                 return FALSE;
1290             }
1291             ptr++;
1292         }
1293     }
1294     else if (flags & HEAP_TAIL_CHECKING_ENABLED)
1295     {
1296         const unsigned char *data = (const unsigned char *)(pArena + 1) + size - pArena->unused_bytes;
1297
1298         for (i = 0; i < pArena->unused_bytes; i++)
1299         {
1300             if (data[i] == ARENA_TAIL_FILLER) continue;
1301             ERR("Heap %p: block %p tail overwritten at %p (byte %u/%u == 0x%02x)\n",
1302                 subheap->heap, pArena + 1, data + i, i, pArena->unused_bytes, data[i] );
1303             return FALSE;
1304         }
1305     }
1306     return TRUE;
1307 }
1308
1309
1310 /***********************************************************************
1311  *           HEAP_IsRealArena  [Internal]
1312  * Validates a block is a valid arena.
1313  *
1314  * RETURNS
1315  *      TRUE: Success
1316  *      FALSE: Failure
1317  */
1318 static BOOL HEAP_IsRealArena( HEAP *heapPtr,   /* [in] ptr to the heap */
1319               DWORD flags,   /* [in] Bit flags that control access during operation */
1320               LPCVOID block, /* [in] Optional pointer to memory block to validate */
1321               BOOL quiet )   /* [in] Flag - if true, HEAP_ValidateInUseArena
1322                               *             does not complain    */
1323 {
1324     SUBHEAP *subheap;
1325     BOOL ret = TRUE;
1326     const ARENA_LARGE *large_arena;
1327
1328     flags &= HEAP_NO_SERIALIZE;
1329     flags |= heapPtr->flags;
1330     /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1331     if (!(flags & HEAP_NO_SERIALIZE))
1332         RtlEnterCriticalSection( &heapPtr->critSection );
1333
1334     if (block)  /* only check this single memory block */
1335     {
1336         const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1337
1338         if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1339             ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1340         {
1341             if (!(large_arena = find_large_block( heapPtr, block )))
1342             {
1343                 if (quiet == NOISY)
1344                     ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1345                 else if (WARN_ON(heap))
1346                     WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1347                 ret = FALSE;
1348             }
1349             else
1350                 ret = validate_large_arena( heapPtr, large_arena, quiet );
1351         } else
1352             ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1353
1354         if (!(flags & HEAP_NO_SERIALIZE))
1355             RtlLeaveCriticalSection( &heapPtr->critSection );
1356         return ret;
1357     }
1358
1359     LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1360     {
1361         char *ptr = (char *)subheap->base + subheap->headerSize;
1362         while (ptr < (char *)subheap->base + subheap->size)
1363         {
1364             if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1365             {
1366                 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1367                     ret = FALSE;
1368                     break;
1369                 }
1370                 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1371             }
1372             else
1373             {
1374                 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1375                     ret = FALSE;
1376                     break;
1377                 }
1378                 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1379             }
1380         }
1381         if (!ret) break;
1382     }
1383
1384     LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1385         if (!(ret = validate_large_arena( heapPtr, large_arena, quiet ))) break;
1386
1387     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1388     return ret;
1389 }
1390
1391
1392 /***********************************************************************
1393  *           validate_block_pointer
1394  *
1395  * Minimum validation needed to catch bad parameters in heap functions.
1396  */
1397 static BOOL validate_block_pointer( HEAP *heap, SUBHEAP **ret_subheap, const ARENA_INUSE *arena )
1398 {
1399     SUBHEAP *subheap;
1400     BOOL ret = FALSE;
1401
1402     if (!(*ret_subheap = subheap = HEAP_FindSubHeap( heap, arena )))
1403     {
1404         ARENA_LARGE *large_arena = find_large_block( heap, arena + 1 );
1405
1406         if (!large_arena)
1407         {
1408             WARN( "Heap %p: pointer %p is not inside heap\n", heap, arena + 1 );
1409             return FALSE;
1410         }
1411         if ((heap->flags & HEAP_VALIDATE) && !validate_large_arena( heap, large_arena, QUIET ))
1412             return FALSE;
1413         return TRUE;
1414     }
1415
1416     if ((const char *)arena < (char *)subheap->base + subheap->headerSize)
1417         WARN( "Heap %p: pointer %p is inside subheap %p header\n", subheap->heap, arena + 1, subheap );
1418     else if (subheap->heap->flags & HEAP_VALIDATE)  /* do the full validation */
1419         ret = HEAP_ValidateInUseArena( subheap, arena, QUIET );
1420     else if ((ULONG_PTR)arena % ALIGNMENT != ARENA_OFFSET)
1421         WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, arena );
1422     else if (arena->magic == ARENA_PENDING_MAGIC)
1423         WARN( "Heap %p: block %p used after free\n", subheap->heap, arena + 1 );
1424     else if (arena->magic != ARENA_INUSE_MAGIC)
1425         WARN( "Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, arena->magic, arena );
1426     else if (arena->size & ARENA_FLAG_FREE)
1427         ERR( "Heap %p: bad flags %08x for in-use arena %p\n",
1428              subheap->heap, arena->size & ~ARENA_SIZE_MASK, arena );
1429     else if ((const char *)(arena + 1) + (arena->size & ARENA_SIZE_MASK) > (const char *)subheap->base + subheap->size ||
1430              (const char *)(arena + 1) + (arena->size & ARENA_SIZE_MASK) < (const char *)(arena + 1))
1431         ERR( "Heap %p: bad size %08x for in-use arena %p\n",
1432              subheap->heap, arena->size & ARENA_SIZE_MASK, arena );
1433     else
1434         ret = TRUE;
1435
1436     return ret;
1437 }
1438
1439
1440 /***********************************************************************
1441  *           heap_set_debug_flags
1442  */
1443 void heap_set_debug_flags( HANDLE handle )
1444 {
1445     HEAP *heap = HEAP_GetPtr( handle );
1446     ULONG global_flags = RtlGetNtGlobalFlags();
1447     ULONG flags = 0;
1448
1449     if (TRACE_ON(heap)) global_flags |= FLG_HEAP_VALIDATE_ALL;
1450     if (WARN_ON(heap)) global_flags |= FLG_HEAP_VALIDATE_PARAMETERS;
1451
1452     if (global_flags & FLG_HEAP_ENABLE_TAIL_CHECK) flags |= HEAP_TAIL_CHECKING_ENABLED;
1453     if (global_flags & FLG_HEAP_ENABLE_FREE_CHECK) flags |= HEAP_FREE_CHECKING_ENABLED;
1454     if (global_flags & FLG_HEAP_DISABLE_COALESCING) flags |= HEAP_DISABLE_COALESCE_ON_FREE;
1455     if (global_flags & FLG_HEAP_PAGE_ALLOCS) flags |= HEAP_PAGE_ALLOCS | HEAP_GROWABLE;
1456
1457     if (global_flags & FLG_HEAP_VALIDATE_PARAMETERS)
1458         flags |= HEAP_VALIDATE | HEAP_VALIDATE_PARAMS |
1459                  HEAP_TAIL_CHECKING_ENABLED | HEAP_FREE_CHECKING_ENABLED;
1460     if (global_flags & FLG_HEAP_VALIDATE_ALL)
1461         flags |= HEAP_VALIDATE | HEAP_VALIDATE_ALL |
1462                  HEAP_TAIL_CHECKING_ENABLED | HEAP_FREE_CHECKING_ENABLED;
1463
1464     if (RUNNING_ON_VALGRIND) flags = 0; /* no sense in validating since Valgrind catches accesses */
1465
1466     heap->flags |= flags;
1467     heap->force_flags |= flags & ~(HEAP_VALIDATE | HEAP_DISABLE_COALESCE_ON_FREE);
1468
1469     if (flags & (HEAP_FREE_CHECKING_ENABLED | HEAP_TAIL_CHECKING_ENABLED))  /* fix existing blocks */
1470     {
1471         SUBHEAP *subheap;
1472         ARENA_LARGE *large;
1473
1474         LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
1475         {
1476             char *ptr = (char *)subheap->base + subheap->headerSize;
1477             char *end = (char *)subheap->base + subheap->commitSize;
1478             while (ptr < end)
1479             {
1480                 ARENA_INUSE *arena = (ARENA_INUSE *)ptr;
1481                 SIZE_T size = arena->size & ARENA_SIZE_MASK;
1482                 if (arena->size & ARENA_FLAG_FREE)
1483                 {
1484                     SIZE_T count = size;
1485
1486                     ptr += sizeof(ARENA_FREE) + size;
1487                     if (ptr >= end) count = end - (char *)((ARENA_FREE *)arena + 1);
1488                     else count -= sizeof(ARENA_FREE *);
1489                     mark_block_free( (ARENA_FREE *)arena + 1, count, flags );
1490                 }
1491                 else
1492                 {
1493                     if (arena->magic == ARENA_PENDING_MAGIC)
1494                         mark_block_free( arena + 1, size, flags );
1495                     else
1496                         mark_block_tail( (char *)(arena + 1) + size - arena->unused_bytes,
1497                                          arena->unused_bytes, flags );
1498                     ptr += sizeof(ARENA_INUSE) + size;
1499                 }
1500             }
1501         }
1502
1503         LIST_FOR_EACH_ENTRY( large, &heap->large_list, ARENA_LARGE, entry )
1504             mark_block_tail( (char *)(large + 1) + large->data_size,
1505                              large->block_size - sizeof(*large) - large->data_size, flags );
1506     }
1507
1508     if ((heap->flags & HEAP_GROWABLE) && !heap->pending_free &&
1509         ((flags & HEAP_FREE_CHECKING_ENABLED) || RUNNING_ON_VALGRIND))
1510     {
1511         void *ptr = NULL;
1512         SIZE_T size = MAX_FREE_PENDING * sizeof(*heap->pending_free);
1513
1514         if (!NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 4, &size, MEM_COMMIT, PAGE_READWRITE ))
1515         {
1516             heap->pending_free = ptr;
1517             heap->pending_pos = 0;
1518         }
1519     }
1520 }
1521
1522
1523 /***********************************************************************
1524  *           RtlCreateHeap   (NTDLL.@)
1525  *
1526  * Create a new Heap.
1527  *
1528  * PARAMS
1529  *  flags      [I] HEAP_ flags from "winnt.h"
1530  *  addr       [I] Desired base address
1531  *  totalSize  [I] Total size of the heap, or 0 for a growable heap
1532  *  commitSize [I] Amount of heap space to commit
1533  *  unknown    [I] Not yet understood
1534  *  definition [I] Heap definition
1535  *
1536  * RETURNS
1537  *  Success: A HANDLE to the newly created heap.
1538  *  Failure: a NULL HANDLE.
1539  */
1540 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1541                              PVOID unknown, PRTL_HEAP_DEFINITION definition )
1542 {
1543     SUBHEAP *subheap;
1544
1545     /* Allocate the heap block */
1546
1547     if (!totalSize)
1548     {
1549         totalSize = HEAP_DEF_SIZE;
1550         flags |= HEAP_GROWABLE;
1551     }
1552
1553     if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1554
1555     heap_set_debug_flags( subheap->heap );
1556
1557     /* link it into the per-process heap list */
1558     if (processHeap)
1559     {
1560         HEAP *heapPtr = subheap->heap;
1561         RtlEnterCriticalSection( &processHeap->critSection );
1562         list_add_head( &processHeap->entry, &heapPtr->entry );
1563         RtlLeaveCriticalSection( &processHeap->critSection );
1564     }
1565     else if (!addr)
1566     {
1567         processHeap = subheap->heap;  /* assume the first heap we create is the process main heap */
1568         list_init( &processHeap->entry );
1569     }
1570
1571     return subheap->heap;
1572 }
1573
1574
1575 /***********************************************************************
1576  *           RtlDestroyHeap   (NTDLL.@)
1577  *
1578  * Destroy a Heap created with RtlCreateHeap().
1579  *
1580  * PARAMS
1581  *  heap [I] Heap to destroy.
1582  *
1583  * RETURNS
1584  *  Success: A NULL HANDLE, if heap is NULL or it was destroyed
1585  *  Failure: The Heap handle, if heap is the process heap.
1586  */
1587 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1588 {
1589     HEAP *heapPtr = HEAP_GetPtr( heap );
1590     SUBHEAP *subheap, *next;
1591     ARENA_LARGE *arena, *arena_next;
1592     SIZE_T size;
1593     void *addr;
1594
1595     TRACE("%p\n", heap );
1596     if (!heapPtr) return heap;
1597
1598     if (heap == processHeap) return heap; /* cannot delete the main process heap */
1599
1600     /* remove it from the per-process list */
1601     RtlEnterCriticalSection( &processHeap->critSection );
1602     list_remove( &heapPtr->entry );
1603     RtlLeaveCriticalSection( &processHeap->critSection );
1604
1605     heapPtr->critSection.DebugInfo->Spare[0] = 0;
1606     RtlDeleteCriticalSection( &heapPtr->critSection );
1607
1608     LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1609     {
1610         list_remove( &arena->entry );
1611         size = 0;
1612         addr = arena;
1613         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1614     }
1615     LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1616     {
1617         if (subheap == &heapPtr->subheap) continue;  /* do this one last */
1618         subheap_notify_free_all(subheap);
1619         list_remove( &subheap->entry );
1620         size = 0;
1621         addr = subheap->base;
1622         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1623     }
1624     subheap_notify_free_all(&heapPtr->subheap);
1625     if (heapPtr->pending_free)
1626     {
1627         size = 0;
1628         addr = heapPtr->pending_free;
1629         NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1630     }
1631     size = 0;
1632     addr = heapPtr->subheap.base;
1633     NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1634     return 0;
1635 }
1636
1637
1638 /***********************************************************************
1639  *           RtlAllocateHeap   (NTDLL.@)
1640  *
1641  * Allocate a memory block from a Heap.
1642  *
1643  * PARAMS
1644  *  heap  [I] Heap to allocate block from
1645  *  flags [I] HEAP_ flags from "winnt.h"
1646  *  size  [I] Size of the memory block to allocate
1647  *
1648  * RETURNS
1649  *  Success: A pointer to the newly allocated block
1650  *  Failure: NULL.
1651  *
1652  * NOTES
1653  *  This call does not SetLastError().
1654  */
1655 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1656 {
1657     ARENA_FREE *pArena;
1658     ARENA_INUSE *pInUse;
1659     SUBHEAP *subheap;
1660     HEAP *heapPtr = HEAP_GetPtr( heap );
1661     SIZE_T rounded_size;
1662
1663     /* Validate the parameters */
1664
1665     if (!heapPtr) return NULL;
1666     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1667     flags |= heapPtr->flags;
1668     rounded_size = ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE( flags );
1669     if (rounded_size < size)  /* overflow */
1670     {
1671         if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1672         return NULL;
1673     }
1674     if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1675
1676     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1677
1678     if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1679     {
1680         void *ret = allocate_large_block( heap, flags, size );
1681         if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1682         if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1683         TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1684         return ret;
1685     }
1686
1687     /* Locate a suitable free block */
1688
1689     if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1690     {
1691         TRACE("(%p,%08x,%08lx): returning NULL\n",
1692                   heap, flags, size  );
1693         if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1694         if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1695         return NULL;
1696     }
1697
1698     /* Remove the arena from the free list */
1699
1700     list_remove( &pArena->entry );
1701
1702     /* Build the in-use arena */
1703
1704     pInUse = (ARENA_INUSE *)pArena;
1705
1706     /* in-use arena is smaller than free arena,
1707      * so we have to add the difference to the size */
1708     pInUse->size  = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1709     pInUse->magic = ARENA_INUSE_MAGIC;
1710
1711     /* Shrink the block */
1712
1713     HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1714     pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1715
1716     notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1717     initialize_block( pInUse + 1, size, pInUse->unused_bytes, flags );
1718
1719     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1720
1721     TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1722     return pInUse + 1;
1723 }
1724
1725
1726 /***********************************************************************
1727  *           RtlFreeHeap   (NTDLL.@)
1728  *
1729  * Free a memory block allocated with RtlAllocateHeap().
1730  *
1731  * PARAMS
1732  *  heap  [I] Heap that block was allocated from
1733  *  flags [I] HEAP_ flags from "winnt.h"
1734  *  ptr   [I] Block to free
1735  *
1736  * RETURNS
1737  *  Success: TRUE, if ptr is NULL or was freed successfully.
1738  *  Failure: FALSE.
1739  */
1740 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1741 {
1742     ARENA_INUSE *pInUse;
1743     SUBHEAP *subheap;
1744     HEAP *heapPtr;
1745
1746     /* Validate the parameters */
1747
1748     if (!ptr) return TRUE;  /* freeing a NULL ptr isn't an error in Win2k */
1749
1750     heapPtr = HEAP_GetPtr( heap );
1751     if (!heapPtr)
1752     {
1753         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1754         return FALSE;
1755     }
1756
1757     flags &= HEAP_NO_SERIALIZE;
1758     flags |= heapPtr->flags;
1759     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1760
1761     /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1762     notify_free( ptr );
1763
1764     /* Some sanity checks */
1765     pInUse  = (ARENA_INUSE *)ptr - 1;
1766     if (!validate_block_pointer( heapPtr, &subheap, pInUse )) goto error;
1767
1768     if (!subheap)
1769         free_large_block( heapPtr, flags, ptr );
1770     else
1771         HEAP_MakeInUseBlockFree( subheap, pInUse );
1772
1773     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1774     TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1775     return TRUE;
1776
1777 error:
1778     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1779     RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1780     TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1781     return FALSE;
1782 }
1783
1784
1785 /***********************************************************************
1786  *           RtlReAllocateHeap   (NTDLL.@)
1787  *
1788  * Change the size of a memory block allocated with RtlAllocateHeap().
1789  *
1790  * PARAMS
1791  *  heap  [I] Heap that block was allocated from
1792  *  flags [I] HEAP_ flags from "winnt.h"
1793  *  ptr   [I] Block to resize
1794  *  size  [I] Size of the memory block to allocate
1795  *
1796  * RETURNS
1797  *  Success: A pointer to the resized block (which may be different).
1798  *  Failure: NULL.
1799  */
1800 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1801 {
1802     ARENA_INUSE *pArena;
1803     HEAP *heapPtr;
1804     SUBHEAP *subheap;
1805     SIZE_T oldBlockSize, oldActualSize, rounded_size;
1806     void *ret;
1807
1808     if (!ptr) return NULL;
1809     if (!(heapPtr = HEAP_GetPtr( heap )))
1810     {
1811         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1812         return NULL;
1813     }
1814
1815     /* Validate the parameters */
1816
1817     flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1818              HEAP_REALLOC_IN_PLACE_ONLY;
1819     flags |= heapPtr->flags;
1820     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1821
1822     rounded_size = ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE(flags);
1823     if (rounded_size < size) goto oom;  /* overflow */
1824     if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1825
1826     pArena = (ARENA_INUSE *)ptr - 1;
1827     if (!validate_block_pointer( heapPtr, &subheap, pArena )) goto error;
1828     if (!subheap)
1829     {
1830         if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1831         goto done;
1832     }
1833
1834     /* Check if we need to grow the block */
1835
1836     oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1837     oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1838     if (rounded_size > oldBlockSize)
1839     {
1840         char *pNext = (char *)(pArena + 1) + oldBlockSize;
1841
1842         if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1843         {
1844             if (flags & HEAP_REALLOC_IN_PLACE_ONLY) goto oom;
1845             if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1846             memcpy( ret, pArena + 1, oldActualSize );
1847             notify_free( pArena + 1 );
1848             HEAP_MakeInUseBlockFree( subheap, pArena );
1849             goto done;
1850         }
1851         if ((pNext < (char *)subheap->base + subheap->size) &&
1852             (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1853             (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1854         {
1855             /* The next block is free and large enough */
1856             ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1857             list_remove( &pFree->entry );
1858             pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1859             if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1860             notify_realloc( pArena + 1, oldActualSize, size );
1861             HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1862         }
1863         else  /* Do it the hard way */
1864         {
1865             ARENA_FREE *pNew;
1866             ARENA_INUSE *pInUse;
1867             SUBHEAP *newsubheap;
1868
1869             if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1870                 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1871                 goto oom;
1872
1873             /* Build the in-use arena */
1874
1875             list_remove( &pNew->entry );
1876             pInUse = (ARENA_INUSE *)pNew;
1877             pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1878                            + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1879             pInUse->magic = ARENA_INUSE_MAGIC;
1880             HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1881
1882             mark_block_initialized( pInUse + 1, oldActualSize );
1883             notify_alloc( pInUse + 1, size, FALSE );
1884             memcpy( pInUse + 1, pArena + 1, oldActualSize );
1885
1886             /* Free the previous block */
1887
1888             notify_free( pArena + 1 );
1889             HEAP_MakeInUseBlockFree( subheap, pArena );
1890             subheap = newsubheap;
1891             pArena  = pInUse;
1892         }
1893     }
1894     else
1895     {
1896         notify_realloc( pArena + 1, oldActualSize, size );
1897         HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1898     }
1899
1900     pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1901
1902     /* Clear the extra bytes if needed */
1903
1904     if (size > oldActualSize)
1905         initialize_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize,
1906                           pArena->unused_bytes, flags );
1907     else
1908         mark_block_tail( (char *)(pArena + 1) + size, pArena->unused_bytes, flags );
1909
1910     /* Return the new arena */
1911
1912     ret = pArena + 1;
1913 done:
1914     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1915     TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1916     return ret;
1917
1918 oom:
1919     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1920     if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1921     RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1922     TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1923     return NULL;
1924
1925 error:
1926     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1927     RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1928     TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1929     return NULL;
1930 }
1931
1932
1933 /***********************************************************************
1934  *           RtlCompactHeap   (NTDLL.@)
1935  *
1936  * Compact the free space in a Heap.
1937  *
1938  * PARAMS
1939  *  heap  [I] Heap that block was allocated from
1940  *  flags [I] HEAP_ flags from "winnt.h"
1941  *
1942  * RETURNS
1943  *  The number of bytes compacted.
1944  *
1945  * NOTES
1946  *  This function is a harmless stub.
1947  */
1948 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1949 {
1950     static BOOL reported;
1951     if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1952     return 0;
1953 }
1954
1955
1956 /***********************************************************************
1957  *           RtlLockHeap   (NTDLL.@)
1958  *
1959  * Lock a Heap.
1960  *
1961  * PARAMS
1962  *  heap  [I] Heap to lock
1963  *
1964  * RETURNS
1965  *  Success: TRUE. The Heap is locked.
1966  *  Failure: FALSE, if heap is invalid.
1967  */
1968 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1969 {
1970     HEAP *heapPtr = HEAP_GetPtr( heap );
1971     if (!heapPtr) return FALSE;
1972     RtlEnterCriticalSection( &heapPtr->critSection );
1973     return TRUE;
1974 }
1975
1976
1977 /***********************************************************************
1978  *           RtlUnlockHeap   (NTDLL.@)
1979  *
1980  * Unlock a Heap.
1981  *
1982  * PARAMS
1983  *  heap  [I] Heap to unlock
1984  *
1985  * RETURNS
1986  *  Success: TRUE. The Heap is unlocked.
1987  *  Failure: FALSE, if heap is invalid.
1988  */
1989 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1990 {
1991     HEAP *heapPtr = HEAP_GetPtr( heap );
1992     if (!heapPtr) return FALSE;
1993     RtlLeaveCriticalSection( &heapPtr->critSection );
1994     return TRUE;
1995 }
1996
1997
1998 /***********************************************************************
1999  *           RtlSizeHeap   (NTDLL.@)
2000  *
2001  * Get the actual size of a memory block allocated from a Heap.
2002  *
2003  * PARAMS
2004  *  heap  [I] Heap that block was allocated from
2005  *  flags [I] HEAP_ flags from "winnt.h"
2006  *  ptr   [I] Block to get the size of
2007  *
2008  * RETURNS
2009  *  Success: The size of the block.
2010  *  Failure: -1, heap or ptr are invalid.
2011  *
2012  * NOTES
2013  *  The size may be bigger than what was passed to RtlAllocateHeap().
2014  */
2015 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
2016 {
2017     SIZE_T ret;
2018     const ARENA_INUSE *pArena;
2019     SUBHEAP *subheap;
2020     HEAP *heapPtr = HEAP_GetPtr( heap );
2021
2022     if (!heapPtr)
2023     {
2024         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
2025         return ~0UL;
2026     }
2027     flags &= HEAP_NO_SERIALIZE;
2028     flags |= heapPtr->flags;
2029     if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
2030
2031     pArena = (const ARENA_INUSE *)ptr - 1;
2032     if (!validate_block_pointer( heapPtr, &subheap, pArena ))
2033     {
2034         RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
2035         ret = ~0UL;
2036     }
2037     else if (!subheap)
2038     {
2039         const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
2040         ret = large_arena->data_size;
2041     }
2042     else
2043     {
2044         ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
2045     }
2046     if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
2047
2048     TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
2049     return ret;
2050 }
2051
2052
2053 /***********************************************************************
2054  *           RtlValidateHeap   (NTDLL.@)
2055  *
2056  * Determine if a block is a valid allocation from a heap.
2057  *
2058  * PARAMS
2059  *  heap  [I] Heap that block was allocated from
2060  *  flags [I] HEAP_ flags from "winnt.h"
2061  *  ptr   [I] Block to check
2062  *
2063  * RETURNS
2064  *  Success: TRUE. The block was allocated from heap.
2065  *  Failure: FALSE, if heap is invalid or ptr was not allocated from it.
2066  */
2067 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
2068 {
2069     HEAP *heapPtr = HEAP_GetPtr( heap );
2070     if (!heapPtr) return FALSE;
2071     return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
2072 }
2073
2074
2075 /***********************************************************************
2076  *           RtlWalkHeap    (NTDLL.@)
2077  *
2078  * FIXME
2079  *  The PROCESS_HEAP_ENTRY flag values seem different between this
2080  *  function and HeapWalk(). To be checked.
2081  */
2082 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
2083 {
2084     LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
2085     HEAP *heapPtr = HEAP_GetPtr(heap);
2086     SUBHEAP *sub, *currentheap = NULL;
2087     NTSTATUS ret;
2088     char *ptr;
2089     int region_index = 0;
2090
2091     if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
2092
2093     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
2094
2095     /* FIXME: enumerate large blocks too */
2096
2097     /* set ptr to the next arena to be examined */
2098
2099     if (!entry->lpData) /* first call (init) ? */
2100     {
2101         TRACE("begin walking of heap %p.\n", heap);
2102         currentheap = &heapPtr->subheap;
2103         ptr = (char*)currentheap->base + currentheap->headerSize;
2104     }
2105     else
2106     {
2107         ptr = entry->lpData;
2108         LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
2109         {
2110             if ((ptr >= (char *)sub->base) &&
2111                 (ptr < (char *)sub->base + sub->size))
2112             {
2113                 currentheap = sub;
2114                 break;
2115             }
2116             region_index++;
2117         }
2118         if (currentheap == NULL)
2119         {
2120             ERR("no matching subheap found, shouldn't happen !\n");
2121             ret = STATUS_NO_MORE_ENTRIES;
2122             goto HW_end;
2123         }
2124
2125         if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC ||
2126             ((ARENA_INUSE *)ptr - 1)->magic == ARENA_PENDING_MAGIC)
2127         {
2128             ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
2129             ptr += pArena->size & ARENA_SIZE_MASK;
2130         }
2131         else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
2132         {
2133             ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
2134             ptr += pArena->size & ARENA_SIZE_MASK;
2135         }
2136         else
2137             ptr += entry->cbData; /* point to next arena */
2138
2139         if (ptr > (char *)currentheap->base + currentheap->size - 1)
2140         {   /* proceed with next subheap */
2141             struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
2142             if (!next)
2143             {  /* successfully finished */
2144                 TRACE("end reached.\n");
2145                 ret = STATUS_NO_MORE_ENTRIES;
2146                 goto HW_end;
2147             }
2148             currentheap = LIST_ENTRY( next, SUBHEAP, entry );
2149             ptr = (char *)currentheap->base + currentheap->headerSize;
2150         }
2151     }
2152
2153     entry->wFlags = 0;
2154     if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2155     {
2156         ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2157
2158         /*TRACE("free, magic: %04x\n", pArena->magic);*/
2159
2160         entry->lpData = pArena + 1;
2161         entry->cbData = pArena->size & ARENA_SIZE_MASK;
2162         entry->cbOverhead = sizeof(ARENA_FREE);
2163         entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
2164     }
2165     else
2166     {
2167         ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2168
2169         /*TRACE("busy, magic: %04x\n", pArena->magic);*/
2170
2171         entry->lpData = pArena + 1;
2172         entry->cbData = pArena->size & ARENA_SIZE_MASK;
2173         entry->cbOverhead = sizeof(ARENA_INUSE);
2174         entry->wFlags = (pArena->magic == ARENA_PENDING_MAGIC) ?
2175                         PROCESS_HEAP_UNCOMMITTED_RANGE : PROCESS_HEAP_ENTRY_BUSY;
2176         /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
2177         and PROCESS_HEAP_ENTRY_DDESHARE yet */
2178     }
2179
2180     entry->iRegionIndex = region_index;
2181
2182     /* first element of heap ? */
2183     if (ptr == (char *)currentheap->base + currentheap->headerSize)
2184     {
2185         entry->wFlags |= PROCESS_HEAP_REGION;
2186         entry->u.Region.dwCommittedSize = currentheap->commitSize;
2187         entry->u.Region.dwUnCommittedSize =
2188                 currentheap->size - currentheap->commitSize;
2189         entry->u.Region.lpFirstBlock = /* first valid block */
2190                 (char *)currentheap->base + currentheap->headerSize;
2191         entry->u.Region.lpLastBlock  = /* first invalid block */
2192                 (char *)currentheap->base + currentheap->size;
2193     }
2194     ret = STATUS_SUCCESS;
2195     if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
2196
2197 HW_end:
2198     if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
2199     return ret;
2200 }
2201
2202
2203 /***********************************************************************
2204  *           RtlGetProcessHeaps    (NTDLL.@)
2205  *
2206  * Get the Heaps belonging to the current process.
2207  *
2208  * PARAMS
2209  *  count [I] size of heaps
2210  *  heaps [O] Destination array for heap HANDLE's
2211  *
2212  * RETURNS
2213  *  Success: The number of Heaps allocated by the process.
2214  *  Failure: 0.
2215  */
2216 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
2217 {
2218     ULONG total = 1;  /* main heap */
2219     struct list *ptr;
2220
2221     RtlEnterCriticalSection( &processHeap->critSection );
2222     LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
2223     if (total <= count)
2224     {
2225         *heaps++ = processHeap;
2226         LIST_FOR_EACH( ptr, &processHeap->entry )
2227             *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
2228     }
2229     RtlLeaveCriticalSection( &processHeap->critSection );
2230     return total;
2231 }
2232
2233 /***********************************************************************
2234  *           RtlQueryHeapInformation    (NTDLL.@)
2235  */
2236 NTSTATUS WINAPI RtlQueryHeapInformation( HANDLE heap, HEAP_INFORMATION_CLASS info_class,
2237                                          PVOID info, SIZE_T size_in, PSIZE_T size_out)
2238 {
2239     switch (info_class)
2240     {
2241     case HeapCompatibilityInformation:
2242         if (size_out) *size_out = sizeof(ULONG);
2243
2244         if (size_in < sizeof(ULONG))
2245             return STATUS_BUFFER_TOO_SMALL;
2246
2247         *(ULONG *)info = 0; /* standard heap */
2248         return STATUS_SUCCESS;
2249
2250     default:
2251         FIXME("Unknown heap information class %u\n", info_class);
2252         return STATUS_INVALID_INFO_CLASS;
2253     }
2254 }