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 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
53 * that there is no unaligned accesses to structure fields.
56 typedef struct tagARENA_INUSE
58 DWORD size; /* Block size; must be the first field */
59 DWORD magic : 24; /* Magic number */
60 DWORD unused_bytes : 8; /* Number of bytes in the block not used by user data (max value is HEAP_MIN_DATA_SIZE+HEAP_MIN_SHRINK_SIZE) */
63 typedef struct tagARENA_FREE
65 DWORD size; /* Block size; must be the first field */
66 DWORD magic; /* Magic number */
67 struct list entry; /* Entry in free list */
72 struct list entry; /* entry in heap large blocks list */
73 SIZE_T data_size; /* size of user data */
74 SIZE_T block_size; /* total size of virtual memory block */
75 DWORD pad[2]; /* padding to ensure 16-byte alignment of data */
76 DWORD size; /* fields for compatibility with normal arenas */
77 DWORD magic; /* these must remain at the end of the structure */
80 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
81 #define ARENA_FLAG_PREV_FREE 0x00000002
82 #define ARENA_SIZE_MASK (~3)
83 #define ARENA_LARGE_SIZE 0xfedcba90 /* magic value for 'size' field in large blocks */
85 /* Value for arena 'magic' field */
86 #define ARENA_INUSE_MAGIC 0x455355
87 #define ARENA_FREE_MAGIC 0x45455246
88 #define ARENA_LARGE_MAGIC 0x6752614c
90 #define ARENA_INUSE_FILLER 0x55
91 #define ARENA_FREE_FILLER 0xaa
93 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
94 #define LARGE_ALIGNMENT 16 /* large blocks have stricter alignment */
96 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
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 (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]))
123 typedef struct tagSUBHEAP
125 void *base; /* Base address of the sub-heap memory block */
126 SIZE_T size; /* Size of the whole sub-heap */
127 SIZE_T commitSize; /* Committed size of the sub-heap */
128 struct list entry; /* Entry in sub-heap list */
129 struct tagHEAP *heap; /* Main heap structure */
130 DWORD headerSize; /* Size of the heap header */
131 DWORD magic; /* Magic number */
134 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
136 typedef struct tagHEAP
139 DWORD flags; /* Heap flags */
140 DWORD force_flags; /* Forced heap flags for debugging */
141 SUBHEAP subheap; /* First sub-heap */
142 struct list entry; /* Entry in process heap list */
143 struct list subheap_list; /* Sub-heap list */
144 struct list large_list; /* Large blocks list */
145 SIZE_T grow_size; /* Size of next subheap for growing heap */
146 DWORD magic; /* Magic number */
147 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
148 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS] DECLSPEC_ALIGN(8); /* Free lists */
151 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
153 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
154 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
156 static HEAP *processHeap; /* main process heap */
158 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
160 /* mark a block of memory as free for debugging purposes */
161 static inline void mark_block_free( void *ptr, SIZE_T size )
163 if (TRACE_ON(heap) || WARN_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
164 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
165 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
166 #elif defined( VALGRIND_MAKE_NOACCESS)
167 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
171 /* mark a block of memory as initialized for debugging purposes */
172 static inline void mark_block_initialized( void *ptr, SIZE_T size )
174 #if defined(VALGRIND_MAKE_MEM_DEFINED)
175 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
176 #elif defined(VALGRIND_MAKE_READABLE)
177 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
181 /* mark a block of memory as uninitialized for debugging purposes */
182 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
184 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
185 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
186 #elif defined(VALGRIND_MAKE_WRITABLE)
187 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
189 if (TRACE_ON(heap) || WARN_ON(heap))
191 memset( ptr, ARENA_INUSE_FILLER, size );
192 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
193 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
194 #elif defined(VALGRIND_MAKE_WRITABLE)
195 /* make it uninitialized to valgrind again */
196 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
201 /* clear contents of a block of memory */
202 static inline void clear_block( void *ptr, SIZE_T size )
204 mark_block_initialized( ptr, size );
205 memset( ptr, 0, size );
208 /* notify that a new block of memory has been allocated for debugging purposes */
209 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
211 #ifdef VALGRIND_MALLOCLIKE_BLOCK
212 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
216 /* notify that a block of memory has been freed for debugging purposes */
217 static inline void notify_free( void const *ptr )
219 #ifdef VALGRIND_FREELIKE_BLOCK
220 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
224 static void subheap_notify_free_all(SUBHEAP const *subheap)
226 #ifdef VALGRIND_FREELIKE_BLOCK
227 char const *ptr = (char const *)subheap->base + subheap->headerSize;
229 if (!RUNNING_ON_VALGRIND) return;
231 while (ptr < (char const *)subheap->base + subheap->size)
233 if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
235 ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
236 if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
237 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
241 ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
242 if (pArena->magic!=ARENA_INUSE_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
243 notify_free(pArena + 1);
244 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
250 /* locate a free list entry of the appropriate size */
251 /* size is the size of the whole block including the arena header */
252 static inline unsigned int get_freelist_index( SIZE_T size )
256 size -= sizeof(ARENA_FREE);
257 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
261 /* get the memory protection type to use for a given heap */
262 static inline ULONG get_protection_type( DWORD flags )
264 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
267 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
269 0, 0, NULL, /* will be set later */
270 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
271 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
275 /***********************************************************************
278 static void HEAP_Dump( HEAP *heap )
284 DPRINTF( "Heap: %p\n", heap );
285 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
286 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
288 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
289 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
290 DPRINTF( "%p free %08lx prev=%p next=%p\n",
291 &heap->freeList[i].arena, HEAP_freeListSizes[i],
292 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
293 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
295 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
297 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
298 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
299 subheap, subheap->base, subheap->size, subheap->commitSize );
301 DPRINTF( "\n Block Arena Stat Size Id\n" );
302 ptr = (char *)subheap->base + subheap->headerSize;
303 while (ptr < (char *)subheap->base + subheap->size)
305 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
307 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
308 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
309 pArena, pArena->magic,
310 pArena->size & ARENA_SIZE_MASK,
311 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
312 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
313 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
314 arenaSize += sizeof(ARENA_FREE);
315 freeSize += pArena->size & ARENA_SIZE_MASK;
317 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
319 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
320 DPRINTF( "%p %08x Used %08x back=%p\n",
321 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
322 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
323 arenaSize += sizeof(ARENA_INUSE);
324 usedSize += pArena->size & ARENA_SIZE_MASK;
328 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
329 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
330 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
331 arenaSize += sizeof(ARENA_INUSE);
332 usedSize += pArena->size & ARENA_SIZE_MASK;
335 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
336 subheap->size, subheap->commitSize, freeSize, usedSize,
337 arenaSize, (arenaSize * 100) / subheap->size );
342 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
345 TRACE( "Dumping entry %p\n", entry );
346 TRACE( "lpData\t\t: %p\n", entry->lpData );
347 TRACE( "cbData\t\t: %08x\n", entry->cbData);
348 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
349 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
350 TRACE( "WFlags\t\t: ");
351 if (entry->wFlags & PROCESS_HEAP_REGION)
352 TRACE( "PROCESS_HEAP_REGION ");
353 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
354 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
355 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
356 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
357 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
358 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
359 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
360 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
361 rem_flags = entry->wFlags &
362 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
363 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
364 PROCESS_HEAP_ENTRY_DDESHARE);
366 TRACE( "Unknown %08x", rem_flags);
368 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
369 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
372 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
374 if (entry->wFlags & PROCESS_HEAP_REGION)
376 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
377 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
378 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
379 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
383 /***********************************************************************
386 * Pointer to the heap
389 static HEAP *HEAP_GetPtr(
390 HANDLE heap /* [in] Handle to the heap */
392 HEAP *heapPtr = (HEAP *)heap;
393 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
395 ERR("Invalid heap %p!\n", heap );
398 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
400 HEAP_Dump( heapPtr );
408 /***********************************************************************
409 * HEAP_InsertFreeBlock
411 * Insert a free block into the free list.
413 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
415 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
418 /* insert at end of free list, i.e. before the next free list entry */
420 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
421 list_add_before( &pEntry->arena.entry, &pArena->entry );
425 /* insert at head of free list */
426 list_add_after( &pEntry->arena.entry, &pArena->entry );
428 pArena->size |= ARENA_FLAG_FREE;
432 /***********************************************************************
434 * Find the sub-heap containing a given address.
440 static SUBHEAP *HEAP_FindSubHeap(
441 const HEAP *heap, /* [in] Heap pointer */
442 LPCVOID ptr ) /* [in] Address */
445 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
446 if (((const char *)ptr >= (const char *)sub->base) &&
447 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
453 /***********************************************************************
456 * Make sure the heap storage is committed for a given size in the specified arena.
458 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
460 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
461 SIZE_T size = (char *)ptr - (char *)subheap->base;
462 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
463 if (size > subheap->size) size = subheap->size;
464 if (size <= subheap->commitSize) return TRUE;
465 size -= subheap->commitSize;
466 ptr = (char *)subheap->base + subheap->commitSize;
467 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
468 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
470 WARN("Could not commit %08lx bytes at %p for heap %p\n",
471 size, ptr, subheap->heap );
474 subheap->commitSize += size;
479 /***********************************************************************
482 * If possible, decommit the heap storage from (including) 'ptr'.
484 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
487 SIZE_T decommit_size;
488 SIZE_T size = (char *)ptr - (char *)subheap->base;
490 /* round to next block and add one full block */
491 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
492 if (size >= subheap->commitSize) return TRUE;
493 decommit_size = subheap->commitSize - size;
494 addr = (char *)subheap->base + size;
496 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
498 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
499 decommit_size, (char *)subheap->base + size, subheap->heap );
502 subheap->commitSize -= decommit_size;
507 /***********************************************************************
508 * HEAP_CreateFreeBlock
510 * Create a free block at a specified address. 'size' is the size of the
511 * whole block, including the new arena.
513 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
519 /* Create a free arena */
520 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
521 pFree = (ARENA_FREE *)ptr;
522 pFree->magic = ARENA_FREE_MAGIC;
524 /* If debugging, erase the freed block content */
526 pEnd = (char *)ptr + size;
527 if (pEnd > (char *)subheap->base + subheap->commitSize)
528 pEnd = (char *)subheap->base + subheap->commitSize;
529 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
531 /* Check if next block is free also */
533 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
534 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
536 /* Remove the next arena from the free list */
537 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
538 list_remove( &pNext->entry );
539 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
540 mark_block_free( pNext, sizeof(ARENA_FREE) );
543 /* Set the next block PREV_FREE flag and pointer */
545 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
548 DWORD *pNext = (DWORD *)((char *)ptr + size);
549 *pNext |= ARENA_FLAG_PREV_FREE;
550 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
551 *((ARENA_FREE **)pNext - 1) = pFree;
554 /* Last, insert the new block into the free list */
556 pFree->size = size - sizeof(*pFree);
557 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
561 /***********************************************************************
562 * HEAP_MakeInUseBlockFree
564 * Turn an in-use block into a free block. Can also decommit the end of
565 * the heap, and possibly even free the sub-heap altogether.
567 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
570 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
572 /* Check if we can merge with previous block */
574 if (pArena->size & ARENA_FLAG_PREV_FREE)
576 pFree = *((ARENA_FREE **)pArena - 1);
577 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
578 /* Remove it from the free list */
579 list_remove( &pFree->entry );
581 else pFree = (ARENA_FREE *)pArena;
583 /* Create a free block */
585 HEAP_CreateFreeBlock( subheap, pFree, size );
586 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
587 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
588 return; /* Not the last block, so nothing more to do */
590 /* Free the whole sub-heap if it's empty and not the original one */
592 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
593 (subheap != &subheap->heap->subheap))
596 void *addr = subheap->base;
597 /* Remove the free block from the list */
598 list_remove( &pFree->entry );
599 /* Remove the subheap from the list */
600 list_remove( &subheap->entry );
601 /* Free the memory */
603 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
607 /* Decommit the end of the heap */
609 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
613 /***********************************************************************
616 * Shrink an in-use block.
618 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
620 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
622 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
623 (pArena->size & ARENA_SIZE_MASK) - size );
624 /* assign size plus previous arena flags */
625 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
629 /* Turn off PREV_FREE flag in next block */
630 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
631 if (pNext < (char *)subheap->base + subheap->size)
632 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
637 /***********************************************************************
638 * allocate_large_block
640 static void *allocate_large_block( HEAP *heap, DWORD flags, SIZE_T size )
643 SIZE_T block_size = sizeof(*arena) + ROUND_SIZE(size);
644 LPVOID address = NULL;
646 if (block_size < size) return NULL; /* overflow */
647 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
648 &block_size, MEM_COMMIT, get_protection_type( flags ) ))
650 WARN("Could not allocate block for %08lx bytes\n", size );
654 arena->data_size = size;
655 arena->block_size = block_size;
656 arena->size = ARENA_LARGE_SIZE;
657 arena->magic = ARENA_LARGE_MAGIC;
658 list_add_tail( &heap->large_list, &arena->entry );
663 /***********************************************************************
666 static void free_large_block( HEAP *heap, DWORD flags, void *ptr )
668 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
669 LPVOID address = arena;
672 list_remove( &arena->entry );
673 NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
677 /***********************************************************************
678 * realloc_large_block
680 static void *realloc_large_block( HEAP *heap, DWORD flags, void *ptr, SIZE_T size )
682 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
685 if (arena->block_size - sizeof(*arena) >= size)
687 /* FIXME: we could remap zero-pages instead */
688 if ((flags & HEAP_ZERO_MEMORY) && size > arena->data_size)
689 memset( (char *)ptr + arena->data_size, 0, size - arena->data_size );
690 arena->data_size = size;
693 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) return NULL;
694 if (!(new_ptr = allocate_large_block( heap, flags, size )))
696 WARN("Could not allocate block for %08lx bytes\n", size );
699 memcpy( new_ptr, ptr, arena->data_size );
700 free_large_block( heap, flags, ptr );
705 /***********************************************************************
708 static ARENA_LARGE *find_large_block( HEAP *heap, const void *ptr )
712 LIST_FOR_EACH_ENTRY( arena, &heap->large_list, ARENA_LARGE, entry )
713 if (ptr == (const void *)(arena + 1)) return arena;
719 /***********************************************************************
720 * validate_large_arena
722 static BOOL validate_large_arena( HEAP *heap, const ARENA_LARGE *arena, BOOL quiet )
724 if ((ULONG_PTR)arena % getpagesize())
728 ERR( "Heap %p: invalid large arena pointer %p\n", heap, arena );
729 if (TRACE_ON(heap)) HEAP_Dump( heap );
731 else if (WARN_ON(heap))
733 WARN( "Heap %p: unaligned arena pointer %p\n", heap, arena );
734 if (TRACE_ON(heap)) HEAP_Dump( heap );
738 if (arena->size != ARENA_LARGE_SIZE || arena->magic != ARENA_LARGE_MAGIC)
742 ERR( "Heap %p: invalid large arena %p values %x/%x\n",
743 heap, arena, arena->size, arena->magic );
744 if (TRACE_ON(heap)) HEAP_Dump( heap );
746 else if (WARN_ON(heap))
748 WARN( "Heap %p: invalid large arena %p values %x/%x\n",
749 heap, arena, arena->size, arena->magic );
750 if (TRACE_ON(heap)) HEAP_Dump( heap );
758 /***********************************************************************
761 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, LPVOID address, DWORD flags,
762 SIZE_T commitSize, SIZE_T totalSize )
765 FREE_LIST_ENTRY *pEntry;
770 /* round-up sizes on a 64K boundary */
771 totalSize = (totalSize + 0xffff) & 0xffff0000;
772 commitSize = (commitSize + 0xffff) & 0xffff0000;
773 if (!commitSize) commitSize = 0x10000;
774 if (totalSize < commitSize) totalSize = commitSize;
775 if (flags & HEAP_SHARED) commitSize = totalSize; /* always commit everything in a shared heap */
777 /* allocate the memory block */
778 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
779 MEM_RESERVE, get_protection_type( flags ) ))
781 WARN("Could not allocate %08lx bytes\n", totalSize );
784 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
785 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
787 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
794 /* If this is a secondary subheap, insert it into list */
796 subheap = (SUBHEAP *)address;
797 subheap->base = address;
798 subheap->heap = heap;
799 subheap->size = totalSize;
800 subheap->commitSize = commitSize;
801 subheap->magic = SUBHEAP_MAGIC;
802 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
803 list_add_head( &heap->subheap_list, &subheap->entry );
807 /* If this is a primary subheap, initialize main heap */
809 heap = (HEAP *)address;
811 heap->magic = HEAP_MAGIC;
812 heap->grow_size = max( HEAP_DEF_SIZE, totalSize );
813 list_init( &heap->subheap_list );
814 list_init( &heap->large_list );
816 subheap = &heap->subheap;
817 subheap->base = address;
818 subheap->heap = heap;
819 subheap->size = totalSize;
820 subheap->commitSize = commitSize;
821 subheap->magic = SUBHEAP_MAGIC;
822 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
823 list_add_head( &heap->subheap_list, &subheap->entry );
825 /* Build the free lists */
827 list_init( &heap->freeList[0].arena.entry );
828 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
830 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
831 pEntry->arena.magic = ARENA_FREE_MAGIC;
832 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
835 /* Initialize critical section */
837 if (!processHeap) /* do it by hand to avoid memory allocations */
839 heap->critSection.DebugInfo = &process_heap_critsect_debug;
840 heap->critSection.LockCount = -1;
841 heap->critSection.RecursionCount = 0;
842 heap->critSection.OwningThread = 0;
843 heap->critSection.LockSemaphore = 0;
844 heap->critSection.SpinCount = 0;
845 process_heap_critsect_debug.CriticalSection = &heap->critSection;
849 RtlInitializeCriticalSection( &heap->critSection );
850 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
853 if (flags & HEAP_SHARED)
855 /* let's assume that only one thread at a time will try to do this */
856 HANDLE sem = heap->critSection.LockSemaphore;
857 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
859 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
860 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
861 heap->critSection.LockSemaphore = sem;
862 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
863 heap->critSection.DebugInfo = NULL;
867 /* Create the first free block */
869 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
870 subheap->size - subheap->headerSize );
876 /***********************************************************************
879 * Find a free block at least as large as the requested size, and make sure
880 * the requested size is committed.
882 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
883 SUBHEAP **ppSubHeap )
888 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
890 /* Find a suitable free list, and in it find a block large enough */
892 ptr = &pEntry->arena.entry;
893 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
895 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
896 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
897 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
898 if (arena_size >= size)
900 subheap = HEAP_FindSubHeap( heap, pArena );
901 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
902 *ppSubHeap = subheap;
907 /* If no block was found, attempt to grow the heap */
909 if (!(heap->flags & HEAP_GROWABLE))
911 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
914 /* make sure that we have a big enough size *committed* to fit another
915 * last free arena in !
916 * So just one heap struct, one first free arena which will eventually
917 * get used, and a second free arena that might get assigned all remaining
918 * free space in HEAP_ShrinkBlock() */
919 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
920 if (total_size < size) return NULL; /* overflow */
922 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
923 max( heap->grow_size, total_size ) )))
926 if (heap->grow_size < 128 * 1024 * 1024) heap->grow_size *= 2;
928 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
929 subheap, subheap->size, heap );
931 *ppSubHeap = subheap;
932 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
936 /***********************************************************************
937 * HEAP_IsValidArenaPtr
939 * Check that the pointer is inside the range possible for arenas.
941 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
944 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
945 if (!subheap) return FALSE;
946 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
947 if (subheap != &heap->subheap) return FALSE;
948 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
949 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
954 /***********************************************************************
955 * HEAP_ValidateFreeArena
957 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
959 ARENA_FREE *prev, *next;
960 char *heapEnd = (char *)subheap->base + subheap->size;
962 /* Check for unaligned pointers */
963 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
965 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
969 /* Check magic number */
970 if (pArena->magic != ARENA_FREE_MAGIC)
972 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
975 /* Check size flags */
976 if (!(pArena->size & ARENA_FLAG_FREE) ||
977 (pArena->size & ARENA_FLAG_PREV_FREE))
979 ERR("Heap %p: bad flags %08x for free arena %p\n",
980 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
983 /* Check arena size */
984 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
986 ERR("Heap %p: bad size %08x for free arena %p\n",
987 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
990 /* Check that next pointer is valid */
991 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
992 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
994 ERR("Heap %p: bad next ptr %p for arena %p\n",
995 subheap->heap, next, pArena );
998 /* Check that next arena is free */
999 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1001 ERR("Heap %p: next arena %p invalid for %p\n",
1002 subheap->heap, next, pArena );
1005 /* Check that prev pointer is valid */
1006 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1007 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1009 ERR("Heap %p: bad prev ptr %p for arena %p\n",
1010 subheap->heap, prev, pArena );
1013 /* Check that prev arena is free */
1014 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1016 /* this often means that the prev arena got overwritten
1017 * by a memory write before that prev arena */
1018 ERR("Heap %p: prev arena %p invalid for %p\n",
1019 subheap->heap, prev, pArena );
1022 /* Check that next block has PREV_FREE flag */
1023 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
1025 if (!(*(DWORD *)((char *)(pArena + 1) +
1026 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1028 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1029 subheap->heap, pArena );
1032 /* Check next block back pointer */
1033 if (*((ARENA_FREE **)((char *)(pArena + 1) +
1034 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
1036 ERR("Heap %p: arena %p has wrong back ptr %p\n",
1037 subheap->heap, pArena,
1038 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
1046 /***********************************************************************
1047 * HEAP_ValidateInUseArena
1049 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1051 const char *heapEnd = (const char *)subheap->base + subheap->size;
1053 /* Check for unaligned pointers */
1054 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
1056 if ( quiet == NOISY )
1058 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1059 if ( TRACE_ON(heap) )
1060 HEAP_Dump( subheap->heap );
1062 else if ( WARN_ON(heap) )
1064 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1065 if ( TRACE_ON(heap) )
1066 HEAP_Dump( subheap->heap );
1071 /* Check magic number */
1072 if (pArena->magic != ARENA_INUSE_MAGIC)
1074 if (quiet == NOISY) {
1075 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1077 HEAP_Dump( subheap->heap );
1078 } else if (WARN_ON(heap)) {
1079 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1081 HEAP_Dump( subheap->heap );
1085 /* Check size flags */
1086 if (pArena->size & ARENA_FLAG_FREE)
1088 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1089 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1092 /* Check arena size */
1093 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
1095 ERR("Heap %p: bad size %08x for in-use arena %p\n",
1096 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
1099 /* Check next arena PREV_FREE flag */
1100 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
1101 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1103 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
1104 subheap->heap, pArena );
1107 /* Check prev free arena */
1108 if (pArena->size & ARENA_FLAG_PREV_FREE)
1110 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1111 /* Check prev pointer */
1112 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1114 ERR("Heap %p: bad back ptr %p for arena %p\n",
1115 subheap->heap, pPrev, pArena );
1118 /* Check that prev arena is free */
1119 if (!(pPrev->size & ARENA_FLAG_FREE) ||
1120 (pPrev->magic != ARENA_FREE_MAGIC))
1122 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1123 subheap->heap, pPrev, pArena );
1126 /* Check that prev arena is really the previous block */
1127 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1129 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1130 subheap->heap, pPrev, pArena );
1138 /***********************************************************************
1139 * HEAP_IsRealArena [Internal]
1140 * Validates a block is a valid arena.
1146 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1147 DWORD flags, /* [in] Bit flags that control access during operation */
1148 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1149 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1150 * does not complain */
1154 const ARENA_LARGE *large_arena;
1156 flags &= HEAP_NO_SERIALIZE;
1157 flags |= heapPtr->flags;
1158 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1159 if (!(flags & HEAP_NO_SERIALIZE))
1160 RtlEnterCriticalSection( &heapPtr->critSection );
1162 if (block) /* only check this single memory block */
1164 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1166 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1167 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1169 if (!(large_arena = find_large_block( heapPtr, block )))
1172 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1173 else if (WARN_ON(heap))
1174 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1178 ret = validate_large_arena( heapPtr, large_arena, quiet );
1180 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1182 if (!(flags & HEAP_NO_SERIALIZE))
1183 RtlLeaveCriticalSection( &heapPtr->critSection );
1187 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1189 char *ptr = (char *)subheap->base + subheap->headerSize;
1190 while (ptr < (char *)subheap->base + subheap->size)
1192 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1194 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1198 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1202 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1206 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1212 LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1213 if (!(ret = validate_large_arena( heapPtr, large_arena, quiet ))) break;
1215 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1220 /***********************************************************************
1221 * RtlCreateHeap (NTDLL.@)
1223 * Create a new Heap.
1226 * flags [I] HEAP_ flags from "winnt.h"
1227 * addr [I] Desired base address
1228 * totalSize [I] Total size of the heap, or 0 for a growable heap
1229 * commitSize [I] Amount of heap space to commit
1230 * unknown [I] Not yet understood
1231 * definition [I] Heap definition
1234 * Success: A HANDLE to the newly created heap.
1235 * Failure: a NULL HANDLE.
1237 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1238 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1242 /* Allocate the heap block */
1246 totalSize = HEAP_DEF_SIZE;
1247 flags |= HEAP_GROWABLE;
1250 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1252 /* link it into the per-process heap list */
1255 HEAP *heapPtr = subheap->heap;
1256 RtlEnterCriticalSection( &processHeap->critSection );
1257 list_add_head( &processHeap->entry, &heapPtr->entry );
1258 RtlLeaveCriticalSection( &processHeap->critSection );
1262 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1263 list_init( &processHeap->entry );
1264 /* make sure structure alignment is correct */
1265 assert( (ULONG_PTR)processHeap->freeList % ALIGNMENT == 0 );
1266 assert( sizeof(ARENA_LARGE) % LARGE_ALIGNMENT == 0 );
1269 return (HANDLE)subheap->heap;
1273 /***********************************************************************
1274 * RtlDestroyHeap (NTDLL.@)
1276 * Destroy a Heap created with RtlCreateHeap().
1279 * heap [I] Heap to destroy.
1282 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1283 * Failure: The Heap handle, if heap is the process heap.
1285 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1287 HEAP *heapPtr = HEAP_GetPtr( heap );
1288 SUBHEAP *subheap, *next;
1289 ARENA_LARGE *arena, *arena_next;
1293 TRACE("%p\n", heap );
1294 if (!heapPtr) return heap;
1296 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1298 /* remove it from the per-process list */
1299 RtlEnterCriticalSection( &processHeap->critSection );
1300 list_remove( &heapPtr->entry );
1301 RtlLeaveCriticalSection( &processHeap->critSection );
1303 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1304 RtlDeleteCriticalSection( &heapPtr->critSection );
1306 LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1308 list_remove( &arena->entry );
1311 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1313 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1315 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1316 subheap_notify_free_all(subheap);
1317 list_remove( &subheap->entry );
1319 addr = subheap->base;
1320 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1322 subheap_notify_free_all(&heapPtr->subheap);
1324 addr = heapPtr->subheap.base;
1325 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1330 /***********************************************************************
1331 * RtlAllocateHeap (NTDLL.@)
1333 * Allocate a memory block from a Heap.
1336 * heap [I] Heap to allocate block from
1337 * flags [I] HEAP_ flags from "winnt.h"
1338 * size [I] Size of the memory block to allocate
1341 * Success: A pointer to the newly allocated block
1345 * This call does not SetLastError().
1347 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1350 ARENA_INUSE *pInUse;
1352 HEAP *heapPtr = HEAP_GetPtr( heap );
1353 SIZE_T rounded_size;
1355 /* Validate the parameters */
1357 if (!heapPtr) return NULL;
1358 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1359 flags |= heapPtr->flags;
1360 rounded_size = ROUND_SIZE(size);
1361 if (rounded_size < size) /* overflow */
1363 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1366 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1368 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1370 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1372 void *ret = allocate_large_block( heap, flags, size );
1373 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1374 if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1375 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1379 /* Locate a suitable free block */
1381 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1383 TRACE("(%p,%08x,%08lx): returning NULL\n",
1384 heap, flags, size );
1385 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1386 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1390 /* Remove the arena from the free list */
1392 list_remove( &pArena->entry );
1394 /* Build the in-use arena */
1396 pInUse = (ARENA_INUSE *)pArena;
1398 /* in-use arena is smaller than free arena,
1399 * so we have to add the difference to the size */
1400 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1401 pInUse->magic = ARENA_INUSE_MAGIC;
1403 /* Shrink the block */
1405 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1406 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1408 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1410 if (flags & HEAP_ZERO_MEMORY)
1412 clear_block( pInUse + 1, size );
1413 mark_block_uninitialized( (char *)(pInUse + 1) + size, pInUse->unused_bytes );
1416 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1418 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1420 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1421 return (LPVOID)(pInUse + 1);
1425 /***********************************************************************
1426 * RtlFreeHeap (NTDLL.@)
1428 * Free a memory block allocated with RtlAllocateHeap().
1431 * heap [I] Heap that block was allocated from
1432 * flags [I] HEAP_ flags from "winnt.h"
1433 * ptr [I] Block to free
1436 * Success: TRUE, if ptr is NULL or was freed successfully.
1439 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1441 ARENA_INUSE *pInUse;
1445 /* Validate the parameters */
1447 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1449 heapPtr = HEAP_GetPtr( heap );
1452 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1456 flags &= HEAP_NO_SERIALIZE;
1457 flags |= heapPtr->flags;
1458 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1460 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1463 /* Some sanity checks */
1464 pInUse = (ARENA_INUSE *)ptr - 1;
1465 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse )))
1467 if (!find_large_block( heapPtr, ptr )) goto error;
1468 free_large_block( heapPtr, flags, ptr );
1471 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1472 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1474 /* Turn the block into a free block */
1476 HEAP_MakeInUseBlockFree( subheap, pInUse );
1479 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1480 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1484 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1485 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1486 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1491 /***********************************************************************
1492 * RtlReAllocateHeap (NTDLL.@)
1494 * Change the size of a memory block allocated with RtlAllocateHeap().
1497 * heap [I] Heap that block was allocated from
1498 * flags [I] HEAP_ flags from "winnt.h"
1499 * ptr [I] Block to resize
1500 * size [I] Size of the memory block to allocate
1503 * Success: A pointer to the resized block (which may be different).
1506 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1508 ARENA_INUSE *pArena;
1511 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1514 if (!ptr) return NULL;
1515 if (!(heapPtr = HEAP_GetPtr( heap )))
1517 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1521 /* Validate the parameters */
1523 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1524 HEAP_REALLOC_IN_PLACE_ONLY;
1525 flags |= heapPtr->flags;
1526 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1528 rounded_size = ROUND_SIZE(size);
1529 if (rounded_size < size) goto oom; /* overflow */
1530 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1532 pArena = (ARENA_INUSE *)ptr - 1;
1533 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena )))
1535 if (!find_large_block( heapPtr, ptr )) goto error;
1536 if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1539 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1540 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1542 /* Check if we need to grow the block */
1544 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1545 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1546 if (rounded_size > oldBlockSize)
1548 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1550 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1552 if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1553 memcpy( ret, pArena + 1, oldActualSize );
1556 if ((pNext < (char *)subheap->base + subheap->size) &&
1557 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1558 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1560 /* The next block is free and large enough */
1561 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1562 list_remove( &pFree->entry );
1563 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1564 if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1565 notify_free( pArena + 1 );
1566 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1567 notify_alloc( pArena + 1, size, FALSE );
1568 /* FIXME: this is wrong as we may lose old VBits settings */
1569 mark_block_initialized( pArena + 1, oldActualSize );
1571 else /* Do it the hard way */
1574 ARENA_INUSE *pInUse;
1575 SUBHEAP *newsubheap;
1577 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1578 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1581 /* Build the in-use arena */
1583 list_remove( &pNew->entry );
1584 pInUse = (ARENA_INUSE *)pNew;
1585 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1586 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1587 pInUse->magic = ARENA_INUSE_MAGIC;
1588 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1590 mark_block_initialized( pInUse + 1, oldActualSize );
1591 notify_alloc( pInUse + 1, size, FALSE );
1592 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1594 /* Free the previous block */
1596 notify_free( pArena + 1 );
1597 HEAP_MakeInUseBlockFree( subheap, pArena );
1598 subheap = newsubheap;
1604 /* Shrink the block */
1605 notify_free( pArena + 1 );
1606 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1607 notify_alloc( pArena + 1, size, FALSE );
1608 /* FIXME: this is wrong as we may lose old VBits settings */
1609 mark_block_initialized( pArena + 1, size );
1612 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1614 /* Clear the extra bytes if needed */
1616 if (size > oldActualSize)
1618 if (flags & HEAP_ZERO_MEMORY)
1620 clear_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize );
1621 mark_block_uninitialized( (char *)(pArena + 1) + size, pArena->unused_bytes );
1624 mark_block_uninitialized( (char *)(pArena + 1) + oldActualSize,
1625 (pArena->size & ARENA_SIZE_MASK) - oldActualSize );
1628 /* Return the new arena */
1632 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1633 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1637 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1638 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1639 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1640 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1644 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1645 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1646 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1651 /***********************************************************************
1652 * RtlCompactHeap (NTDLL.@)
1654 * Compact the free space in a Heap.
1657 * heap [I] Heap that block was allocated from
1658 * flags [I] HEAP_ flags from "winnt.h"
1661 * The number of bytes compacted.
1664 * This function is a harmless stub.
1666 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1668 static BOOL reported;
1669 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1674 /***********************************************************************
1675 * RtlLockHeap (NTDLL.@)
1680 * heap [I] Heap to lock
1683 * Success: TRUE. The Heap is locked.
1684 * Failure: FALSE, if heap is invalid.
1686 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1688 HEAP *heapPtr = HEAP_GetPtr( heap );
1689 if (!heapPtr) return FALSE;
1690 RtlEnterCriticalSection( &heapPtr->critSection );
1695 /***********************************************************************
1696 * RtlUnlockHeap (NTDLL.@)
1701 * heap [I] Heap to unlock
1704 * Success: TRUE. The Heap is unlocked.
1705 * Failure: FALSE, if heap is invalid.
1707 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1709 HEAP *heapPtr = HEAP_GetPtr( heap );
1710 if (!heapPtr) return FALSE;
1711 RtlLeaveCriticalSection( &heapPtr->critSection );
1716 /***********************************************************************
1717 * RtlSizeHeap (NTDLL.@)
1719 * Get the actual size of a memory block allocated from a Heap.
1722 * heap [I] Heap that block was allocated from
1723 * flags [I] HEAP_ flags from "winnt.h"
1724 * ptr [I] Block to get the size of
1727 * Success: The size of the block.
1728 * Failure: -1, heap or ptr are invalid.
1731 * The size may be bigger than what was passed to RtlAllocateHeap().
1733 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1736 HEAP *heapPtr = HEAP_GetPtr( heap );
1740 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1743 flags &= HEAP_NO_SERIALIZE;
1744 flags |= heapPtr->flags;
1745 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1746 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1748 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1753 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1754 if (pArena->size == ARENA_LARGE_SIZE)
1756 const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
1757 ret = large_arena->data_size;
1759 else ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1761 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1763 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1768 /***********************************************************************
1769 * RtlValidateHeap (NTDLL.@)
1771 * Determine if a block is a valid allocation from a heap.
1774 * heap [I] Heap that block was allocated from
1775 * flags [I] HEAP_ flags from "winnt.h"
1776 * ptr [I] Block to check
1779 * Success: TRUE. The block was allocated from heap.
1780 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1782 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1784 HEAP *heapPtr = HEAP_GetPtr( heap );
1785 if (!heapPtr) return FALSE;
1786 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1790 /***********************************************************************
1791 * RtlWalkHeap (NTDLL.@)
1794 * The PROCESS_HEAP_ENTRY flag values seem different between this
1795 * function and HeapWalk(). To be checked.
1797 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1799 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1800 HEAP *heapPtr = HEAP_GetPtr(heap);
1801 SUBHEAP *sub, *currentheap = NULL;
1804 int region_index = 0;
1806 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1808 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1810 /* FIXME: enumerate large blocks too */
1812 /* set ptr to the next arena to be examined */
1814 if (!entry->lpData) /* first call (init) ? */
1816 TRACE("begin walking of heap %p.\n", heap);
1817 currentheap = &heapPtr->subheap;
1818 ptr = (char*)currentheap->base + currentheap->headerSize;
1822 ptr = entry->lpData;
1823 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1825 if ((ptr >= (char *)sub->base) &&
1826 (ptr < (char *)sub->base + sub->size))
1833 if (currentheap == NULL)
1835 ERR("no matching subheap found, shouldn't happen !\n");
1836 ret = STATUS_NO_MORE_ENTRIES;
1840 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1842 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1843 ptr += pArena->size & ARENA_SIZE_MASK;
1845 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1847 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1848 ptr += pArena->size & ARENA_SIZE_MASK;
1851 ptr += entry->cbData; /* point to next arena */
1853 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1854 { /* proceed with next subheap */
1855 struct list *next = list_next( &heapPtr->subheap_list, ¤theap->entry );
1857 { /* successfully finished */
1858 TRACE("end reached.\n");
1859 ret = STATUS_NO_MORE_ENTRIES;
1862 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1863 ptr = (char *)currentheap->base + currentheap->headerSize;
1868 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1870 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1872 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1874 entry->lpData = pArena + 1;
1875 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1876 entry->cbOverhead = sizeof(ARENA_FREE);
1877 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1881 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1883 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1885 entry->lpData = pArena + 1;
1886 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1887 entry->cbOverhead = sizeof(ARENA_INUSE);
1888 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1889 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1890 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1893 entry->iRegionIndex = region_index;
1895 /* first element of heap ? */
1896 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1898 entry->wFlags |= PROCESS_HEAP_REGION;
1899 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1900 entry->u.Region.dwUnCommittedSize =
1901 currentheap->size - currentheap->commitSize;
1902 entry->u.Region.lpFirstBlock = /* first valid block */
1903 (char *)currentheap->base + currentheap->headerSize;
1904 entry->u.Region.lpLastBlock = /* first invalid block */
1905 (char *)currentheap->base + currentheap->size;
1907 ret = STATUS_SUCCESS;
1908 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1911 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1916 /***********************************************************************
1917 * RtlGetProcessHeaps (NTDLL.@)
1919 * Get the Heaps belonging to the current process.
1922 * count [I] size of heaps
1923 * heaps [O] Destination array for heap HANDLE's
1926 * Success: The number of Heaps allocated by the process.
1929 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1931 ULONG total = 1; /* main heap */
1934 RtlEnterCriticalSection( &processHeap->critSection );
1935 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1938 *heaps++ = processHeap;
1939 LIST_FOR_EACH( ptr, &processHeap->entry )
1940 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1942 RtlLeaveCriticalSection( &processHeap->critSection );