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