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