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 commitSize; /* Committed size of the sub-heap */
129 struct list entry; /* Entry in sub-heap list */
130 struct tagHEAP *heap; /* Main heap structure */
131 DWORD headerSize; /* Size of the heap header */
132 DWORD magic; /* Magic number */
135 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
137 typedef struct tagHEAP
140 DWORD flags; /* Heap flags */
141 DWORD force_flags; /* Forced heap flags for debugging */
142 SUBHEAP subheap; /* First sub-heap */
143 struct list entry; /* Entry in process heap list */
144 struct list subheap_list; /* Sub-heap list */
145 struct list large_list; /* Large blocks list */
146 SIZE_T grow_size; /* Size of next subheap for growing heap */
147 DWORD magic; /* Magic number */
148 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
149 FREE_LIST_ENTRY *freeList; /* Free lists */
152 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
154 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
155 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
157 static HEAP *processHeap; /* main process heap */
159 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
161 /* mark a block of memory as free for debugging purposes */
162 static inline void mark_block_free( void *ptr, SIZE_T size )
164 if (TRACE_ON(heap) || WARN_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
165 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
166 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
167 #elif defined( VALGRIND_MAKE_NOACCESS)
168 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
172 /* mark a block of memory as initialized for debugging purposes */
173 static inline void mark_block_initialized( void *ptr, SIZE_T size )
175 #if defined(VALGRIND_MAKE_MEM_DEFINED)
176 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
177 #elif defined(VALGRIND_MAKE_READABLE)
178 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
182 /* mark a block of memory as uninitialized for debugging purposes */
183 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
185 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
186 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
187 #elif defined(VALGRIND_MAKE_WRITABLE)
188 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
190 if (TRACE_ON(heap) || WARN_ON(heap))
192 memset( ptr, ARENA_INUSE_FILLER, size );
193 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
194 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
195 #elif defined(VALGRIND_MAKE_WRITABLE)
196 /* make it uninitialized to valgrind again */
197 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
202 /* clear contents of a block of memory */
203 static inline void clear_block( void *ptr, SIZE_T size )
205 mark_block_initialized( ptr, size );
206 memset( ptr, 0, size );
209 /* notify that a new block of memory has been allocated for debugging purposes */
210 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
212 #ifdef VALGRIND_MALLOCLIKE_BLOCK
213 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
217 /* notify that a block of memory has been freed for debugging purposes */
218 static inline void notify_free( void const *ptr )
220 #ifdef VALGRIND_FREELIKE_BLOCK
221 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
225 static void subheap_notify_free_all(SUBHEAP const *subheap)
227 #ifdef VALGRIND_FREELIKE_BLOCK
228 char const *ptr = (char const *)subheap->base + subheap->headerSize;
230 if (!RUNNING_ON_VALGRIND) return;
232 while (ptr < (char const *)subheap->base + subheap->size)
234 if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
236 ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
237 if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
238 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
242 ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
243 if (pArena->magic!=ARENA_INUSE_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
244 notify_free(pArena + 1);
245 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
251 /* locate a free list entry of the appropriate size */
252 /* size is the size of the whole block including the arena header */
253 static inline unsigned int get_freelist_index( SIZE_T size )
257 size -= sizeof(ARENA_FREE);
258 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
262 /* get the memory protection type to use for a given heap */
263 static inline ULONG get_protection_type( DWORD flags )
265 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
268 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
270 0, 0, NULL, /* will be set later */
271 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
272 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
276 /***********************************************************************
279 static void HEAP_Dump( HEAP *heap )
285 DPRINTF( "Heap: %p\n", heap );
286 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
287 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
289 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
290 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
291 DPRINTF( "%p free %08lx prev=%p next=%p\n",
292 &heap->freeList[i].arena, HEAP_freeListSizes[i],
293 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
294 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
296 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
298 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
299 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
300 subheap, subheap->base, subheap->size, subheap->commitSize );
302 DPRINTF( "\n Block Arena Stat Size Id\n" );
303 ptr = (char *)subheap->base + subheap->headerSize;
304 while (ptr < (char *)subheap->base + subheap->size)
306 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
308 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
309 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
310 pArena, pArena->magic,
311 pArena->size & ARENA_SIZE_MASK,
312 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
313 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
314 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
315 arenaSize += sizeof(ARENA_FREE);
316 freeSize += pArena->size & ARENA_SIZE_MASK;
318 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
320 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
321 DPRINTF( "%p %08x Used %08x back=%p\n",
322 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
323 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
324 arenaSize += sizeof(ARENA_INUSE);
325 usedSize += pArena->size & ARENA_SIZE_MASK;
329 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
330 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
331 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
332 arenaSize += sizeof(ARENA_INUSE);
333 usedSize += pArena->size & ARENA_SIZE_MASK;
336 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
337 subheap->size, subheap->commitSize, freeSize, usedSize,
338 arenaSize, (arenaSize * 100) / subheap->size );
343 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
346 TRACE( "Dumping entry %p\n", entry );
347 TRACE( "lpData\t\t: %p\n", entry->lpData );
348 TRACE( "cbData\t\t: %08x\n", entry->cbData);
349 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
350 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
351 TRACE( "WFlags\t\t: ");
352 if (entry->wFlags & PROCESS_HEAP_REGION)
353 TRACE( "PROCESS_HEAP_REGION ");
354 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
355 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
356 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
357 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
358 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
359 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
360 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
361 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
362 rem_flags = entry->wFlags &
363 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
364 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
365 PROCESS_HEAP_ENTRY_DDESHARE);
367 TRACE( "Unknown %08x", rem_flags);
369 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
370 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
373 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
375 if (entry->wFlags & PROCESS_HEAP_REGION)
377 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
378 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
379 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
380 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
384 /***********************************************************************
387 * Pointer to the heap
390 static HEAP *HEAP_GetPtr(
391 HANDLE heap /* [in] Handle to the heap */
393 HEAP *heapPtr = heap;
394 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
396 ERR("Invalid heap %p!\n", heap );
399 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
401 HEAP_Dump( heapPtr );
409 /***********************************************************************
410 * HEAP_InsertFreeBlock
412 * Insert a free block into the free list.
414 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
416 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
419 /* insert at end of free list, i.e. before the next free list entry */
421 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
422 list_add_before( &pEntry->arena.entry, &pArena->entry );
426 /* insert at head of free list */
427 list_add_after( &pEntry->arena.entry, &pArena->entry );
429 pArena->size |= ARENA_FLAG_FREE;
433 /***********************************************************************
435 * Find the sub-heap containing a given address.
441 static SUBHEAP *HEAP_FindSubHeap(
442 const HEAP *heap, /* [in] Heap pointer */
443 LPCVOID ptr ) /* [in] Address */
446 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
447 if ((ptr >= sub->base) &&
448 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
454 /***********************************************************************
457 * Make sure the heap storage is committed for a given size in the specified arena.
459 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
461 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
462 SIZE_T size = (char *)ptr - (char *)subheap->base;
463 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
464 if (size > subheap->size) size = subheap->size;
465 if (size <= subheap->commitSize) return TRUE;
466 size -= subheap->commitSize;
467 ptr = (char *)subheap->base + subheap->commitSize;
468 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
469 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
471 WARN("Could not commit %08lx bytes at %p for heap %p\n",
472 size, ptr, subheap->heap );
475 subheap->commitSize += size;
480 /***********************************************************************
483 * If possible, decommit the heap storage from (including) 'ptr'.
485 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
488 SIZE_T decommit_size;
489 SIZE_T size = (char *)ptr - (char *)subheap->base;
491 /* round to next block and add one full block */
492 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
493 if (size >= subheap->commitSize) return TRUE;
494 decommit_size = subheap->commitSize - size;
495 addr = (char *)subheap->base + size;
497 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
499 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
500 decommit_size, (char *)subheap->base + size, subheap->heap );
503 subheap->commitSize -= decommit_size;
508 /***********************************************************************
509 * HEAP_CreateFreeBlock
511 * Create a free block at a specified address. 'size' is the size of the
512 * whole block, including the new arena.
514 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
520 /* Create a free arena */
521 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
523 pFree->magic = ARENA_FREE_MAGIC;
525 /* If debugging, erase the freed block content */
527 pEnd = (char *)ptr + size;
528 if (pEnd > (char *)subheap->base + subheap->commitSize)
529 pEnd = (char *)subheap->base + subheap->commitSize;
530 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
532 /* Check if next block is free also */
534 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
535 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
537 /* Remove the next arena from the free list */
538 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
539 list_remove( &pNext->entry );
540 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
541 mark_block_free( pNext, sizeof(ARENA_FREE) );
544 /* Set the next block PREV_FREE flag and pointer */
546 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
549 DWORD *pNext = (DWORD *)((char *)ptr + size);
550 *pNext |= ARENA_FLAG_PREV_FREE;
551 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
552 *((ARENA_FREE **)pNext - 1) = pFree;
555 /* Last, insert the new block into the free list */
557 pFree->size = size - sizeof(*pFree);
558 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
562 /***********************************************************************
563 * HEAP_MakeInUseBlockFree
565 * Turn an in-use block into a free block. Can also decommit the end of
566 * the heap, and possibly even free the sub-heap altogether.
568 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
571 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
573 /* Check if we can merge with previous block */
575 if (pArena->size & ARENA_FLAG_PREV_FREE)
577 pFree = *((ARENA_FREE **)pArena - 1);
578 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
579 /* Remove it from the free list */
580 list_remove( &pFree->entry );
582 else pFree = (ARENA_FREE *)pArena;
584 /* Create a free block */
586 HEAP_CreateFreeBlock( subheap, pFree, size );
587 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
588 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
589 return; /* Not the last block, so nothing more to do */
591 /* Free the whole sub-heap if it's empty and not the original one */
593 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
594 (subheap != &subheap->heap->subheap))
597 void *addr = subheap->base;
598 /* Remove the free block from the list */
599 list_remove( &pFree->entry );
600 /* Remove the subheap from the list */
601 list_remove( &subheap->entry );
602 /* Free the memory */
604 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
608 /* Decommit the end of the heap */
610 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
614 /***********************************************************************
617 * Shrink an in-use block.
619 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
621 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
623 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
624 (pArena->size & ARENA_SIZE_MASK) - size );
625 /* assign size plus previous arena flags */
626 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
630 /* Turn off PREV_FREE flag in next block */
631 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
632 if (pNext < (char *)subheap->base + subheap->size)
633 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
638 /***********************************************************************
639 * allocate_large_block
641 static void *allocate_large_block( HEAP *heap, DWORD flags, SIZE_T size )
644 SIZE_T block_size = sizeof(*arena) + ROUND_SIZE(size);
645 LPVOID address = NULL;
647 if (block_size < size) return NULL; /* overflow */
648 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
649 &block_size, MEM_COMMIT, get_protection_type( flags ) ))
651 WARN("Could not allocate block for %08lx bytes\n", size );
655 arena->data_size = size;
656 arena->block_size = block_size;
657 arena->size = ARENA_LARGE_SIZE;
658 arena->magic = ARENA_LARGE_MAGIC;
659 list_add_tail( &heap->large_list, &arena->entry );
664 /***********************************************************************
667 static void free_large_block( HEAP *heap, DWORD flags, void *ptr )
669 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
670 LPVOID address = arena;
673 list_remove( &arena->entry );
674 NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
678 /***********************************************************************
679 * realloc_large_block
681 static void *realloc_large_block( HEAP *heap, DWORD flags, void *ptr, SIZE_T size )
683 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
686 if (arena->block_size - sizeof(*arena) >= size)
688 /* FIXME: we could remap zero-pages instead */
689 if ((flags & HEAP_ZERO_MEMORY) && size > arena->data_size)
690 memset( (char *)ptr + arena->data_size, 0, size - arena->data_size );
691 arena->data_size = size;
694 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) return NULL;
695 if (!(new_ptr = allocate_large_block( heap, flags, size )))
697 WARN("Could not allocate block for %08lx bytes\n", size );
700 memcpy( new_ptr, ptr, arena->data_size );
701 free_large_block( heap, flags, ptr );
706 /***********************************************************************
709 static ARENA_LARGE *find_large_block( HEAP *heap, const void *ptr )
713 LIST_FOR_EACH_ENTRY( arena, &heap->large_list, ARENA_LARGE, entry )
714 if (ptr == arena + 1) return arena;
720 /***********************************************************************
721 * validate_large_arena
723 static BOOL validate_large_arena( HEAP *heap, const ARENA_LARGE *arena, BOOL quiet )
725 if ((ULONG_PTR)arena % getpagesize())
729 ERR( "Heap %p: invalid large arena pointer %p\n", heap, arena );
730 if (TRACE_ON(heap)) HEAP_Dump( heap );
732 else if (WARN_ON(heap))
734 WARN( "Heap %p: unaligned arena pointer %p\n", heap, arena );
735 if (TRACE_ON(heap)) HEAP_Dump( heap );
739 if (arena->size != ARENA_LARGE_SIZE || arena->magic != ARENA_LARGE_MAGIC)
743 ERR( "Heap %p: invalid large arena %p values %x/%x\n",
744 heap, arena, arena->size, arena->magic );
745 if (TRACE_ON(heap)) HEAP_Dump( heap );
747 else if (WARN_ON(heap))
749 WARN( "Heap %p: invalid large arena %p values %x/%x\n",
750 heap, arena, arena->size, arena->magic );
751 if (TRACE_ON(heap)) HEAP_Dump( heap );
759 /***********************************************************************
762 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, LPVOID address, DWORD flags,
763 SIZE_T commitSize, SIZE_T totalSize )
766 FREE_LIST_ENTRY *pEntry;
771 /* round-up sizes on a 64K boundary */
772 totalSize = (totalSize + 0xffff) & 0xffff0000;
773 commitSize = (commitSize + 0xffff) & 0xffff0000;
774 if (!commitSize) commitSize = 0x10000;
775 totalSize = min( totalSize, 0xffff0000 ); /* don't allow a heap larger than 4Gb */
776 if (totalSize < commitSize) totalSize = commitSize;
777 if (flags & HEAP_SHARED) commitSize = totalSize; /* always commit everything in a shared heap */
779 /* allocate the memory block */
780 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
781 MEM_RESERVE, get_protection_type( flags ) ))
783 WARN("Could not allocate %08lx bytes\n", totalSize );
786 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
787 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
789 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
796 /* If this is a secondary subheap, insert it into list */
799 subheap->base = address;
800 subheap->heap = heap;
801 subheap->size = totalSize;
802 subheap->commitSize = commitSize;
803 subheap->magic = SUBHEAP_MAGIC;
804 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
805 list_add_head( &heap->subheap_list, &subheap->entry );
809 /* If this is a primary subheap, initialize main heap */
813 heap->magic = HEAP_MAGIC;
814 heap->grow_size = max( HEAP_DEF_SIZE, totalSize );
815 list_init( &heap->subheap_list );
816 list_init( &heap->large_list );
818 subheap = &heap->subheap;
819 subheap->base = address;
820 subheap->heap = heap;
821 subheap->size = totalSize;
822 subheap->commitSize = commitSize;
823 subheap->magic = SUBHEAP_MAGIC;
824 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
825 list_add_head( &heap->subheap_list, &subheap->entry );
827 /* Build the free lists */
829 heap->freeList = (FREE_LIST_ENTRY *)((char *)heap + subheap->headerSize);
830 subheap->headerSize += HEAP_NB_FREE_LISTS * sizeof(FREE_LIST_ENTRY);
831 list_init( &heap->freeList[0].arena.entry );
832 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
834 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
835 pEntry->arena.magic = ARENA_FREE_MAGIC;
836 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
839 /* Initialize critical section */
841 if (!processHeap) /* do it by hand to avoid memory allocations */
843 heap->critSection.DebugInfo = &process_heap_critsect_debug;
844 heap->critSection.LockCount = -1;
845 heap->critSection.RecursionCount = 0;
846 heap->critSection.OwningThread = 0;
847 heap->critSection.LockSemaphore = 0;
848 heap->critSection.SpinCount = 0;
849 process_heap_critsect_debug.CriticalSection = &heap->critSection;
853 RtlInitializeCriticalSection( &heap->critSection );
854 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
857 if (flags & HEAP_SHARED)
859 /* let's assume that only one thread at a time will try to do this */
860 HANDLE sem = heap->critSection.LockSemaphore;
861 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
863 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
864 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
865 heap->critSection.LockSemaphore = sem;
866 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
867 heap->critSection.DebugInfo = NULL;
871 /* Create the first free block */
873 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
874 subheap->size - subheap->headerSize );
880 /***********************************************************************
883 * Find a free block at least as large as the requested size, and make sure
884 * the requested size is committed.
886 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
887 SUBHEAP **ppSubHeap )
892 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
894 /* Find a suitable free list, and in it find a block large enough */
896 ptr = &pEntry->arena.entry;
897 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
899 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
900 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
901 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
902 if (arena_size >= size)
904 subheap = HEAP_FindSubHeap( heap, pArena );
905 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
906 *ppSubHeap = subheap;
911 /* If no block was found, attempt to grow the heap */
913 if (!(heap->flags & HEAP_GROWABLE))
915 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
918 /* make sure that we have a big enough size *committed* to fit another
919 * last free arena in !
920 * So just one heap struct, one first free arena which will eventually
921 * get used, and a second free arena that might get assigned all remaining
922 * free space in HEAP_ShrinkBlock() */
923 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
924 if (total_size < size) return NULL; /* overflow */
926 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
927 max( heap->grow_size, total_size ) )))
930 if (heap->grow_size < 128 * 1024 * 1024) heap->grow_size *= 2;
932 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
933 subheap, subheap->size, heap );
935 *ppSubHeap = subheap;
936 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
940 /***********************************************************************
941 * HEAP_IsValidArenaPtr
943 * Check that the pointer is inside the range possible for arenas.
945 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
948 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
949 if (!subheap) return FALSE;
950 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
951 if (subheap != &heap->subheap) return FALSE;
952 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
953 if (ptr == &heap->freeList[i].arena) return TRUE;
958 /***********************************************************************
959 * HEAP_ValidateFreeArena
961 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
963 ARENA_FREE *prev, *next;
964 char *heapEnd = (char *)subheap->base + subheap->size;
966 /* Check for unaligned pointers */
967 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
969 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
973 /* Check magic number */
974 if (pArena->magic != ARENA_FREE_MAGIC)
976 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
979 /* Check size flags */
980 if (!(pArena->size & ARENA_FLAG_FREE) ||
981 (pArena->size & ARENA_FLAG_PREV_FREE))
983 ERR("Heap %p: bad flags %08x for free arena %p\n",
984 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
987 /* Check arena size */
988 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
990 ERR("Heap %p: bad size %08x for free arena %p\n",
991 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
994 /* Check that next pointer is valid */
995 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
996 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
998 ERR("Heap %p: bad next ptr %p for arena %p\n",
999 subheap->heap, next, pArena );
1002 /* Check that next arena is free */
1003 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1005 ERR("Heap %p: next arena %p invalid for %p\n",
1006 subheap->heap, next, pArena );
1009 /* Check that prev pointer is valid */
1010 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1011 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1013 ERR("Heap %p: bad prev ptr %p for arena %p\n",
1014 subheap->heap, prev, pArena );
1017 /* Check that prev arena is free */
1018 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1020 /* this often means that the prev arena got overwritten
1021 * by a memory write before that prev arena */
1022 ERR("Heap %p: prev arena %p invalid for %p\n",
1023 subheap->heap, prev, pArena );
1026 /* Check that next block has PREV_FREE flag */
1027 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
1029 if (!(*(DWORD *)((char *)(pArena + 1) +
1030 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1032 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1033 subheap->heap, pArena );
1036 /* Check next block back pointer */
1037 if (*((ARENA_FREE **)((char *)(pArena + 1) +
1038 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
1040 ERR("Heap %p: arena %p has wrong back ptr %p\n",
1041 subheap->heap, pArena,
1042 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
1050 /***********************************************************************
1051 * HEAP_ValidateInUseArena
1053 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1055 const char *heapEnd = (const char *)subheap->base + subheap->size;
1057 /* Check for unaligned pointers */
1058 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1060 if ( quiet == NOISY )
1062 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1063 if ( TRACE_ON(heap) )
1064 HEAP_Dump( subheap->heap );
1066 else if ( WARN_ON(heap) )
1068 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1069 if ( TRACE_ON(heap) )
1070 HEAP_Dump( subheap->heap );
1075 /* Check magic number */
1076 if (pArena->magic != ARENA_INUSE_MAGIC)
1078 if (quiet == NOISY) {
1079 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1081 HEAP_Dump( subheap->heap );
1082 } else if (WARN_ON(heap)) {
1083 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1085 HEAP_Dump( subheap->heap );
1089 /* Check size flags */
1090 if (pArena->size & ARENA_FLAG_FREE)
1092 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1093 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1096 /* Check arena size */
1097 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
1099 ERR("Heap %p: bad size %08x for in-use arena %p\n",
1100 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
1103 /* Check next arena PREV_FREE flag */
1104 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
1105 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1107 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
1108 subheap->heap, pArena );
1111 /* Check prev free arena */
1112 if (pArena->size & ARENA_FLAG_PREV_FREE)
1114 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1115 /* Check prev pointer */
1116 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1118 ERR("Heap %p: bad back ptr %p for arena %p\n",
1119 subheap->heap, pPrev, pArena );
1122 /* Check that prev arena is free */
1123 if (!(pPrev->size & ARENA_FLAG_FREE) ||
1124 (pPrev->magic != ARENA_FREE_MAGIC))
1126 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1127 subheap->heap, pPrev, pArena );
1130 /* Check that prev arena is really the previous block */
1131 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1133 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1134 subheap->heap, pPrev, pArena );
1142 /***********************************************************************
1143 * HEAP_IsRealArena [Internal]
1144 * Validates a block is a valid arena.
1150 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1151 DWORD flags, /* [in] Bit flags that control access during operation */
1152 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1153 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1154 * does not complain */
1158 const ARENA_LARGE *large_arena;
1160 flags &= HEAP_NO_SERIALIZE;
1161 flags |= heapPtr->flags;
1162 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1163 if (!(flags & HEAP_NO_SERIALIZE))
1164 RtlEnterCriticalSection( &heapPtr->critSection );
1166 if (block) /* only check this single memory block */
1168 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1170 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1171 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1173 if (!(large_arena = find_large_block( heapPtr, block )))
1176 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1177 else if (WARN_ON(heap))
1178 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1182 ret = validate_large_arena( heapPtr, large_arena, quiet );
1184 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1186 if (!(flags & HEAP_NO_SERIALIZE))
1187 RtlLeaveCriticalSection( &heapPtr->critSection );
1191 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1193 char *ptr = (char *)subheap->base + subheap->headerSize;
1194 while (ptr < (char *)subheap->base + subheap->size)
1196 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1198 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1202 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1206 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1210 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1216 LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1217 if (!(ret = validate_large_arena( heapPtr, large_arena, quiet ))) break;
1219 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1224 /***********************************************************************
1225 * RtlCreateHeap (NTDLL.@)
1227 * Create a new Heap.
1230 * flags [I] HEAP_ flags from "winnt.h"
1231 * addr [I] Desired base address
1232 * totalSize [I] Total size of the heap, or 0 for a growable heap
1233 * commitSize [I] Amount of heap space to commit
1234 * unknown [I] Not yet understood
1235 * definition [I] Heap definition
1238 * Success: A HANDLE to the newly created heap.
1239 * Failure: a NULL HANDLE.
1241 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1242 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1246 /* Allocate the heap block */
1250 totalSize = HEAP_DEF_SIZE;
1251 flags |= HEAP_GROWABLE;
1254 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1256 /* link it into the per-process heap list */
1259 HEAP *heapPtr = subheap->heap;
1260 RtlEnterCriticalSection( &processHeap->critSection );
1261 list_add_head( &processHeap->entry, &heapPtr->entry );
1262 RtlLeaveCriticalSection( &processHeap->critSection );
1266 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1267 list_init( &processHeap->entry );
1270 return subheap->heap;
1274 /***********************************************************************
1275 * RtlDestroyHeap (NTDLL.@)
1277 * Destroy a Heap created with RtlCreateHeap().
1280 * heap [I] Heap to destroy.
1283 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1284 * Failure: The Heap handle, if heap is the process heap.
1286 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1288 HEAP *heapPtr = HEAP_GetPtr( heap );
1289 SUBHEAP *subheap, *next;
1290 ARENA_LARGE *arena, *arena_next;
1294 TRACE("%p\n", heap );
1295 if (!heapPtr) return heap;
1297 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1299 /* remove it from the per-process list */
1300 RtlEnterCriticalSection( &processHeap->critSection );
1301 list_remove( &heapPtr->entry );
1302 RtlLeaveCriticalSection( &processHeap->critSection );
1304 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1305 RtlDeleteCriticalSection( &heapPtr->critSection );
1307 LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1309 list_remove( &arena->entry );
1312 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1314 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1316 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1317 subheap_notify_free_all(subheap);
1318 list_remove( &subheap->entry );
1320 addr = subheap->base;
1321 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1323 subheap_notify_free_all(&heapPtr->subheap);
1325 addr = heapPtr->subheap.base;
1326 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1331 /***********************************************************************
1332 * RtlAllocateHeap (NTDLL.@)
1334 * Allocate a memory block from a Heap.
1337 * heap [I] Heap to allocate block from
1338 * flags [I] HEAP_ flags from "winnt.h"
1339 * size [I] Size of the memory block to allocate
1342 * Success: A pointer to the newly allocated block
1346 * This call does not SetLastError().
1348 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1351 ARENA_INUSE *pInUse;
1353 HEAP *heapPtr = HEAP_GetPtr( heap );
1354 SIZE_T rounded_size;
1356 /* Validate the parameters */
1358 if (!heapPtr) return NULL;
1359 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1360 flags |= heapPtr->flags;
1361 rounded_size = ROUND_SIZE(size);
1362 if (rounded_size < size) /* overflow */
1364 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1367 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1369 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1371 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1373 void *ret = allocate_large_block( heap, flags, size );
1374 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1375 if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1376 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1377 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1381 /* Locate a suitable free block */
1383 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1385 TRACE("(%p,%08x,%08lx): returning NULL\n",
1386 heap, flags, size );
1387 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1388 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1392 /* Remove the arena from the free list */
1394 list_remove( &pArena->entry );
1396 /* Build the in-use arena */
1398 pInUse = (ARENA_INUSE *)pArena;
1400 /* in-use arena is smaller than free arena,
1401 * so we have to add the difference to the size */
1402 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1403 pInUse->magic = ARENA_INUSE_MAGIC;
1405 /* Shrink the block */
1407 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1408 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1410 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1412 if (flags & HEAP_ZERO_MEMORY)
1414 clear_block( pInUse + 1, size );
1415 mark_block_uninitialized( (char *)(pInUse + 1) + size, pInUse->unused_bytes );
1418 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1420 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1422 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1427 /***********************************************************************
1428 * RtlFreeHeap (NTDLL.@)
1430 * Free a memory block allocated with RtlAllocateHeap().
1433 * heap [I] Heap that block was allocated from
1434 * flags [I] HEAP_ flags from "winnt.h"
1435 * ptr [I] Block to free
1438 * Success: TRUE, if ptr is NULL or was freed successfully.
1441 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1443 ARENA_INUSE *pInUse;
1447 /* Validate the parameters */
1449 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1451 heapPtr = HEAP_GetPtr( heap );
1454 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1458 flags &= HEAP_NO_SERIALIZE;
1459 flags |= heapPtr->flags;
1460 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1462 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1465 /* Some sanity checks */
1466 pInUse = (ARENA_INUSE *)ptr - 1;
1467 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse )))
1469 if (!find_large_block( heapPtr, ptr )) goto error;
1470 free_large_block( heapPtr, flags, ptr );
1473 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1474 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1476 /* Turn the block into a free block */
1478 HEAP_MakeInUseBlockFree( subheap, pInUse );
1481 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1482 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1486 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1487 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1488 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1493 /***********************************************************************
1494 * RtlReAllocateHeap (NTDLL.@)
1496 * Change the size of a memory block allocated with RtlAllocateHeap().
1499 * heap [I] Heap that block was allocated from
1500 * flags [I] HEAP_ flags from "winnt.h"
1501 * ptr [I] Block to resize
1502 * size [I] Size of the memory block to allocate
1505 * Success: A pointer to the resized block (which may be different).
1508 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1510 ARENA_INUSE *pArena;
1513 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1516 if (!ptr) return NULL;
1517 if (!(heapPtr = HEAP_GetPtr( heap )))
1519 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1523 /* Validate the parameters */
1525 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1526 HEAP_REALLOC_IN_PLACE_ONLY;
1527 flags |= heapPtr->flags;
1528 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1530 rounded_size = ROUND_SIZE(size);
1531 if (rounded_size < size) goto oom; /* overflow */
1532 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1534 pArena = (ARENA_INUSE *)ptr - 1;
1535 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena )))
1537 if (!find_large_block( heapPtr, ptr )) goto error;
1538 if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1540 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1543 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1544 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1546 /* Check if we need to grow the block */
1548 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1549 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1550 if (rounded_size > oldBlockSize)
1552 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1554 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1556 if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1557 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1558 memcpy( ret, pArena + 1, oldActualSize );
1559 notify_free( pArena + 1 );
1560 HEAP_MakeInUseBlockFree( subheap, pArena );
1563 if ((pNext < (char *)subheap->base + subheap->size) &&
1564 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1565 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1567 /* The next block is free and large enough */
1568 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1569 list_remove( &pFree->entry );
1570 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1571 if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1572 notify_free( pArena + 1 );
1573 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1574 notify_alloc( pArena + 1, size, FALSE );
1575 /* FIXME: this is wrong as we may lose old VBits settings */
1576 mark_block_initialized( pArena + 1, oldActualSize );
1578 else /* Do it the hard way */
1581 ARENA_INUSE *pInUse;
1582 SUBHEAP *newsubheap;
1584 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1585 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1588 /* Build the in-use arena */
1590 list_remove( &pNew->entry );
1591 pInUse = (ARENA_INUSE *)pNew;
1592 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1593 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1594 pInUse->magic = ARENA_INUSE_MAGIC;
1595 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1597 mark_block_initialized( pInUse + 1, oldActualSize );
1598 notify_alloc( pInUse + 1, size, FALSE );
1599 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1601 /* Free the previous block */
1603 notify_free( pArena + 1 );
1604 HEAP_MakeInUseBlockFree( subheap, pArena );
1605 subheap = newsubheap;
1611 /* Shrink the block */
1612 notify_free( pArena + 1 );
1613 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1614 notify_alloc( pArena + 1, size, FALSE );
1615 /* FIXME: this is wrong as we may lose old VBits settings */
1616 mark_block_initialized( pArena + 1, size );
1619 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1621 /* Clear the extra bytes if needed */
1623 if (size > oldActualSize)
1625 if (flags & HEAP_ZERO_MEMORY)
1627 clear_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize );
1628 mark_block_uninitialized( (char *)(pArena + 1) + size, pArena->unused_bytes );
1631 mark_block_uninitialized( (char *)(pArena + 1) + oldActualSize,
1632 (pArena->size & ARENA_SIZE_MASK) - oldActualSize );
1635 /* Return the new arena */
1639 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1640 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1644 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1645 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1646 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1647 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1651 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1652 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1653 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1658 /***********************************************************************
1659 * RtlCompactHeap (NTDLL.@)
1661 * Compact the free space in a Heap.
1664 * heap [I] Heap that block was allocated from
1665 * flags [I] HEAP_ flags from "winnt.h"
1668 * The number of bytes compacted.
1671 * This function is a harmless stub.
1673 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1675 static BOOL reported;
1676 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1681 /***********************************************************************
1682 * RtlLockHeap (NTDLL.@)
1687 * heap [I] Heap to lock
1690 * Success: TRUE. The Heap is locked.
1691 * Failure: FALSE, if heap is invalid.
1693 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1695 HEAP *heapPtr = HEAP_GetPtr( heap );
1696 if (!heapPtr) return FALSE;
1697 RtlEnterCriticalSection( &heapPtr->critSection );
1702 /***********************************************************************
1703 * RtlUnlockHeap (NTDLL.@)
1708 * heap [I] Heap to unlock
1711 * Success: TRUE. The Heap is unlocked.
1712 * Failure: FALSE, if heap is invalid.
1714 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1716 HEAP *heapPtr = HEAP_GetPtr( heap );
1717 if (!heapPtr) return FALSE;
1718 RtlLeaveCriticalSection( &heapPtr->critSection );
1723 /***********************************************************************
1724 * RtlSizeHeap (NTDLL.@)
1726 * Get the actual size of a memory block allocated from a Heap.
1729 * heap [I] Heap that block was allocated from
1730 * flags [I] HEAP_ flags from "winnt.h"
1731 * ptr [I] Block to get the size of
1734 * Success: The size of the block.
1735 * Failure: -1, heap or ptr are invalid.
1738 * The size may be bigger than what was passed to RtlAllocateHeap().
1740 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1743 HEAP *heapPtr = HEAP_GetPtr( heap );
1747 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1750 flags &= HEAP_NO_SERIALIZE;
1751 flags |= heapPtr->flags;
1752 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1753 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1755 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1760 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1761 if (pArena->size == ARENA_LARGE_SIZE)
1763 const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
1764 ret = large_arena->data_size;
1766 else ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1768 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1770 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1775 /***********************************************************************
1776 * RtlValidateHeap (NTDLL.@)
1778 * Determine if a block is a valid allocation from a heap.
1781 * heap [I] Heap that block was allocated from
1782 * flags [I] HEAP_ flags from "winnt.h"
1783 * ptr [I] Block to check
1786 * Success: TRUE. The block was allocated from heap.
1787 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1789 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1791 HEAP *heapPtr = HEAP_GetPtr( heap );
1792 if (!heapPtr) return FALSE;
1793 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1797 /***********************************************************************
1798 * RtlWalkHeap (NTDLL.@)
1801 * The PROCESS_HEAP_ENTRY flag values seem different between this
1802 * function and HeapWalk(). To be checked.
1804 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1806 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1807 HEAP *heapPtr = HEAP_GetPtr(heap);
1808 SUBHEAP *sub, *currentheap = NULL;
1811 int region_index = 0;
1813 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1815 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1817 /* FIXME: enumerate large blocks too */
1819 /* set ptr to the next arena to be examined */
1821 if (!entry->lpData) /* first call (init) ? */
1823 TRACE("begin walking of heap %p.\n", heap);
1824 currentheap = &heapPtr->subheap;
1825 ptr = (char*)currentheap->base + currentheap->headerSize;
1829 ptr = entry->lpData;
1830 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1832 if ((ptr >= (char *)sub->base) &&
1833 (ptr < (char *)sub->base + sub->size))
1840 if (currentheap == NULL)
1842 ERR("no matching subheap found, shouldn't happen !\n");
1843 ret = STATUS_NO_MORE_ENTRIES;
1847 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1849 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1850 ptr += pArena->size & ARENA_SIZE_MASK;
1852 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1854 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1855 ptr += pArena->size & ARENA_SIZE_MASK;
1858 ptr += entry->cbData; /* point to next arena */
1860 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1861 { /* proceed with next subheap */
1862 struct list *next = list_next( &heapPtr->subheap_list, ¤theap->entry );
1864 { /* successfully finished */
1865 TRACE("end reached.\n");
1866 ret = STATUS_NO_MORE_ENTRIES;
1869 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1870 ptr = (char *)currentheap->base + currentheap->headerSize;
1875 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1877 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1879 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1881 entry->lpData = pArena + 1;
1882 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1883 entry->cbOverhead = sizeof(ARENA_FREE);
1884 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1888 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1890 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1892 entry->lpData = pArena + 1;
1893 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1894 entry->cbOverhead = sizeof(ARENA_INUSE);
1895 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1896 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1897 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1900 entry->iRegionIndex = region_index;
1902 /* first element of heap ? */
1903 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1905 entry->wFlags |= PROCESS_HEAP_REGION;
1906 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1907 entry->u.Region.dwUnCommittedSize =
1908 currentheap->size - currentheap->commitSize;
1909 entry->u.Region.lpFirstBlock = /* first valid block */
1910 (char *)currentheap->base + currentheap->headerSize;
1911 entry->u.Region.lpLastBlock = /* first invalid block */
1912 (char *)currentheap->base + currentheap->size;
1914 ret = STATUS_SUCCESS;
1915 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1918 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1923 /***********************************************************************
1924 * RtlGetProcessHeaps (NTDLL.@)
1926 * Get the Heaps belonging to the current process.
1929 * count [I] size of heaps
1930 * heaps [O] Destination array for heap HANDLE's
1933 * Success: The number of Heaps allocated by the process.
1936 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1938 ULONG total = 1; /* main heap */
1941 RtlEnterCriticalSection( &processHeap->critSection );
1942 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1945 *heaps++ = processHeap;
1946 LIST_FOR_EACH( ptr, &processHeap->entry )
1947 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1949 RtlLeaveCriticalSection( &processHeap->critSection );