push ca931951dc5f3f050707cce013d2412130f45f11
[wine/hacks.git] / dlls / ntdll / heap.c
blobb721142a30790b64dc4b2b1a2693fffc72ba3d82
1 /*
2 * Win32 heap functions
4 * Copyright 1996 Alexandre Julliard
5 * Copyright 1998 Ulrich Weigand
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.
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.
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
22 #include "config.h"
23 #include "wine/port.h"
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
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"
45 WINE_DEFAULT_DEBUG_CHANNEL(heap);
46 WINE_DECLARE_DEBUG_CHANNEL(heap_poison);
48 /* Note: the heap data structures are loosely based on what Pietrek describes in his
49 * book 'Windows 95 System Programming Secrets', with some adaptations for
50 * better compatibility with NT.
53 typedef struct tagARENA_INUSE
55 DWORD size; /* Block size; must be the first field */
56 DWORD magic : 24; /* Magic number */
57 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) */
58 } ARENA_INUSE;
60 typedef struct tagARENA_FREE
62 DWORD size; /* Block size; must be the first field */
63 DWORD magic; /* Magic number */
64 struct list entry; /* Entry in free list */
65 } ARENA_FREE;
67 typedef struct
69 struct list entry; /* entry in heap large blocks list */
70 SIZE_T data_size; /* size of user data */
71 SIZE_T block_size; /* total size of virtual memory block */
72 DWORD pad[2]; /* padding to ensure 16-byte alignment of data */
73 DWORD size; /* fields for compatibility with normal arenas */
74 DWORD magic; /* these must remain at the end of the structure */
75 } ARENA_LARGE;
77 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
78 #define ARENA_FLAG_PREV_FREE 0x00000002
79 #define ARENA_SIZE_MASK (~3)
80 #define ARENA_LARGE_SIZE 0xfedcba90 /* magic value for 'size' field in large blocks */
82 /* Value for arena 'magic' field */
83 #define ARENA_INUSE_MAGIC 0x455355
84 #define ARENA_FREE_MAGIC 0x45455246
85 #define ARENA_LARGE_MAGIC 0x6752614c
87 #define ARENA_INUSE_FILLER 0x55
88 #define ARENA_FREE_FILLER 0xaa
90 /* everything is aligned on 8 byte boundaries (16 for Win64) */
91 #define ALIGNMENT (2*sizeof(void*))
92 #define LARGE_ALIGNMENT 16 /* large blocks have stricter alignment */
93 #define ARENA_OFFSET (ALIGNMENT - sizeof(ARENA_INUSE))
95 C_ASSERT( sizeof(ARENA_LARGE) % LARGE_ALIGNMENT == 0 );
97 #define ROUND_SIZE(size) ((((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1)) + ARENA_OFFSET)
99 #define QUIET 1 /* Suppress messages */
100 #define NOISY 0 /* Report all errors */
102 /* minimum data size (without arenas) of an allocated block */
103 /* make sure that it's larger than a free list entry */
104 #define HEAP_MIN_DATA_SIZE ROUND_SIZE(2 * sizeof(struct list))
105 /* minimum size that must remain to shrink an allocated block */
106 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
107 /* minimum size to start allocating large blocks */
108 #define HEAP_MIN_LARGE_BLOCK_SIZE 0x7f000
110 /* Max size of the blocks on the free lists */
111 static const SIZE_T HEAP_freeListSizes[] =
113 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
115 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
117 typedef union
119 ARENA_FREE arena;
120 void *alignment[4];
121 } FREE_LIST_ENTRY;
123 struct tagHEAP;
125 typedef struct tagSUBHEAP
127 void *base; /* Base address of the sub-heap memory block */
128 SIZE_T size; /* Size of the whole sub-heap */
129 SIZE_T min_commit; /* Minimum committed size */
130 SIZE_T commitSize; /* Committed size of the sub-heap */
131 struct list entry; /* Entry in sub-heap list */
132 struct tagHEAP *heap; /* Main heap structure */
133 DWORD headerSize; /* Size of the heap header */
134 DWORD magic; /* Magic number */
135 } SUBHEAP;
137 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
139 typedef struct tagHEAP
141 DWORD unknown[3];
142 DWORD flags; /* Heap flags */
143 DWORD force_flags; /* Forced heap flags for debugging */
144 SUBHEAP subheap; /* First sub-heap */
145 struct list entry; /* Entry in process heap list */
146 struct list subheap_list; /* Sub-heap list */
147 struct list large_list; /* Large blocks list */
148 SIZE_T grow_size; /* Size of next subheap for growing heap */
149 DWORD magic; /* Magic number */
150 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
151 FREE_LIST_ENTRY *freeList; /* Free lists */
152 } HEAP;
154 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
156 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
157 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
159 static HEAP *processHeap; /* main process heap */
161 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
163 /* mark a block of memory as free for debugging purposes */
164 static inline void mark_block_free( void *ptr, SIZE_T size )
166 if (TRACE_ON(heap) || WARN_ON(heap) || TRACE_ON(heap_poison)) memset( ptr, ARENA_FREE_FILLER, size );
167 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
168 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
169 #elif defined( VALGRIND_MAKE_NOACCESS)
170 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
171 #endif
174 /* mark a block of memory as initialized for debugging purposes */
175 static inline void mark_block_initialized( void *ptr, SIZE_T size )
177 #if defined(VALGRIND_MAKE_MEM_DEFINED)
178 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
179 #elif defined(VALGRIND_MAKE_READABLE)
180 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
181 #endif
184 /* mark a block of memory as uninitialized for debugging purposes */
185 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
187 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
188 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
189 #elif defined(VALGRIND_MAKE_WRITABLE)
190 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
191 #endif
192 if (TRACE_ON(heap) || WARN_ON(heap) || TRACE_ON(heap_poison))
194 memset( ptr, ARENA_INUSE_FILLER, size );
195 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
196 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
197 #elif defined(VALGRIND_MAKE_WRITABLE)
198 /* make it uninitialized to valgrind again */
199 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
200 #endif
204 /* clear contents of a block of memory */
205 static inline void clear_block( void *ptr, SIZE_T size )
207 mark_block_initialized( ptr, size );
208 memset( ptr, 0, size );
211 /* notify that a new block of memory has been allocated for debugging purposes */
212 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
214 #ifdef VALGRIND_MALLOCLIKE_BLOCK
215 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
216 #endif
219 /* notify that a block of memory has been freed for debugging purposes */
220 static inline void notify_free( void const *ptr )
222 #ifdef VALGRIND_FREELIKE_BLOCK
223 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
224 #endif
227 static void subheap_notify_free_all(SUBHEAP const *subheap)
229 #ifdef VALGRIND_FREELIKE_BLOCK
230 char const *ptr = (char const *)subheap->base + subheap->headerSize;
232 if (!RUNNING_ON_VALGRIND) return;
234 while (ptr < (char const *)subheap->base + subheap->size)
236 if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
238 ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
239 if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
240 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
242 else
244 ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
245 if (pArena->magic!=ARENA_INUSE_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
246 notify_free(pArena + 1);
247 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
250 #endif
253 /* locate a free list entry of the appropriate size */
254 /* size is the size of the whole block including the arena header */
255 static inline unsigned int get_freelist_index( SIZE_T size )
257 unsigned int i;
259 size -= sizeof(ARENA_FREE);
260 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
261 return i;
264 /* get the memory protection type to use for a given heap */
265 static inline ULONG get_protection_type( DWORD flags )
267 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
270 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
272 0, 0, NULL, /* will be set later */
273 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
274 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
278 /***********************************************************************
279 * HEAP_Dump
281 static void HEAP_Dump( HEAP *heap )
283 unsigned int i;
284 SUBHEAP *subheap;
285 char *ptr;
287 DPRINTF( "Heap: %p\n", heap );
288 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
289 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
291 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
292 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
293 DPRINTF( "%p free %08lx prev=%p next=%p\n",
294 &heap->freeList[i].arena, HEAP_freeListSizes[i],
295 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
296 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
298 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
300 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
301 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
302 subheap, subheap->base, subheap->size, subheap->commitSize );
304 DPRINTF( "\n Block Arena Stat Size Id\n" );
305 ptr = (char *)subheap->base + subheap->headerSize;
306 while (ptr < (char *)subheap->base + subheap->size)
308 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
310 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
311 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
312 pArena, pArena->magic,
313 pArena->size & ARENA_SIZE_MASK,
314 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
315 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
316 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
317 arenaSize += sizeof(ARENA_FREE);
318 freeSize += pArena->size & ARENA_SIZE_MASK;
320 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
322 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
323 DPRINTF( "%p %08x Used %08x back=%p\n",
324 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
325 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
326 arenaSize += sizeof(ARENA_INUSE);
327 usedSize += pArena->size & ARENA_SIZE_MASK;
329 else
331 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
332 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
333 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
334 arenaSize += sizeof(ARENA_INUSE);
335 usedSize += pArena->size & ARENA_SIZE_MASK;
338 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
339 subheap->size, subheap->commitSize, freeSize, usedSize,
340 arenaSize, (arenaSize * 100) / subheap->size );
345 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
347 WORD rem_flags;
348 TRACE( "Dumping entry %p\n", entry );
349 TRACE( "lpData\t\t: %p\n", entry->lpData );
350 TRACE( "cbData\t\t: %08x\n", entry->cbData);
351 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
352 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
353 TRACE( "WFlags\t\t: ");
354 if (entry->wFlags & PROCESS_HEAP_REGION)
355 TRACE( "PROCESS_HEAP_REGION ");
356 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
357 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
358 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
359 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
360 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
361 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
362 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
363 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
364 rem_flags = entry->wFlags &
365 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
366 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
367 PROCESS_HEAP_ENTRY_DDESHARE);
368 if (rem_flags)
369 TRACE( "Unknown %08x", rem_flags);
370 TRACE( "\n");
371 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
372 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
374 /* Treat as block */
375 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
377 if (entry->wFlags & PROCESS_HEAP_REGION)
379 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
380 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
381 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
382 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
386 /***********************************************************************
387 * HEAP_GetPtr
388 * RETURNS
389 * Pointer to the heap
390 * NULL: Failure
392 static HEAP *HEAP_GetPtr(
393 HANDLE heap /* [in] Handle to the heap */
395 HEAP *heapPtr = heap;
396 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
398 ERR("Invalid heap %p!\n", heap );
399 return NULL;
401 if ((TRACE_ON(heap)|| TRACE_ON(heap_poison)) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
403 HEAP_Dump( heapPtr );
404 assert( FALSE );
405 return NULL;
407 return heapPtr;
411 /***********************************************************************
412 * HEAP_InsertFreeBlock
414 * Insert a free block into the free list.
416 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
418 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
419 if (last)
421 /* insert at end of free list, i.e. before the next free list entry */
422 pEntry++;
423 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
424 list_add_before( &pEntry->arena.entry, &pArena->entry );
426 else
428 /* insert at head of free list */
429 list_add_after( &pEntry->arena.entry, &pArena->entry );
431 pArena->size |= ARENA_FLAG_FREE;
435 /***********************************************************************
436 * HEAP_FindSubHeap
437 * Find the sub-heap containing a given address.
439 * RETURNS
440 * Pointer: Success
441 * NULL: Failure
443 static SUBHEAP *HEAP_FindSubHeap(
444 const HEAP *heap, /* [in] Heap pointer */
445 LPCVOID ptr ) /* [in] Address */
447 SUBHEAP *sub;
448 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
449 if ((ptr >= sub->base) &&
450 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
451 return sub;
452 return NULL;
456 /***********************************************************************
457 * HEAP_Commit
459 * Make sure the heap storage is committed for a given size in the specified arena.
461 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
463 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
464 SIZE_T size = (char *)ptr - (char *)subheap->base;
465 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
466 if (size > subheap->size) size = subheap->size;
467 if (size <= subheap->commitSize) return TRUE;
468 size -= subheap->commitSize;
469 ptr = (char *)subheap->base + subheap->commitSize;
470 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
471 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
473 WARN("Could not commit %08lx bytes at %p for heap %p\n",
474 size, ptr, subheap->heap );
475 return FALSE;
477 subheap->commitSize += size;
478 return TRUE;
482 /***********************************************************************
483 * HEAP_Decommit
485 * If possible, decommit the heap storage from (including) 'ptr'.
487 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
489 void *addr;
490 SIZE_T decommit_size;
491 SIZE_T size = (char *)ptr - (char *)subheap->base;
493 /* round to next block and add one full block */
494 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
495 size = max( size, subheap->min_commit );
496 if (size >= subheap->commitSize) return TRUE;
497 decommit_size = subheap->commitSize - size;
498 addr = (char *)subheap->base + size;
500 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
502 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
503 decommit_size, (char *)subheap->base + size, subheap->heap );
504 return FALSE;
506 subheap->commitSize -= decommit_size;
507 return TRUE;
511 /***********************************************************************
512 * HEAP_CreateFreeBlock
514 * Create a free block at a specified address. 'size' is the size of the
515 * whole block, including the new arena.
517 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
519 ARENA_FREE *pFree;
520 char *pEnd;
521 BOOL last;
523 /* Create a free arena */
524 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
525 pFree = ptr;
526 pFree->magic = ARENA_FREE_MAGIC;
528 /* If debugging, erase the freed block content */
530 pEnd = (char *)ptr + size;
531 if (pEnd > (char *)subheap->base + subheap->commitSize)
532 pEnd = (char *)subheap->base + subheap->commitSize;
533 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
535 /* Check if next block is free also */
537 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
538 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
540 /* Remove the next arena from the free list */
541 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
542 list_remove( &pNext->entry );
543 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
544 mark_block_free( pNext, sizeof(ARENA_FREE) );
547 /* Set the next block PREV_FREE flag and pointer */
549 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
550 if (!last)
552 DWORD *pNext = (DWORD *)((char *)ptr + size);
553 *pNext |= ARENA_FLAG_PREV_FREE;
554 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
555 *((ARENA_FREE **)pNext - 1) = pFree;
558 /* Last, insert the new block into the free list */
560 pFree->size = size - sizeof(*pFree);
561 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
565 /***********************************************************************
566 * HEAP_MakeInUseBlockFree
568 * Turn an in-use block into a free block. Can also decommit the end of
569 * the heap, and possibly even free the sub-heap altogether.
571 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
573 ARENA_FREE *pFree;
574 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
576 /* Check if we can merge with previous block */
578 if (pArena->size & ARENA_FLAG_PREV_FREE)
580 pFree = *((ARENA_FREE **)pArena - 1);
581 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
582 /* Remove it from the free list */
583 list_remove( &pFree->entry );
585 else pFree = (ARENA_FREE *)pArena;
587 /* Create a free block */
589 HEAP_CreateFreeBlock( subheap, pFree, size );
590 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
591 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
592 return; /* Not the last block, so nothing more to do */
594 /* Free the whole sub-heap if it's empty and not the original one */
596 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
597 (subheap != &subheap->heap->subheap))
599 SIZE_T size = 0;
600 void *addr = subheap->base;
601 /* Remove the free block from the list */
602 list_remove( &pFree->entry );
603 /* Remove the subheap from the list */
604 list_remove( &subheap->entry );
605 /* Free the memory */
606 subheap->magic = 0;
607 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
608 return;
611 /* Decommit the end of the heap */
613 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
617 /***********************************************************************
618 * HEAP_ShrinkBlock
620 * Shrink an in-use block.
622 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
624 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
626 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
627 (pArena->size & ARENA_SIZE_MASK) - size );
628 /* assign size plus previous arena flags */
629 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
631 else
633 /* Turn off PREV_FREE flag in next block */
634 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
635 if (pNext < (char *)subheap->base + subheap->size)
636 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
641 /***********************************************************************
642 * allocate_large_block
644 static void *allocate_large_block( HEAP *heap, DWORD flags, SIZE_T size )
646 ARENA_LARGE *arena;
647 SIZE_T block_size = sizeof(*arena) + ROUND_SIZE(size);
648 LPVOID address = NULL;
650 if (block_size < size) return NULL; /* overflow */
651 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 5,
652 &block_size, MEM_COMMIT, get_protection_type( flags ) ))
654 WARN("Could not allocate block for %08lx bytes\n", size );
655 return NULL;
657 arena = address;
658 arena->data_size = size;
659 arena->block_size = block_size;
660 arena->size = ARENA_LARGE_SIZE;
661 arena->magic = ARENA_LARGE_MAGIC;
662 list_add_tail( &heap->large_list, &arena->entry );
663 return arena + 1;
667 /***********************************************************************
668 * free_large_block
670 static void free_large_block( HEAP *heap, DWORD flags, void *ptr )
672 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
673 LPVOID address = arena;
674 SIZE_T size = 0;
676 list_remove( &arena->entry );
677 NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
681 /***********************************************************************
682 * realloc_large_block
684 static void *realloc_large_block( HEAP *heap, DWORD flags, void *ptr, SIZE_T size )
686 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
687 void *new_ptr;
689 if (arena->block_size - sizeof(*arena) >= size)
691 /* FIXME: we could remap zero-pages instead */
692 if ((flags & HEAP_ZERO_MEMORY) && size > arena->data_size)
693 memset( (char *)ptr + arena->data_size, 0, size - arena->data_size );
694 arena->data_size = size;
695 return ptr;
697 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) return NULL;
698 if (!(new_ptr = allocate_large_block( heap, flags, size )))
700 WARN("Could not allocate block for %08lx bytes\n", size );
701 return NULL;
703 memcpy( new_ptr, ptr, arena->data_size );
704 free_large_block( heap, flags, ptr );
705 return new_ptr;
709 /***********************************************************************
710 * find_large_block
712 static ARENA_LARGE *find_large_block( HEAP *heap, const void *ptr )
714 ARENA_LARGE *arena;
716 LIST_FOR_EACH_ENTRY( arena, &heap->large_list, ARENA_LARGE, entry )
717 if (ptr == arena + 1) return arena;
719 return NULL;
723 /***********************************************************************
724 * validate_large_arena
726 static BOOL validate_large_arena( HEAP *heap, const ARENA_LARGE *arena, BOOL quiet )
728 if ((ULONG_PTR)arena % getpagesize())
730 if (quiet == NOISY)
732 ERR( "Heap %p: invalid large arena pointer %p\n", heap, arena );
733 if (TRACE_ON(heap)) HEAP_Dump( heap );
735 else if (WARN_ON(heap))
737 WARN( "Heap %p: unaligned arena pointer %p\n", heap, arena );
738 if (TRACE_ON(heap)) HEAP_Dump( heap );
740 return FALSE;
742 if (arena->size != ARENA_LARGE_SIZE || arena->magic != ARENA_LARGE_MAGIC)
744 if (quiet == NOISY)
746 ERR( "Heap %p: invalid large arena %p values %x/%x\n",
747 heap, arena, arena->size, arena->magic );
748 if (TRACE_ON(heap)) HEAP_Dump( heap );
750 else if (WARN_ON(heap))
752 WARN( "Heap %p: invalid large arena %p values %x/%x\n",
753 heap, arena, arena->size, arena->magic );
754 if (TRACE_ON(heap)) HEAP_Dump( heap );
756 return FALSE;
758 return TRUE;
762 /***********************************************************************
763 * HEAP_CreateSubHeap
765 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, LPVOID address, DWORD flags,
766 SIZE_T commitSize, SIZE_T totalSize )
768 SUBHEAP *subheap;
769 FREE_LIST_ENTRY *pEntry;
770 unsigned int i;
772 if (!address)
774 /* round-up sizes on a 64K boundary */
775 totalSize = (totalSize + 0xffff) & 0xffff0000;
776 commitSize = (commitSize + 0xffff) & 0xffff0000;
777 if (!commitSize) commitSize = 0x10000;
778 totalSize = min( totalSize, 0xffff0000 ); /* don't allow a heap larger than 4Gb */
779 if (totalSize < commitSize) totalSize = commitSize;
780 if (flags & HEAP_SHARED) commitSize = totalSize; /* always commit everything in a shared heap */
782 /* allocate the memory block */
783 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
784 MEM_RESERVE, get_protection_type( flags ) ))
786 WARN("Could not allocate %08lx bytes\n", totalSize );
787 return NULL;
789 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
790 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
792 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
793 return NULL;
797 if (heap)
799 /* If this is a secondary subheap, insert it into list */
801 subheap = address;
802 subheap->base = address;
803 subheap->heap = heap;
804 subheap->size = totalSize;
805 subheap->min_commit = 0x10000;
806 subheap->commitSize = commitSize;
807 subheap->magic = SUBHEAP_MAGIC;
808 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
809 list_add_head( &heap->subheap_list, &subheap->entry );
811 else
813 /* If this is a primary subheap, initialize main heap */
815 heap = address;
816 heap->flags = flags;
817 heap->magic = HEAP_MAGIC;
818 heap->grow_size = max( HEAP_DEF_SIZE, totalSize );
819 list_init( &heap->subheap_list );
820 list_init( &heap->large_list );
822 subheap = &heap->subheap;
823 subheap->base = address;
824 subheap->heap = heap;
825 subheap->size = totalSize;
826 subheap->min_commit = commitSize;
827 subheap->commitSize = commitSize;
828 subheap->magic = SUBHEAP_MAGIC;
829 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
830 list_add_head( &heap->subheap_list, &subheap->entry );
832 /* Build the free lists */
834 heap->freeList = (FREE_LIST_ENTRY *)((char *)heap + subheap->headerSize);
835 subheap->headerSize += HEAP_NB_FREE_LISTS * sizeof(FREE_LIST_ENTRY);
836 list_init( &heap->freeList[0].arena.entry );
837 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
839 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
840 pEntry->arena.magic = ARENA_FREE_MAGIC;
841 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
844 /* Initialize critical section */
846 if (!processHeap) /* do it by hand to avoid memory allocations */
848 if(TRACE_ON(heap_poison))
849 TRACE_(heap_poison)("poisioning heap\n");
850 heap->critSection.DebugInfo = &process_heap_critsect_debug;
851 heap->critSection.LockCount = -1;
852 heap->critSection.RecursionCount = 0;
853 heap->critSection.OwningThread = 0;
854 heap->critSection.LockSemaphore = 0;
855 heap->critSection.SpinCount = 0;
856 process_heap_critsect_debug.CriticalSection = &heap->critSection;
858 else
860 RtlInitializeCriticalSection( &heap->critSection );
861 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
864 if (flags & HEAP_SHARED)
866 /* let's assume that only one thread at a time will try to do this */
867 HANDLE sem = heap->critSection.LockSemaphore;
868 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
870 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
871 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
872 heap->critSection.LockSemaphore = sem;
873 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
874 heap->critSection.DebugInfo = NULL;
878 /* Create the first free block */
880 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
881 subheap->size - subheap->headerSize );
883 return subheap;
887 /***********************************************************************
888 * HEAP_FindFreeBlock
890 * Find a free block at least as large as the requested size, and make sure
891 * the requested size is committed.
893 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
894 SUBHEAP **ppSubHeap )
896 SUBHEAP *subheap;
897 struct list *ptr;
898 SIZE_T total_size;
899 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
901 /* Find a suitable free list, and in it find a block large enough */
903 ptr = &pEntry->arena.entry;
904 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
906 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
907 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
908 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
909 if (arena_size >= size)
911 subheap = HEAP_FindSubHeap( heap, pArena );
912 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
913 *ppSubHeap = subheap;
914 return pArena;
918 /* If no block was found, attempt to grow the heap */
920 if (!(heap->flags & HEAP_GROWABLE))
922 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
923 return NULL;
925 /* make sure that we have a big enough size *committed* to fit another
926 * last free arena in !
927 * So just one heap struct, one first free arena which will eventually
928 * get used, and a second free arena that might get assigned all remaining
929 * free space in HEAP_ShrinkBlock() */
930 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
931 if (total_size < size) return NULL; /* overflow */
933 if ((subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
934 max( heap->grow_size, total_size ) )))
936 if (heap->grow_size < 128 * 1024 * 1024) heap->grow_size *= 2;
938 else while (!subheap) /* shrink the grow size again if we are running out of space */
940 if (heap->grow_size <= total_size || heap->grow_size <= 4 * 1024 * 1024) return NULL;
941 heap->grow_size /= 2;
942 subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
943 max( heap->grow_size, total_size ) );
946 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
947 subheap, subheap->size, heap );
949 *ppSubHeap = subheap;
950 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
954 /***********************************************************************
955 * HEAP_IsValidArenaPtr
957 * Check that the pointer is inside the range possible for arenas.
959 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
961 unsigned int i;
962 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
963 if (!subheap) return FALSE;
964 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
965 if (subheap != &heap->subheap) return FALSE;
966 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
967 if (ptr == &heap->freeList[i].arena) return TRUE;
968 return FALSE;
972 /***********************************************************************
973 * HEAP_ValidateFreeArena
975 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
977 ARENA_FREE *prev, *next;
978 char *heapEnd = (char *)subheap->base + subheap->size;
980 /* Check for unaligned pointers */
981 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
983 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
984 return FALSE;
987 /* Check magic number */
988 if (pArena->magic != ARENA_FREE_MAGIC)
990 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
991 return FALSE;
993 /* Check size flags */
994 if (!(pArena->size & ARENA_FLAG_FREE) ||
995 (pArena->size & ARENA_FLAG_PREV_FREE))
997 ERR("Heap %p: bad flags %08x for free arena %p\n",
998 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
999 return FALSE;
1001 /* Check arena size */
1002 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
1004 ERR("Heap %p: bad size %08x for free arena %p\n",
1005 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
1006 return FALSE;
1008 /* Check that next pointer is valid */
1009 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
1010 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
1012 ERR("Heap %p: bad next ptr %p for arena %p\n",
1013 subheap->heap, next, pArena );
1014 return FALSE;
1016 /* Check that next arena is free */
1017 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1019 ERR("Heap %p: next arena %p invalid for %p\n",
1020 subheap->heap, next, pArena );
1021 return FALSE;
1023 /* Check that prev pointer is valid */
1024 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1025 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1027 ERR("Heap %p: bad prev ptr %p for arena %p\n",
1028 subheap->heap, prev, pArena );
1029 return FALSE;
1031 /* Check that prev arena is free */
1032 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1034 /* this often means that the prev arena got overwritten
1035 * by a memory write before that prev arena */
1036 ERR("Heap %p: prev arena %p invalid for %p\n",
1037 subheap->heap, prev, pArena );
1038 return FALSE;
1040 /* Check that next block has PREV_FREE flag */
1041 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
1043 if (!(*(DWORD *)((char *)(pArena + 1) +
1044 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1046 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1047 subheap->heap, pArena );
1048 return FALSE;
1050 /* Check next block back pointer */
1051 if (*((ARENA_FREE **)((char *)(pArena + 1) +
1052 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
1054 ERR("Heap %p: arena %p has wrong back ptr %p\n",
1055 subheap->heap, pArena,
1056 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
1057 return FALSE;
1060 return TRUE;
1064 /***********************************************************************
1065 * HEAP_ValidateInUseArena
1067 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1069 const char *heapEnd = (const char *)subheap->base + subheap->size;
1071 /* Check for unaligned pointers */
1072 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1074 if ( quiet == NOISY )
1076 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1077 if ( TRACE_ON(heap) )
1078 HEAP_Dump( subheap->heap );
1080 else if ( WARN_ON(heap) )
1082 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1083 if ( TRACE_ON(heap) )
1084 HEAP_Dump( subheap->heap );
1086 return FALSE;
1089 /* Check magic number */
1090 if (pArena->magic != ARENA_INUSE_MAGIC)
1092 if (quiet == NOISY) {
1093 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1094 if (TRACE_ON(heap))
1095 HEAP_Dump( subheap->heap );
1096 } else if (WARN_ON(heap)) {
1097 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1098 if (TRACE_ON(heap))
1099 HEAP_Dump( subheap->heap );
1101 return FALSE;
1103 /* Check size flags */
1104 if (pArena->size & ARENA_FLAG_FREE)
1106 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1107 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1108 return FALSE;
1110 /* Check arena size */
1111 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
1113 ERR("Heap %p: bad size %08x for in-use arena %p\n",
1114 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
1115 return FALSE;
1117 /* Check next arena PREV_FREE flag */
1118 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
1119 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1121 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
1122 subheap->heap, pArena );
1123 return FALSE;
1125 /* Check prev free arena */
1126 if (pArena->size & ARENA_FLAG_PREV_FREE)
1128 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1129 /* Check prev pointer */
1130 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1132 ERR("Heap %p: bad back ptr %p for arena %p\n",
1133 subheap->heap, pPrev, pArena );
1134 return FALSE;
1136 /* Check that prev arena is free */
1137 if (!(pPrev->size & ARENA_FLAG_FREE) ||
1138 (pPrev->magic != ARENA_FREE_MAGIC))
1140 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1141 subheap->heap, pPrev, pArena );
1142 return FALSE;
1144 /* Check that prev arena is really the previous block */
1145 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1147 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1148 subheap->heap, pPrev, pArena );
1149 return FALSE;
1152 return TRUE;
1156 /***********************************************************************
1157 * HEAP_IsRealArena [Internal]
1158 * Validates a block is a valid arena.
1160 * RETURNS
1161 * TRUE: Success
1162 * FALSE: Failure
1164 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1165 DWORD flags, /* [in] Bit flags that control access during operation */
1166 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1167 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1168 * does not complain */
1170 SUBHEAP *subheap;
1171 BOOL ret = TRUE;
1172 const ARENA_LARGE *large_arena;
1174 flags &= HEAP_NO_SERIALIZE;
1175 flags |= heapPtr->flags;
1176 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1177 if (!(flags & HEAP_NO_SERIALIZE))
1178 RtlEnterCriticalSection( &heapPtr->critSection );
1180 if (block) /* only check this single memory block */
1182 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1184 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1185 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1187 if (!(large_arena = find_large_block( heapPtr, block )))
1189 if (quiet == NOISY)
1190 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1191 else if (WARN_ON(heap))
1192 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1193 ret = FALSE;
1195 else
1196 ret = validate_large_arena( heapPtr, large_arena, quiet );
1197 } else
1198 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1200 if (!(flags & HEAP_NO_SERIALIZE))
1201 RtlLeaveCriticalSection( &heapPtr->critSection );
1202 return ret;
1205 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1207 char *ptr = (char *)subheap->base + subheap->headerSize;
1208 while (ptr < (char *)subheap->base + subheap->size)
1210 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1212 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1213 ret = FALSE;
1214 break;
1216 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1218 else
1220 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1221 ret = FALSE;
1222 break;
1224 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1227 if (!ret) break;
1230 LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1231 if (!(ret = validate_large_arena( heapPtr, large_arena, quiet ))) break;
1233 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1234 return ret;
1238 /***********************************************************************
1239 * RtlCreateHeap (NTDLL.@)
1241 * Create a new Heap.
1243 * PARAMS
1244 * flags [I] HEAP_ flags from "winnt.h"
1245 * addr [I] Desired base address
1246 * totalSize [I] Total size of the heap, or 0 for a growable heap
1247 * commitSize [I] Amount of heap space to commit
1248 * unknown [I] Not yet understood
1249 * definition [I] Heap definition
1251 * RETURNS
1252 * Success: A HANDLE to the newly created heap.
1253 * Failure: a NULL HANDLE.
1255 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1256 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1258 SUBHEAP *subheap;
1260 /* Allocate the heap block */
1262 if (!totalSize)
1264 totalSize = HEAP_DEF_SIZE;
1265 flags |= HEAP_GROWABLE;
1268 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1270 /* link it into the per-process heap list */
1271 if (processHeap)
1273 HEAP *heapPtr = subheap->heap;
1274 RtlEnterCriticalSection( &processHeap->critSection );
1275 list_add_head( &processHeap->entry, &heapPtr->entry );
1276 RtlLeaveCriticalSection( &processHeap->critSection );
1278 else if (!addr)
1280 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1281 list_init( &processHeap->entry );
1284 return subheap->heap;
1288 /***********************************************************************
1289 * RtlDestroyHeap (NTDLL.@)
1291 * Destroy a Heap created with RtlCreateHeap().
1293 * PARAMS
1294 * heap [I] Heap to destroy.
1296 * RETURNS
1297 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1298 * Failure: The Heap handle, if heap is the process heap.
1300 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1302 HEAP *heapPtr = HEAP_GetPtr( heap );
1303 SUBHEAP *subheap, *next;
1304 ARENA_LARGE *arena, *arena_next;
1305 SIZE_T size;
1306 void *addr;
1308 TRACE("%p\n", heap );
1309 if (!heapPtr) return heap;
1311 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1313 /* remove it from the per-process list */
1314 RtlEnterCriticalSection( &processHeap->critSection );
1315 list_remove( &heapPtr->entry );
1316 RtlLeaveCriticalSection( &processHeap->critSection );
1318 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1319 RtlDeleteCriticalSection( &heapPtr->critSection );
1321 LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1323 list_remove( &arena->entry );
1324 size = 0;
1325 addr = arena;
1326 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1328 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1330 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1331 subheap_notify_free_all(subheap);
1332 list_remove( &subheap->entry );
1333 size = 0;
1334 addr = subheap->base;
1335 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1337 subheap_notify_free_all(&heapPtr->subheap);
1338 size = 0;
1339 addr = heapPtr->subheap.base;
1340 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1341 return 0;
1345 /***********************************************************************
1346 * RtlAllocateHeap (NTDLL.@)
1348 * Allocate a memory block from a Heap.
1350 * PARAMS
1351 * heap [I] Heap to allocate block from
1352 * flags [I] HEAP_ flags from "winnt.h"
1353 * size [I] Size of the memory block to allocate
1355 * RETURNS
1356 * Success: A pointer to the newly allocated block
1357 * Failure: NULL.
1359 * NOTES
1360 * This call does not SetLastError().
1362 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1364 ARENA_FREE *pArena;
1365 ARENA_INUSE *pInUse;
1366 SUBHEAP *subheap;
1367 HEAP *heapPtr = HEAP_GetPtr( heap );
1368 SIZE_T rounded_size;
1370 /* Validate the parameters */
1372 if (!heapPtr) return NULL;
1373 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1374 flags |= heapPtr->flags;
1375 rounded_size = ROUND_SIZE(size);
1376 if (rounded_size < size) /* overflow */
1378 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1379 return NULL;
1381 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1383 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1385 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1387 void *ret = allocate_large_block( heap, flags, size );
1388 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1389 if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1390 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1391 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1392 return ret;
1395 /* Locate a suitable free block */
1397 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1399 TRACE("(%p,%08x,%08lx): returning NULL\n",
1400 heap, flags, size );
1401 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1402 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1403 return NULL;
1406 /* Remove the arena from the free list */
1408 list_remove( &pArena->entry );
1410 /* Build the in-use arena */
1412 pInUse = (ARENA_INUSE *)pArena;
1414 /* in-use arena is smaller than free arena,
1415 * so we have to add the difference to the size */
1416 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1417 pInUse->magic = ARENA_INUSE_MAGIC;
1419 /* Shrink the block */
1421 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1422 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1424 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1426 if (flags & HEAP_ZERO_MEMORY)
1428 clear_block( pInUse + 1, size );
1429 mark_block_uninitialized( (char *)(pInUse + 1) + size, pInUse->unused_bytes );
1431 else
1432 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1434 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1436 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1437 return pInUse + 1;
1441 /***********************************************************************
1442 * RtlFreeHeap (NTDLL.@)
1444 * Free a memory block allocated with RtlAllocateHeap().
1446 * PARAMS
1447 * heap [I] Heap that block was allocated from
1448 * flags [I] HEAP_ flags from "winnt.h"
1449 * ptr [I] Block to free
1451 * RETURNS
1452 * Success: TRUE, if ptr is NULL or was freed successfully.
1453 * Failure: FALSE.
1455 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1457 ARENA_INUSE *pInUse;
1458 SUBHEAP *subheap;
1459 HEAP *heapPtr;
1461 /* Validate the parameters */
1463 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1465 heapPtr = HEAP_GetPtr( heap );
1466 if (!heapPtr)
1468 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1469 return FALSE;
1472 flags &= HEAP_NO_SERIALIZE;
1473 flags |= heapPtr->flags;
1474 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1476 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1477 notify_free( ptr );
1479 /* Some sanity checks */
1480 pInUse = (ARENA_INUSE *)ptr - 1;
1481 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse )))
1483 if (!find_large_block( heapPtr, ptr )) goto error;
1484 free_large_block( heapPtr, flags, ptr );
1485 goto done;
1487 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1488 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1490 /* Turn the block into a free block */
1492 HEAP_MakeInUseBlockFree( subheap, pInUse );
1494 done:
1495 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1496 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1497 return TRUE;
1499 error:
1500 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1501 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1502 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1503 return FALSE;
1507 /***********************************************************************
1508 * RtlReAllocateHeap (NTDLL.@)
1510 * Change the size of a memory block allocated with RtlAllocateHeap().
1512 * PARAMS
1513 * heap [I] Heap that block was allocated from
1514 * flags [I] HEAP_ flags from "winnt.h"
1515 * ptr [I] Block to resize
1516 * size [I] Size of the memory block to allocate
1518 * RETURNS
1519 * Success: A pointer to the resized block (which may be different).
1520 * Failure: NULL.
1522 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1524 ARENA_INUSE *pArena;
1525 HEAP *heapPtr;
1526 SUBHEAP *subheap;
1527 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1528 void *ret;
1530 if (!ptr) return NULL;
1531 if (!(heapPtr = HEAP_GetPtr( heap )))
1533 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1534 return NULL;
1537 /* Validate the parameters */
1539 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1540 HEAP_REALLOC_IN_PLACE_ONLY;
1541 flags |= heapPtr->flags;
1542 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1544 rounded_size = ROUND_SIZE(size);
1545 if (rounded_size < size) goto oom; /* overflow */
1546 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1548 pArena = (ARENA_INUSE *)ptr - 1;
1549 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena )))
1551 if (!find_large_block( heapPtr, ptr )) goto error;
1552 if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1553 notify_free( ptr );
1554 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1555 goto done;
1557 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1558 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1560 /* Check if we need to grow the block */
1562 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1563 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1564 if (rounded_size > oldBlockSize)
1566 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1568 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1570 if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1571 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1572 memcpy( ret, pArena + 1, oldActualSize );
1573 notify_free( pArena + 1 );
1574 HEAP_MakeInUseBlockFree( subheap, pArena );
1575 goto done;
1577 if ((pNext < (char *)subheap->base + subheap->size) &&
1578 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1579 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1581 /* The next block is free and large enough */
1582 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1583 list_remove( &pFree->entry );
1584 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1585 if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1586 notify_free( pArena + 1 );
1587 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1588 notify_alloc( pArena + 1, size, FALSE );
1589 /* FIXME: this is wrong as we may lose old VBits settings */
1590 mark_block_initialized( pArena + 1, oldActualSize );
1592 else /* Do it the hard way */
1594 ARENA_FREE *pNew;
1595 ARENA_INUSE *pInUse;
1596 SUBHEAP *newsubheap;
1598 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1599 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1600 goto oom;
1602 /* Build the in-use arena */
1604 list_remove( &pNew->entry );
1605 pInUse = (ARENA_INUSE *)pNew;
1606 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1607 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1608 pInUse->magic = ARENA_INUSE_MAGIC;
1609 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1611 mark_block_initialized( pInUse + 1, oldActualSize );
1612 notify_alloc( pInUse + 1, size, FALSE );
1613 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1615 /* Free the previous block */
1617 notify_free( pArena + 1 );
1618 HEAP_MakeInUseBlockFree( subheap, pArena );
1619 subheap = newsubheap;
1620 pArena = pInUse;
1623 else
1625 /* Shrink the block */
1626 notify_free( pArena + 1 );
1627 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1628 notify_alloc( pArena + 1, size, FALSE );
1629 /* FIXME: this is wrong as we may lose old VBits settings */
1630 mark_block_initialized( pArena + 1, size );
1633 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1635 /* Clear the extra bytes if needed */
1637 if (size > oldActualSize)
1639 if (flags & HEAP_ZERO_MEMORY)
1641 clear_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize );
1642 mark_block_uninitialized( (char *)(pArena + 1) + size, pArena->unused_bytes );
1644 else
1645 mark_block_uninitialized( (char *)(pArena + 1) + oldActualSize,
1646 (pArena->size & ARENA_SIZE_MASK) - oldActualSize );
1649 /* Return the new arena */
1651 ret = pArena + 1;
1652 done:
1653 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1654 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1655 return ret;
1657 oom:
1658 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1659 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1660 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1661 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1662 return NULL;
1664 error:
1665 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1666 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1667 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1668 return NULL;
1672 /***********************************************************************
1673 * RtlCompactHeap (NTDLL.@)
1675 * Compact the free space in a Heap.
1677 * PARAMS
1678 * heap [I] Heap that block was allocated from
1679 * flags [I] HEAP_ flags from "winnt.h"
1681 * RETURNS
1682 * The number of bytes compacted.
1684 * NOTES
1685 * This function is a harmless stub.
1687 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1689 static BOOL reported;
1690 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1691 return 0;
1695 /***********************************************************************
1696 * RtlLockHeap (NTDLL.@)
1698 * Lock a Heap.
1700 * PARAMS
1701 * heap [I] Heap to lock
1703 * RETURNS
1704 * Success: TRUE. The Heap is locked.
1705 * Failure: FALSE, if heap is invalid.
1707 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1709 HEAP *heapPtr = HEAP_GetPtr( heap );
1710 if (!heapPtr) return FALSE;
1711 RtlEnterCriticalSection( &heapPtr->critSection );
1712 return TRUE;
1716 /***********************************************************************
1717 * RtlUnlockHeap (NTDLL.@)
1719 * Unlock a Heap.
1721 * PARAMS
1722 * heap [I] Heap to unlock
1724 * RETURNS
1725 * Success: TRUE. The Heap is unlocked.
1726 * Failure: FALSE, if heap is invalid.
1728 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1730 HEAP *heapPtr = HEAP_GetPtr( heap );
1731 if (!heapPtr) return FALSE;
1732 RtlLeaveCriticalSection( &heapPtr->critSection );
1733 return TRUE;
1737 /***********************************************************************
1738 * RtlSizeHeap (NTDLL.@)
1740 * Get the actual size of a memory block allocated from a Heap.
1742 * PARAMS
1743 * heap [I] Heap that block was allocated from
1744 * flags [I] HEAP_ flags from "winnt.h"
1745 * ptr [I] Block to get the size of
1747 * RETURNS
1748 * Success: The size of the block.
1749 * Failure: -1, heap or ptr are invalid.
1751 * NOTES
1752 * The size may be bigger than what was passed to RtlAllocateHeap().
1754 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1756 SIZE_T ret;
1757 HEAP *heapPtr = HEAP_GetPtr( heap );
1759 if (!heapPtr)
1761 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1762 return ~0UL;
1764 flags &= HEAP_NO_SERIALIZE;
1765 flags |= heapPtr->flags;
1766 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1767 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1769 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1770 ret = ~0UL;
1772 else
1774 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1775 if (pArena->size == ARENA_LARGE_SIZE)
1777 const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
1778 ret = large_arena->data_size;
1780 else ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1782 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1784 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1785 return ret;
1789 /***********************************************************************
1790 * RtlValidateHeap (NTDLL.@)
1792 * Determine if a block is a valid allocation from a heap.
1794 * PARAMS
1795 * heap [I] Heap that block was allocated from
1796 * flags [I] HEAP_ flags from "winnt.h"
1797 * ptr [I] Block to check
1799 * RETURNS
1800 * Success: TRUE. The block was allocated from heap.
1801 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1803 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1805 HEAP *heapPtr = HEAP_GetPtr( heap );
1806 if (!heapPtr) return FALSE;
1807 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1811 /***********************************************************************
1812 * RtlWalkHeap (NTDLL.@)
1814 * FIXME
1815 * The PROCESS_HEAP_ENTRY flag values seem different between this
1816 * function and HeapWalk(). To be checked.
1818 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1820 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1821 HEAP *heapPtr = HEAP_GetPtr(heap);
1822 SUBHEAP *sub, *currentheap = NULL;
1823 NTSTATUS ret;
1824 char *ptr;
1825 int region_index = 0;
1827 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1829 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1831 /* FIXME: enumerate large blocks too */
1833 /* set ptr to the next arena to be examined */
1835 if (!entry->lpData) /* first call (init) ? */
1837 TRACE("begin walking of heap %p.\n", heap);
1838 currentheap = &heapPtr->subheap;
1839 ptr = (char*)currentheap->base + currentheap->headerSize;
1841 else
1843 ptr = entry->lpData;
1844 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1846 if ((ptr >= (char *)sub->base) &&
1847 (ptr < (char *)sub->base + sub->size))
1849 currentheap = sub;
1850 break;
1852 region_index++;
1854 if (currentheap == NULL)
1856 ERR("no matching subheap found, shouldn't happen !\n");
1857 ret = STATUS_NO_MORE_ENTRIES;
1858 goto HW_end;
1861 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1863 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1864 ptr += pArena->size & ARENA_SIZE_MASK;
1866 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1868 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1869 ptr += pArena->size & ARENA_SIZE_MASK;
1871 else
1872 ptr += entry->cbData; /* point to next arena */
1874 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1875 { /* proceed with next subheap */
1876 struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
1877 if (!next)
1878 { /* successfully finished */
1879 TRACE("end reached.\n");
1880 ret = STATUS_NO_MORE_ENTRIES;
1881 goto HW_end;
1883 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1884 ptr = (char *)currentheap->base + currentheap->headerSize;
1888 entry->wFlags = 0;
1889 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1891 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1893 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1895 entry->lpData = pArena + 1;
1896 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1897 entry->cbOverhead = sizeof(ARENA_FREE);
1898 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1900 else
1902 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1904 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1906 entry->lpData = pArena + 1;
1907 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1908 entry->cbOverhead = sizeof(ARENA_INUSE);
1909 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1910 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1911 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1914 entry->iRegionIndex = region_index;
1916 /* first element of heap ? */
1917 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1919 entry->wFlags |= PROCESS_HEAP_REGION;
1920 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1921 entry->u.Region.dwUnCommittedSize =
1922 currentheap->size - currentheap->commitSize;
1923 entry->u.Region.lpFirstBlock = /* first valid block */
1924 (char *)currentheap->base + currentheap->headerSize;
1925 entry->u.Region.lpLastBlock = /* first invalid block */
1926 (char *)currentheap->base + currentheap->size;
1928 ret = STATUS_SUCCESS;
1929 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1931 HW_end:
1932 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1933 return ret;
1937 /***********************************************************************
1938 * RtlGetProcessHeaps (NTDLL.@)
1940 * Get the Heaps belonging to the current process.
1942 * PARAMS
1943 * count [I] size of heaps
1944 * heaps [O] Destination array for heap HANDLE's
1946 * RETURNS
1947 * Success: The number of Heaps allocated by the process.
1948 * Failure: 0.
1950 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1952 ULONG total = 1; /* main heap */
1953 struct list *ptr;
1955 RtlEnterCriticalSection( &processHeap->critSection );
1956 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1957 if (total <= count)
1959 *heaps++ = processHeap;
1960 LIST_FOR_EACH( ptr, &processHeap->entry )
1961 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1963 RtlLeaveCriticalSection( &processHeap->critSection );
1964 return total;