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
23 #include "wine/port.h"
30 #ifdef HAVE_VALGRIND_MEMCHECK_H
31 #include <valgrind/memcheck.h>
34 #define NONAMELESSUNION
35 #define NONAMELESSSTRUCT
37 #define WIN32_NO_STATUS
41 #include "wine/list.h"
42 #include "wine/debug.h"
43 #include "wine/server.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(heap);
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.
52 typedef struct tagARENA_INUSE
54 DWORD size; /* Block size; must be the first field */
55 DWORD magic : 24; /* Magic number */
56 DWORD unused_bytes : 8; /* Number of bytes in the block not used by user data (max value is HEAP_MIN_DATA_SIZE+HEAP_MIN_SHRINK_SIZE) */
59 typedef struct tagARENA_FREE
61 DWORD size; /* Block size; must be the first field */
62 DWORD magic; /* Magic number */
63 struct list entry; /* Entry in free list */
68 struct list entry; /* entry in heap large blocks list */
69 SIZE_T data_size; /* size of user data */
70 SIZE_T block_size; /* total size of virtual memory block */
71 DWORD pad[2]; /* padding to ensure 16-byte alignment of data */
72 DWORD size; /* fields for compatibility with normal arenas */
73 DWORD magic; /* these must remain at the end of the structure */
76 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
77 #define ARENA_FLAG_PREV_FREE 0x00000002
78 #define ARENA_SIZE_MASK (~3)
79 #define ARENA_LARGE_SIZE 0xfedcba90 /* magic value for 'size' field in large blocks */
81 /* Value for arena 'magic' field */
82 #define ARENA_INUSE_MAGIC 0x455355
83 #define ARENA_FREE_MAGIC 0x45455246
84 #define ARENA_LARGE_MAGIC 0x6752614c
86 #define ARENA_INUSE_FILLER 0x55
87 #define ARENA_FREE_FILLER 0xaa
89 /* everything is aligned on 8 byte boundaries (16 for Win64) */
90 #define ALIGNMENT (2*sizeof(void*))
91 #define LARGE_ALIGNMENT 16 /* large blocks have stricter alignment */
92 #define ARENA_OFFSET (ALIGNMENT - sizeof(ARENA_INUSE))
94 C_ASSERT( sizeof(ARENA_LARGE) % LARGE_ALIGNMENT == 0 );
96 #define ROUND_SIZE(size) ((((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1)) + ARENA_OFFSET)
98 #define QUIET 1 /* Suppress messages */
99 #define NOISY 0 /* Report all errors */
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 ROUND_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
109 /* Max size of the blocks on the free lists */
110 static const SIZE_T HEAP_freeListSizes[] =
112 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
114 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
124 typedef struct tagSUBHEAP
126 void *base; /* Base address of the sub-heap memory block */
127 SIZE_T size; /* Size of the whole sub-heap */
128 SIZE_T min_commit; /* Minimum committed size */
129 SIZE_T commitSize; /* Committed size of the sub-heap */
130 struct list entry; /* Entry in sub-heap list */
131 struct tagHEAP *heap; /* Main heap structure */
132 DWORD headerSize; /* Size of the heap header */
133 DWORD magic; /* Magic number */
136 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
138 typedef struct tagHEAP
141 DWORD flags; /* Heap flags */
142 DWORD force_flags; /* Forced heap flags for debugging */
143 SUBHEAP subheap; /* First sub-heap */
144 struct list entry; /* Entry in process heap list */
145 struct list subheap_list; /* Sub-heap list */
146 struct list large_list; /* Large blocks list */
147 SIZE_T grow_size; /* Size of next subheap for growing heap */
148 DWORD magic; /* Magic number */
149 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
150 FREE_LIST_ENTRY *freeList; /* Free lists */
153 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
155 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
156 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
158 static HEAP *processHeap; /* main process heap */
160 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
162 /* mark a block of memory as free for debugging purposes */
163 static inline void mark_block_free( void *ptr, SIZE_T size )
165 if (TRACE_ON(heap) || WARN_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
166 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
167 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
168 #elif defined( VALGRIND_MAKE_NOACCESS)
169 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
173 /* mark a block of memory as initialized for debugging purposes */
174 static inline void mark_block_initialized( void *ptr, SIZE_T size )
176 #if defined(VALGRIND_MAKE_MEM_DEFINED)
177 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
178 #elif defined(VALGRIND_MAKE_READABLE)
179 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
183 /* mark a block of memory as uninitialized for debugging purposes */
184 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
186 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
187 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
188 #elif defined(VALGRIND_MAKE_WRITABLE)
189 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
191 if (TRACE_ON(heap) || WARN_ON(heap))
193 memset( ptr, ARENA_INUSE_FILLER, size );
194 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
195 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
196 #elif defined(VALGRIND_MAKE_WRITABLE)
197 /* make it uninitialized to valgrind again */
198 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
203 /* clear contents of a block of memory */
204 static inline void clear_block( void *ptr, SIZE_T size )
206 mark_block_initialized( ptr, size );
207 memset( ptr, 0, size );
210 /* notify that a new block of memory has been allocated for debugging purposes */
211 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
213 #ifdef VALGRIND_MALLOCLIKE_BLOCK
214 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
218 /* notify that a block of memory has been freed for debugging purposes */
219 static inline void notify_free( void const *ptr )
221 #ifdef VALGRIND_FREELIKE_BLOCK
222 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
226 static void subheap_notify_free_all(SUBHEAP const *subheap)
228 #ifdef VALGRIND_FREELIKE_BLOCK
229 char const *ptr = (char const *)subheap->base + subheap->headerSize;
231 if (!RUNNING_ON_VALGRIND) return;
233 while (ptr < (char const *)subheap->base + subheap->size)
235 if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
237 ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
238 if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
239 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
243 ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
244 if (pArena->magic!=ARENA_INUSE_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
245 notify_free(pArena + 1);
246 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
252 /* locate a free list entry of the appropriate size */
253 /* size is the size of the whole block including the arena header */
254 static inline unsigned int get_freelist_index( SIZE_T size )
258 size -= sizeof(ARENA_FREE);
259 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
263 /* get the memory protection type to use for a given heap */
264 static inline ULONG get_protection_type( DWORD flags )
266 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
269 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
271 0, 0, NULL, /* will be set later */
272 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
273 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
277 /***********************************************************************
280 static void HEAP_Dump( HEAP *heap )
286 DPRINTF( "Heap: %p\n", heap );
287 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
288 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
290 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
291 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
292 DPRINTF( "%p free %08lx prev=%p next=%p\n",
293 &heap->freeList[i].arena, HEAP_freeListSizes[i],
294 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
295 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
297 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
299 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
300 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
301 subheap, subheap->base, subheap->size, subheap->commitSize );
303 DPRINTF( "\n Block Arena Stat Size Id\n" );
304 ptr = (char *)subheap->base + subheap->headerSize;
305 while (ptr < (char *)subheap->base + subheap->size)
307 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
309 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
310 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
311 pArena, pArena->magic,
312 pArena->size & ARENA_SIZE_MASK,
313 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
314 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
315 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
316 arenaSize += sizeof(ARENA_FREE);
317 freeSize += pArena->size & ARENA_SIZE_MASK;
319 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
321 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
322 DPRINTF( "%p %08x Used %08x back=%p\n",
323 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
324 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
325 arenaSize += sizeof(ARENA_INUSE);
326 usedSize += pArena->size & ARENA_SIZE_MASK;
330 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
331 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
332 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
333 arenaSize += sizeof(ARENA_INUSE);
334 usedSize += pArena->size & ARENA_SIZE_MASK;
337 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
338 subheap->size, subheap->commitSize, freeSize, usedSize,
339 arenaSize, (arenaSize * 100) / subheap->size );
344 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
347 TRACE( "Dumping entry %p\n", entry );
348 TRACE( "lpData\t\t: %p\n", entry->lpData );
349 TRACE( "cbData\t\t: %08x\n", entry->cbData);
350 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
351 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
352 TRACE( "WFlags\t\t: ");
353 if (entry->wFlags & PROCESS_HEAP_REGION)
354 TRACE( "PROCESS_HEAP_REGION ");
355 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
356 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
357 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
358 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
359 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
360 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
361 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
362 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
363 rem_flags = entry->wFlags &
364 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
365 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
366 PROCESS_HEAP_ENTRY_DDESHARE);
368 TRACE( "Unknown %08x", rem_flags);
370 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
371 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
374 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
376 if (entry->wFlags & PROCESS_HEAP_REGION)
378 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
379 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
380 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
381 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
385 /***********************************************************************
388 * Pointer to the heap
391 static HEAP *HEAP_GetPtr(
392 HANDLE heap /* [in] Handle to the heap */
394 HEAP *heapPtr = heap;
395 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
397 ERR("Invalid heap %p!\n", heap );
400 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
402 HEAP_Dump( heapPtr );
410 /***********************************************************************
411 * HEAP_InsertFreeBlock
413 * Insert a free block into the free list.
415 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
417 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
420 /* insert at end of free list, i.e. before the next free list entry */
422 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
423 list_add_before( &pEntry->arena.entry, &pArena->entry );
427 /* insert at head of free list */
428 list_add_after( &pEntry->arena.entry, &pArena->entry );
430 pArena->size |= ARENA_FLAG_FREE;
434 /***********************************************************************
436 * Find the sub-heap containing a given address.
442 static SUBHEAP *HEAP_FindSubHeap(
443 const HEAP *heap, /* [in] Heap pointer */
444 LPCVOID ptr ) /* [in] Address */
447 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
448 if ((ptr >= sub->base) &&
449 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
455 /***********************************************************************
458 * Make sure the heap storage is committed for a given size in the specified arena.
460 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
462 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
463 SIZE_T size = (char *)ptr - (char *)subheap->base;
464 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
465 if (size > subheap->size) size = subheap->size;
466 if (size <= subheap->commitSize) return TRUE;
467 size -= subheap->commitSize;
468 ptr = (char *)subheap->base + subheap->commitSize;
469 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
470 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
472 WARN("Could not commit %08lx bytes at %p for heap %p\n",
473 size, ptr, subheap->heap );
476 subheap->commitSize += size;
481 /***********************************************************************
484 * If possible, decommit the heap storage from (including) 'ptr'.
486 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
489 SIZE_T decommit_size;
490 SIZE_T size = (char *)ptr - (char *)subheap->base;
492 /* round to next block and add one full block */
493 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
494 size = max( size, subheap->min_commit );
495 if (size >= subheap->commitSize) return TRUE;
496 decommit_size = subheap->commitSize - size;
497 addr = (char *)subheap->base + size;
499 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
501 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
502 decommit_size, (char *)subheap->base + size, subheap->heap );
505 subheap->commitSize -= decommit_size;
510 /***********************************************************************
511 * HEAP_CreateFreeBlock
513 * Create a free block at a specified address. 'size' is the size of the
514 * whole block, including the new arena.
516 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
522 /* Create a free arena */
523 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
525 pFree->magic = ARENA_FREE_MAGIC;
527 /* If debugging, erase the freed block content */
529 pEnd = (char *)ptr + size;
530 if (pEnd > (char *)subheap->base + subheap->commitSize)
531 pEnd = (char *)subheap->base + subheap->commitSize;
532 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
534 /* Check if next block is free also */
536 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
537 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
539 /* Remove the next arena from the free list */
540 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
541 list_remove( &pNext->entry );
542 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
543 mark_block_free( pNext, sizeof(ARENA_FREE) );
546 /* Set the next block PREV_FREE flag and pointer */
548 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
551 DWORD *pNext = (DWORD *)((char *)ptr + size);
552 *pNext |= ARENA_FLAG_PREV_FREE;
553 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
554 *((ARENA_FREE **)pNext - 1) = pFree;
557 /* Last, insert the new block into the free list */
559 pFree->size = size - sizeof(*pFree);
560 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
564 /***********************************************************************
565 * HEAP_MakeInUseBlockFree
567 * Turn an in-use block into a free block. Can also decommit the end of
568 * the heap, and possibly even free the sub-heap altogether.
570 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
573 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
575 /* Check if we can merge with previous block */
577 if (pArena->size & ARENA_FLAG_PREV_FREE)
579 pFree = *((ARENA_FREE **)pArena - 1);
580 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
581 /* Remove it from the free list */
582 list_remove( &pFree->entry );
584 else pFree = (ARENA_FREE *)pArena;
586 /* Create a free block */
588 HEAP_CreateFreeBlock( subheap, pFree, size );
589 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
590 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
591 return; /* Not the last block, so nothing more to do */
593 /* Free the whole sub-heap if it's empty and not the original one */
595 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
596 (subheap != &subheap->heap->subheap))
599 void *addr = subheap->base;
600 /* Remove the free block from the list */
601 list_remove( &pFree->entry );
602 /* Remove the subheap from the list */
603 list_remove( &subheap->entry );
604 /* Free the memory */
606 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
610 /* Decommit the end of the heap */
612 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
616 /***********************************************************************
619 * Shrink an in-use block.
621 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
623 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
625 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
626 (pArena->size & ARENA_SIZE_MASK) - size );
627 /* assign size plus previous arena flags */
628 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
632 /* Turn off PREV_FREE flag in next block */
633 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
634 if (pNext < (char *)subheap->base + subheap->size)
635 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
640 /***********************************************************************
641 * allocate_large_block
643 static void *allocate_large_block( HEAP *heap, DWORD flags, SIZE_T size )
646 SIZE_T block_size = sizeof(*arena) + ROUND_SIZE(size);
647 LPVOID address = NULL;
649 if (block_size < size) return NULL; /* overflow */
650 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 5,
651 &block_size, MEM_COMMIT, get_protection_type( flags ) ))
653 WARN("Could not allocate block for %08lx bytes\n", size );
657 arena->data_size = size;
658 arena->block_size = block_size;
659 arena->size = ARENA_LARGE_SIZE;
660 arena->magic = ARENA_LARGE_MAGIC;
661 list_add_tail( &heap->large_list, &arena->entry );
666 /***********************************************************************
669 static void free_large_block( HEAP *heap, DWORD flags, void *ptr )
671 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
672 LPVOID address = arena;
675 list_remove( &arena->entry );
676 NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
680 /***********************************************************************
681 * realloc_large_block
683 static void *realloc_large_block( HEAP *heap, DWORD flags, void *ptr, SIZE_T size )
685 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
688 if (arena->block_size - sizeof(*arena) >= size)
690 /* FIXME: we could remap zero-pages instead */
691 if ((flags & HEAP_ZERO_MEMORY) && size > arena->data_size)
692 memset( (char *)ptr + arena->data_size, 0, size - arena->data_size );
693 arena->data_size = size;
696 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) return NULL;
697 if (!(new_ptr = allocate_large_block( heap, flags, size )))
699 WARN("Could not allocate block for %08lx bytes\n", size );
702 memcpy( new_ptr, ptr, arena->data_size );
703 free_large_block( heap, flags, ptr );
708 /***********************************************************************
711 static ARENA_LARGE *find_large_block( HEAP *heap, const void *ptr )
715 LIST_FOR_EACH_ENTRY( arena, &heap->large_list, ARENA_LARGE, entry )
716 if (ptr == arena + 1) return arena;
722 /***********************************************************************
723 * validate_large_arena
725 static BOOL validate_large_arena( HEAP *heap, const ARENA_LARGE *arena, BOOL quiet )
727 if ((ULONG_PTR)arena % getpagesize())
731 ERR( "Heap %p: invalid large arena pointer %p\n", heap, arena );
732 if (TRACE_ON(heap)) HEAP_Dump( heap );
734 else if (WARN_ON(heap))
736 WARN( "Heap %p: unaligned arena pointer %p\n", heap, arena );
737 if (TRACE_ON(heap)) HEAP_Dump( heap );
741 if (arena->size != ARENA_LARGE_SIZE || arena->magic != ARENA_LARGE_MAGIC)
745 ERR( "Heap %p: invalid large arena %p values %x/%x\n",
746 heap, arena, arena->size, arena->magic );
747 if (TRACE_ON(heap)) HEAP_Dump( heap );
749 else if (WARN_ON(heap))
751 WARN( "Heap %p: invalid large arena %p values %x/%x\n",
752 heap, arena, arena->size, arena->magic );
753 if (TRACE_ON(heap)) HEAP_Dump( heap );
761 /***********************************************************************
764 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, LPVOID address, DWORD flags,
765 SIZE_T commitSize, SIZE_T totalSize )
768 FREE_LIST_ENTRY *pEntry;
773 /* round-up sizes on a 64K boundary */
774 totalSize = (totalSize + 0xffff) & 0xffff0000;
775 commitSize = (commitSize + 0xffff) & 0xffff0000;
776 if (!commitSize) commitSize = 0x10000;
777 totalSize = min( totalSize, 0xffff0000 ); /* don't allow a heap larger than 4Gb */
778 if (totalSize < commitSize) totalSize = commitSize;
779 if (flags & HEAP_SHARED) commitSize = totalSize; /* always commit everything in a shared heap */
781 /* allocate the memory block */
782 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
783 MEM_RESERVE, get_protection_type( flags ) ))
785 WARN("Could not allocate %08lx bytes\n", totalSize );
788 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
789 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
791 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
798 /* If this is a secondary subheap, insert it into list */
801 subheap->base = address;
802 subheap->heap = heap;
803 subheap->size = totalSize;
804 subheap->min_commit = 0x10000;
805 subheap->commitSize = commitSize;
806 subheap->magic = SUBHEAP_MAGIC;
807 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
808 list_add_head( &heap->subheap_list, &subheap->entry );
812 /* If this is a primary subheap, initialize main heap */
816 heap->magic = HEAP_MAGIC;
817 heap->grow_size = max( HEAP_DEF_SIZE, totalSize );
818 list_init( &heap->subheap_list );
819 list_init( &heap->large_list );
821 subheap = &heap->subheap;
822 subheap->base = address;
823 subheap->heap = heap;
824 subheap->size = totalSize;
825 subheap->min_commit = commitSize;
826 subheap->commitSize = commitSize;
827 subheap->magic = SUBHEAP_MAGIC;
828 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
829 list_add_head( &heap->subheap_list, &subheap->entry );
831 /* Build the free lists */
833 heap->freeList = (FREE_LIST_ENTRY *)((char *)heap + subheap->headerSize);
834 subheap->headerSize += HEAP_NB_FREE_LISTS * sizeof(FREE_LIST_ENTRY);
835 list_init( &heap->freeList[0].arena.entry );
836 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
838 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
839 pEntry->arena.magic = ARENA_FREE_MAGIC;
840 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
843 /* Initialize critical section */
845 if (!processHeap) /* do it by hand to avoid memory allocations */
847 heap->critSection.DebugInfo = &process_heap_critsect_debug;
848 heap->critSection.LockCount = -1;
849 heap->critSection.RecursionCount = 0;
850 heap->critSection.OwningThread = 0;
851 heap->critSection.LockSemaphore = 0;
852 heap->critSection.SpinCount = 0;
853 process_heap_critsect_debug.CriticalSection = &heap->critSection;
857 RtlInitializeCriticalSection( &heap->critSection );
858 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
861 if (flags & HEAP_SHARED)
863 /* let's assume that only one thread at a time will try to do this */
864 HANDLE sem = heap->critSection.LockSemaphore;
865 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
867 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
868 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
869 heap->critSection.LockSemaphore = sem;
870 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
871 heap->critSection.DebugInfo = NULL;
875 /* Create the first free block */
877 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
878 subheap->size - subheap->headerSize );
884 /***********************************************************************
887 * Find a free block at least as large as the requested size, and make sure
888 * the requested size is committed.
890 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
891 SUBHEAP **ppSubHeap )
896 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
898 /* Find a suitable free list, and in it find a block large enough */
900 ptr = &pEntry->arena.entry;
901 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
903 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
904 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
905 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
906 if (arena_size >= size)
908 subheap = HEAP_FindSubHeap( heap, pArena );
909 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
910 *ppSubHeap = subheap;
915 /* If no block was found, attempt to grow the heap */
917 if (!(heap->flags & HEAP_GROWABLE))
919 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
922 /* make sure that we have a big enough size *committed* to fit another
923 * last free arena in !
924 * So just one heap struct, one first free arena which will eventually
925 * get used, and a second free arena that might get assigned all remaining
926 * free space in HEAP_ShrinkBlock() */
927 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
928 if (total_size < size) return NULL; /* overflow */
930 if ((subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
931 max( heap->grow_size, total_size ) )))
933 if (heap->grow_size < 128 * 1024 * 1024) heap->grow_size *= 2;
935 else while (!subheap) /* shrink the grow size again if we are running out of space */
937 if (heap->grow_size <= total_size || heap->grow_size <= 4 * 1024 * 1024) return NULL;
938 heap->grow_size /= 2;
939 subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
940 max( heap->grow_size, total_size ) );
943 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
944 subheap, subheap->size, heap );
946 *ppSubHeap = subheap;
947 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
951 /***********************************************************************
952 * HEAP_IsValidArenaPtr
954 * Check that the pointer is inside the range possible for arenas.
956 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
959 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
960 if (!subheap) return FALSE;
961 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
962 if (subheap != &heap->subheap) return FALSE;
963 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
964 if (ptr == &heap->freeList[i].arena) return TRUE;
969 /***********************************************************************
970 * HEAP_ValidateFreeArena
972 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
974 ARENA_FREE *prev, *next;
975 char *heapEnd = (char *)subheap->base + subheap->size;
977 /* Check for unaligned pointers */
978 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
980 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
984 /* Check magic number */
985 if (pArena->magic != ARENA_FREE_MAGIC)
987 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
990 /* Check size flags */
991 if (!(pArena->size & ARENA_FLAG_FREE) ||
992 (pArena->size & ARENA_FLAG_PREV_FREE))
994 ERR("Heap %p: bad flags %08x for free arena %p\n",
995 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
998 /* Check arena size */
999 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
1001 ERR("Heap %p: bad size %08x for free arena %p\n",
1002 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
1005 /* Check that next pointer is valid */
1006 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
1007 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
1009 ERR("Heap %p: bad next ptr %p for arena %p\n",
1010 subheap->heap, next, pArena );
1013 /* Check that next arena is free */
1014 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1016 ERR("Heap %p: next arena %p invalid for %p\n",
1017 subheap->heap, next, pArena );
1020 /* Check that prev pointer is valid */
1021 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1022 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1024 ERR("Heap %p: bad prev ptr %p for arena %p\n",
1025 subheap->heap, prev, pArena );
1028 /* Check that prev arena is free */
1029 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1031 /* this often means that the prev arena got overwritten
1032 * by a memory write before that prev arena */
1033 ERR("Heap %p: prev arena %p invalid for %p\n",
1034 subheap->heap, prev, pArena );
1037 /* Check that next block has PREV_FREE flag */
1038 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
1040 if (!(*(DWORD *)((char *)(pArena + 1) +
1041 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1043 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1044 subheap->heap, pArena );
1047 /* Check next block back pointer */
1048 if (*((ARENA_FREE **)((char *)(pArena + 1) +
1049 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
1051 ERR("Heap %p: arena %p has wrong back ptr %p\n",
1052 subheap->heap, pArena,
1053 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
1061 /***********************************************************************
1062 * HEAP_ValidateInUseArena
1064 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1066 const char *heapEnd = (const char *)subheap->base + subheap->size;
1068 /* Check for unaligned pointers */
1069 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1071 if ( quiet == NOISY )
1073 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1074 if ( TRACE_ON(heap) )
1075 HEAP_Dump( subheap->heap );
1077 else if ( WARN_ON(heap) )
1079 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1080 if ( TRACE_ON(heap) )
1081 HEAP_Dump( subheap->heap );
1086 /* Check magic number */
1087 if (pArena->magic != ARENA_INUSE_MAGIC)
1089 if (quiet == NOISY) {
1090 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1092 HEAP_Dump( subheap->heap );
1093 } else if (WARN_ON(heap)) {
1094 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1096 HEAP_Dump( subheap->heap );
1100 /* Check size flags */
1101 if (pArena->size & ARENA_FLAG_FREE)
1103 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1104 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1107 /* Check arena size */
1108 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
1110 ERR("Heap %p: bad size %08x for in-use arena %p\n",
1111 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
1114 /* Check next arena PREV_FREE flag */
1115 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
1116 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1118 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
1119 subheap->heap, pArena );
1122 /* Check prev free arena */
1123 if (pArena->size & ARENA_FLAG_PREV_FREE)
1125 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1126 /* Check prev pointer */
1127 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1129 ERR("Heap %p: bad back ptr %p for arena %p\n",
1130 subheap->heap, pPrev, pArena );
1133 /* Check that prev arena is free */
1134 if (!(pPrev->size & ARENA_FLAG_FREE) ||
1135 (pPrev->magic != ARENA_FREE_MAGIC))
1137 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1138 subheap->heap, pPrev, pArena );
1141 /* Check that prev arena is really the previous block */
1142 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1144 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1145 subheap->heap, pPrev, pArena );
1153 /***********************************************************************
1154 * HEAP_IsRealArena [Internal]
1155 * Validates a block is a valid arena.
1161 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1162 DWORD flags, /* [in] Bit flags that control access during operation */
1163 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1164 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1165 * does not complain */
1169 const ARENA_LARGE *large_arena;
1171 flags &= HEAP_NO_SERIALIZE;
1172 flags |= heapPtr->flags;
1173 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1174 if (!(flags & HEAP_NO_SERIALIZE))
1175 RtlEnterCriticalSection( &heapPtr->critSection );
1177 if (block) /* only check this single memory block */
1179 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1181 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1182 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1184 if (!(large_arena = find_large_block( heapPtr, block )))
1187 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1188 else if (WARN_ON(heap))
1189 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1193 ret = validate_large_arena( heapPtr, large_arena, quiet );
1195 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1197 if (!(flags & HEAP_NO_SERIALIZE))
1198 RtlLeaveCriticalSection( &heapPtr->critSection );
1202 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1204 char *ptr = (char *)subheap->base + subheap->headerSize;
1205 while (ptr < (char *)subheap->base + subheap->size)
1207 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1209 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1213 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1217 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1221 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1227 LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1228 if (!(ret = validate_large_arena( heapPtr, large_arena, quiet ))) break;
1230 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1235 /***********************************************************************
1236 * RtlCreateHeap (NTDLL.@)
1238 * Create a new Heap.
1241 * flags [I] HEAP_ flags from "winnt.h"
1242 * addr [I] Desired base address
1243 * totalSize [I] Total size of the heap, or 0 for a growable heap
1244 * commitSize [I] Amount of heap space to commit
1245 * unknown [I] Not yet understood
1246 * definition [I] Heap definition
1249 * Success: A HANDLE to the newly created heap.
1250 * Failure: a NULL HANDLE.
1252 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1253 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1257 /* Allocate the heap block */
1261 totalSize = HEAP_DEF_SIZE;
1262 flags |= HEAP_GROWABLE;
1265 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1267 /* link it into the per-process heap list */
1270 HEAP *heapPtr = subheap->heap;
1271 RtlEnterCriticalSection( &processHeap->critSection );
1272 list_add_head( &processHeap->entry, &heapPtr->entry );
1273 RtlLeaveCriticalSection( &processHeap->critSection );
1277 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1278 list_init( &processHeap->entry );
1281 return subheap->heap;
1285 /***********************************************************************
1286 * RtlDestroyHeap (NTDLL.@)
1288 * Destroy a Heap created with RtlCreateHeap().
1291 * heap [I] Heap to destroy.
1294 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1295 * Failure: The Heap handle, if heap is the process heap.
1297 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1299 HEAP *heapPtr = HEAP_GetPtr( heap );
1300 SUBHEAP *subheap, *next;
1301 ARENA_LARGE *arena, *arena_next;
1305 TRACE("%p\n", heap );
1306 if (!heapPtr) return heap;
1308 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1310 /* remove it from the per-process list */
1311 RtlEnterCriticalSection( &processHeap->critSection );
1312 list_remove( &heapPtr->entry );
1313 RtlLeaveCriticalSection( &processHeap->critSection );
1315 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1316 RtlDeleteCriticalSection( &heapPtr->critSection );
1318 LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1320 list_remove( &arena->entry );
1323 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1325 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1327 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1328 subheap_notify_free_all(subheap);
1329 list_remove( &subheap->entry );
1331 addr = subheap->base;
1332 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1334 subheap_notify_free_all(&heapPtr->subheap);
1336 addr = heapPtr->subheap.base;
1337 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1342 /***********************************************************************
1343 * RtlAllocateHeap (NTDLL.@)
1345 * Allocate a memory block from a Heap.
1348 * heap [I] Heap to allocate block from
1349 * flags [I] HEAP_ flags from "winnt.h"
1350 * size [I] Size of the memory block to allocate
1353 * Success: A pointer to the newly allocated block
1357 * This call does not SetLastError().
1359 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1362 ARENA_INUSE *pInUse;
1364 HEAP *heapPtr = HEAP_GetPtr( heap );
1365 SIZE_T rounded_size;
1367 /* Validate the parameters */
1369 if (!heapPtr) return NULL;
1370 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1371 flags |= heapPtr->flags;
1372 rounded_size = ROUND_SIZE(size);
1373 if (rounded_size < size) /* overflow */
1375 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1378 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1380 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1382 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1384 void *ret = allocate_large_block( heap, flags, size );
1385 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1386 if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1387 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1388 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1392 /* Locate a suitable free block */
1394 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1396 TRACE("(%p,%08x,%08lx): returning NULL\n",
1397 heap, flags, size );
1398 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1399 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1403 /* Remove the arena from the free list */
1405 list_remove( &pArena->entry );
1407 /* Build the in-use arena */
1409 pInUse = (ARENA_INUSE *)pArena;
1411 /* in-use arena is smaller than free arena,
1412 * so we have to add the difference to the size */
1413 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1414 pInUse->magic = ARENA_INUSE_MAGIC;
1416 /* Shrink the block */
1418 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1419 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1421 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1423 if (flags & HEAP_ZERO_MEMORY)
1425 clear_block( pInUse + 1, size );
1426 mark_block_uninitialized( (char *)(pInUse + 1) + size, pInUse->unused_bytes );
1429 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1431 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1433 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1438 /***********************************************************************
1439 * RtlFreeHeap (NTDLL.@)
1441 * Free a memory block allocated with RtlAllocateHeap().
1444 * heap [I] Heap that block was allocated from
1445 * flags [I] HEAP_ flags from "winnt.h"
1446 * ptr [I] Block to free
1449 * Success: TRUE, if ptr is NULL or was freed successfully.
1452 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1454 ARENA_INUSE *pInUse;
1458 /* Validate the parameters */
1460 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1462 heapPtr = HEAP_GetPtr( heap );
1465 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1469 flags &= HEAP_NO_SERIALIZE;
1470 flags |= heapPtr->flags;
1471 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1473 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1476 /* Some sanity checks */
1477 pInUse = (ARENA_INUSE *)ptr - 1;
1478 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse )))
1480 if (!find_large_block( heapPtr, ptr )) goto error;
1481 free_large_block( heapPtr, flags, ptr );
1484 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1485 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1487 /* Turn the block into a free block */
1489 HEAP_MakeInUseBlockFree( subheap, pInUse );
1492 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1493 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1497 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1498 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1499 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1504 /***********************************************************************
1505 * RtlReAllocateHeap (NTDLL.@)
1507 * Change the size of a memory block allocated with RtlAllocateHeap().
1510 * heap [I] Heap that block was allocated from
1511 * flags [I] HEAP_ flags from "winnt.h"
1512 * ptr [I] Block to resize
1513 * size [I] Size of the memory block to allocate
1516 * Success: A pointer to the resized block (which may be different).
1519 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1521 ARENA_INUSE *pArena;
1524 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1527 if (!ptr) return NULL;
1528 if (!(heapPtr = HEAP_GetPtr( heap )))
1530 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1534 /* Validate the parameters */
1536 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1537 HEAP_REALLOC_IN_PLACE_ONLY;
1538 flags |= heapPtr->flags;
1539 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1541 rounded_size = ROUND_SIZE(size);
1542 if (rounded_size < size) goto oom; /* overflow */
1543 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1545 pArena = (ARENA_INUSE *)ptr - 1;
1546 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena )))
1548 if (!find_large_block( heapPtr, ptr )) goto error;
1549 if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1551 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1554 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1555 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1557 /* Check if we need to grow the block */
1559 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1560 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1561 if (rounded_size > oldBlockSize)
1563 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1565 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1567 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) goto oom;
1568 if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1569 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1570 memcpy( ret, pArena + 1, oldActualSize );
1571 notify_free( pArena + 1 );
1572 HEAP_MakeInUseBlockFree( subheap, pArena );
1575 if ((pNext < (char *)subheap->base + subheap->size) &&
1576 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1577 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1579 /* The next block is free and large enough */
1580 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1581 list_remove( &pFree->entry );
1582 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1583 if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1584 notify_free( pArena + 1 );
1585 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1586 notify_alloc( pArena + 1, size, FALSE );
1587 /* FIXME: this is wrong as we may lose old VBits settings */
1588 mark_block_initialized( pArena + 1, oldActualSize );
1590 else /* Do it the hard way */
1593 ARENA_INUSE *pInUse;
1594 SUBHEAP *newsubheap;
1596 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1597 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1600 /* Build the in-use arena */
1602 list_remove( &pNew->entry );
1603 pInUse = (ARENA_INUSE *)pNew;
1604 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1605 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1606 pInUse->magic = ARENA_INUSE_MAGIC;
1607 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1609 mark_block_initialized( pInUse + 1, oldActualSize );
1610 notify_alloc( pInUse + 1, size, FALSE );
1611 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1613 /* Free the previous block */
1615 notify_free( pArena + 1 );
1616 HEAP_MakeInUseBlockFree( subheap, pArena );
1617 subheap = newsubheap;
1623 /* Shrink the block */
1624 notify_free( pArena + 1 );
1625 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1626 notify_alloc( pArena + 1, size, FALSE );
1627 /* FIXME: this is wrong as we may lose old VBits settings */
1628 mark_block_initialized( pArena + 1, size );
1631 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1633 /* Clear the extra bytes if needed */
1635 if (size > oldActualSize)
1637 if (flags & HEAP_ZERO_MEMORY)
1639 clear_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize );
1640 mark_block_uninitialized( (char *)(pArena + 1) + size, pArena->unused_bytes );
1643 mark_block_uninitialized( (char *)(pArena + 1) + oldActualSize,
1644 (pArena->size & ARENA_SIZE_MASK) - oldActualSize );
1647 /* Return the new arena */
1651 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1652 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1656 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1657 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1658 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1659 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1663 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1664 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1665 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1670 /***********************************************************************
1671 * RtlCompactHeap (NTDLL.@)
1673 * Compact the free space in a Heap.
1676 * heap [I] Heap that block was allocated from
1677 * flags [I] HEAP_ flags from "winnt.h"
1680 * The number of bytes compacted.
1683 * This function is a harmless stub.
1685 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1687 static BOOL reported;
1688 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1693 /***********************************************************************
1694 * RtlLockHeap (NTDLL.@)
1699 * heap [I] Heap to lock
1702 * Success: TRUE. The Heap is locked.
1703 * Failure: FALSE, if heap is invalid.
1705 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1707 HEAP *heapPtr = HEAP_GetPtr( heap );
1708 if (!heapPtr) return FALSE;
1709 RtlEnterCriticalSection( &heapPtr->critSection );
1714 /***********************************************************************
1715 * RtlUnlockHeap (NTDLL.@)
1720 * heap [I] Heap to unlock
1723 * Success: TRUE. The Heap is unlocked.
1724 * Failure: FALSE, if heap is invalid.
1726 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1728 HEAP *heapPtr = HEAP_GetPtr( heap );
1729 if (!heapPtr) return FALSE;
1730 RtlLeaveCriticalSection( &heapPtr->critSection );
1735 /***********************************************************************
1736 * RtlSizeHeap (NTDLL.@)
1738 * Get the actual size of a memory block allocated from a Heap.
1741 * heap [I] Heap that block was allocated from
1742 * flags [I] HEAP_ flags from "winnt.h"
1743 * ptr [I] Block to get the size of
1746 * Success: The size of the block.
1747 * Failure: -1, heap or ptr are invalid.
1750 * The size may be bigger than what was passed to RtlAllocateHeap().
1752 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1755 HEAP *heapPtr = HEAP_GetPtr( heap );
1759 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1762 flags &= HEAP_NO_SERIALIZE;
1763 flags |= heapPtr->flags;
1764 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1765 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1767 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1772 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1773 if (pArena->size == ARENA_LARGE_SIZE)
1775 const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
1776 ret = large_arena->data_size;
1778 else ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1780 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1782 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1787 /***********************************************************************
1788 * RtlValidateHeap (NTDLL.@)
1790 * Determine if a block is a valid allocation from a heap.
1793 * heap [I] Heap that block was allocated from
1794 * flags [I] HEAP_ flags from "winnt.h"
1795 * ptr [I] Block to check
1798 * Success: TRUE. The block was allocated from heap.
1799 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1801 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1803 HEAP *heapPtr = HEAP_GetPtr( heap );
1804 if (!heapPtr) return FALSE;
1805 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1809 /***********************************************************************
1810 * RtlWalkHeap (NTDLL.@)
1813 * The PROCESS_HEAP_ENTRY flag values seem different between this
1814 * function and HeapWalk(). To be checked.
1816 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1818 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1819 HEAP *heapPtr = HEAP_GetPtr(heap);
1820 SUBHEAP *sub, *currentheap = NULL;
1823 int region_index = 0;
1825 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1827 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1829 /* FIXME: enumerate large blocks too */
1831 /* set ptr to the next arena to be examined */
1833 if (!entry->lpData) /* first call (init) ? */
1835 TRACE("begin walking of heap %p.\n", heap);
1836 currentheap = &heapPtr->subheap;
1837 ptr = (char*)currentheap->base + currentheap->headerSize;
1841 ptr = entry->lpData;
1842 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1844 if ((ptr >= (char *)sub->base) &&
1845 (ptr < (char *)sub->base + sub->size))
1852 if (currentheap == NULL)
1854 ERR("no matching subheap found, shouldn't happen !\n");
1855 ret = STATUS_NO_MORE_ENTRIES;
1859 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1861 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1862 ptr += pArena->size & ARENA_SIZE_MASK;
1864 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1866 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1867 ptr += pArena->size & ARENA_SIZE_MASK;
1870 ptr += entry->cbData; /* point to next arena */
1872 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1873 { /* proceed with next subheap */
1874 struct list *next = list_next( &heapPtr->subheap_list, ¤theap->entry );
1876 { /* successfully finished */
1877 TRACE("end reached.\n");
1878 ret = STATUS_NO_MORE_ENTRIES;
1881 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1882 ptr = (char *)currentheap->base + currentheap->headerSize;
1887 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1889 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1891 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1893 entry->lpData = pArena + 1;
1894 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1895 entry->cbOverhead = sizeof(ARENA_FREE);
1896 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1900 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1902 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1904 entry->lpData = pArena + 1;
1905 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1906 entry->cbOverhead = sizeof(ARENA_INUSE);
1907 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1908 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1909 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1912 entry->iRegionIndex = region_index;
1914 /* first element of heap ? */
1915 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1917 entry->wFlags |= PROCESS_HEAP_REGION;
1918 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1919 entry->u.Region.dwUnCommittedSize =
1920 currentheap->size - currentheap->commitSize;
1921 entry->u.Region.lpFirstBlock = /* first valid block */
1922 (char *)currentheap->base + currentheap->headerSize;
1923 entry->u.Region.lpLastBlock = /* first invalid block */
1924 (char *)currentheap->base + currentheap->size;
1926 ret = STATUS_SUCCESS;
1927 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1930 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1935 /***********************************************************************
1936 * RtlGetProcessHeaps (NTDLL.@)
1938 * Get the Heaps belonging to the current process.
1941 * count [I] size of heaps
1942 * heaps [O] Destination array for heap HANDLE's
1945 * Success: The number of Heaps allocated by the process.
1948 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1950 ULONG total = 1; /* main heap */
1953 RtlEnterCriticalSection( &processHeap->critSection );
1954 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1957 *heaps++ = processHeap;
1958 LIST_FOR_EACH( ptr, &processHeap->entry )
1959 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1961 RtlLeaveCriticalSection( &processHeap->critSection );
1965 /***********************************************************************
1966 * RtlQueryHeapInformation (NTDLL.@)
1968 NTSTATUS WINAPI RtlQueryHeapInformation( HANDLE heap, HEAP_INFORMATION_CLASS info_class,
1969 PVOID info, SIZE_T size_in, PSIZE_T size_out)
1973 case HeapCompatibilityInformation:
1974 if (size_out) *size_out = sizeof(ULONG);
1976 if (size_in < sizeof(ULONG))
1977 return STATUS_BUFFER_TOO_SMALL;
1979 *(ULONG *)info = 0; /* standard heap */
1980 return STATUS_SUCCESS;
1983 FIXME("Unknown heap information class %u\n", info_class);
1984 return STATUS_INVALID_INFO_CLASS;