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
29 #ifdef HAVE_VALGRIND_MEMCHECK_H
30 #include <valgrind/memcheck.h>
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
36 #define WIN32_NO_STATUS
40 #include "wine/list.h"
41 #include "wine/debug.h"
42 #include "wine/server.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(heap);
46 /* Note: the heap data structures are loosely based on what Pietrek describes in his
47 * book 'Windows 95 System Programming Secrets', with some adaptations for
48 * better compatibility with NT.
51 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
52 * that there is no unaligned accesses to structure fields.
55 typedef struct tagARENA_INUSE
57 DWORD size; /* Block size; must be the first field */
58 DWORD magic : 24; /* Magic number */
59 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) */
62 typedef struct tagARENA_FREE
64 DWORD size; /* Block size; must be the first field */
65 DWORD magic; /* Magic number */
66 struct list entry; /* Entry in free list */
69 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
70 #define ARENA_FLAG_PREV_FREE 0x00000002
71 #define ARENA_SIZE_MASK (~3)
72 #define ARENA_INUSE_MAGIC 0x455355 /* Value for arena 'magic' field */
73 #define ARENA_FREE_MAGIC 0x45455246 /* Value for arena 'magic' field */
75 #define ARENA_INUSE_FILLER 0x55
76 #define ARENA_FREE_FILLER 0xaa
78 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
79 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
81 #define QUIET 1 /* Suppress messages */
82 #define NOISY 0 /* Report all errors */
84 /* minimum data size (without arenas) of an allocated block */
85 /* make sure that it's larger than a free list entry */
86 #define HEAP_MIN_DATA_SIZE (2 * sizeof(struct list))
87 /* minimum size that must remain to shrink an allocated block */
88 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
90 /* Max size of the blocks on the free lists */
91 static const SIZE_T HEAP_freeListSizes[] =
93 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
95 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
104 typedef struct tagSUBHEAP
106 void *base; /* Base address of the sub-heap memory block */
107 SIZE_T size; /* Size of the whole sub-heap */
108 SIZE_T commitSize; /* Committed size of the sub-heap */
109 struct list entry; /* Entry in sub-heap list */
110 struct tagHEAP *heap; /* Main heap structure */
111 DWORD headerSize; /* Size of the heap header */
112 DWORD magic; /* Magic number */
115 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
117 typedef struct tagHEAP
120 DWORD flags; /* Heap flags */
121 DWORD force_flags; /* Forced heap flags for debugging */
122 SUBHEAP subheap; /* First sub-heap */
123 struct list entry; /* Entry in process heap list */
124 struct list subheap_list; /* Sub-heap list */
125 DWORD magic; /* Magic number */
126 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
127 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
130 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
132 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
133 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
135 static HEAP *processHeap; /* main process heap */
137 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
139 /* mark a block of memory as free for debugging purposes */
140 static inline void mark_block_free( void *ptr, SIZE_T size )
142 if (TRACE_ON(heap) || WARN_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
143 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
144 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
145 #elif defined( VALGRIND_MAKE_NOACCESS)
146 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
150 /* mark a block of memory as initialized for debugging purposes */
151 static inline void mark_block_initialized( void *ptr, SIZE_T size )
153 #if defined(VALGRIND_MAKE_MEM_DEFINED)
154 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
155 #elif defined(VALGRIND_MAKE_READABLE)
156 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
160 /* mark a block of memory as uninitialized for debugging purposes */
161 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
163 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
164 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
165 #elif defined(VALGRIND_MAKE_WRITABLE)
166 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
168 if (TRACE_ON(heap) || WARN_ON(heap))
170 memset( ptr, ARENA_INUSE_FILLER, size );
171 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
172 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
173 #elif defined(VALGRIND_MAKE_WRITABLE)
174 /* make it uninitialized to valgrind again */
175 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
180 /* clear contents of a block of memory */
181 static inline void clear_block( void *ptr, SIZE_T size )
183 mark_block_initialized( ptr, size );
184 memset( ptr, 0, size );
187 /* notify that a new block of memory has been allocated for debugging purposes */
188 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
190 #ifdef VALGRIND_MALLOCLIKE_BLOCK
191 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
195 /* notify that a block of memory has been freed for debugging purposes */
196 static inline void notify_free( void *ptr )
198 #ifdef VALGRIND_FREELIKE_BLOCK
199 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
203 /* locate a free list entry of the appropriate size */
204 /* size is the size of the whole block including the arena header */
205 static inline unsigned int get_freelist_index( SIZE_T size )
209 size -= sizeof(ARENA_FREE);
210 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
214 /* get the memory protection type to use for a given heap */
215 static inline ULONG get_protection_type( DWORD flags )
217 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
220 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
222 0, 0, NULL, /* will be set later */
223 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
224 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
228 /***********************************************************************
231 static void HEAP_Dump( HEAP *heap )
237 DPRINTF( "Heap: %p\n", heap );
238 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
239 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
241 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
242 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
243 DPRINTF( "%p free %08lx prev=%p next=%p\n",
244 &heap->freeList[i].arena, HEAP_freeListSizes[i],
245 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
246 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
248 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
250 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
251 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
252 subheap, subheap->base, subheap->size, subheap->commitSize );
254 DPRINTF( "\n Block Arena Stat Size Id\n" );
255 ptr = (char *)subheap->base + subheap->headerSize;
256 while (ptr < (char *)subheap->base + subheap->size)
258 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
260 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
261 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
262 pArena, pArena->magic,
263 pArena->size & ARENA_SIZE_MASK,
264 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
265 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
266 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
267 arenaSize += sizeof(ARENA_FREE);
268 freeSize += pArena->size & ARENA_SIZE_MASK;
270 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
272 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
273 DPRINTF( "%p %08x Used %08x back=%p\n",
274 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
275 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
276 arenaSize += sizeof(ARENA_INUSE);
277 usedSize += pArena->size & ARENA_SIZE_MASK;
281 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
282 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
283 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
284 arenaSize += sizeof(ARENA_INUSE);
285 usedSize += pArena->size & ARENA_SIZE_MASK;
288 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
289 subheap->size, subheap->commitSize, freeSize, usedSize,
290 arenaSize, (arenaSize * 100) / subheap->size );
295 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
298 TRACE( "Dumping entry %p\n", entry );
299 TRACE( "lpData\t\t: %p\n", entry->lpData );
300 TRACE( "cbData\t\t: %08x\n", entry->cbData);
301 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
302 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
303 TRACE( "WFlags\t\t: ");
304 if (entry->wFlags & PROCESS_HEAP_REGION)
305 TRACE( "PROCESS_HEAP_REGION ");
306 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
307 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
308 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
309 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
310 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
311 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
312 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
313 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
314 rem_flags = entry->wFlags &
315 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
316 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
317 PROCESS_HEAP_ENTRY_DDESHARE);
319 TRACE( "Unknown %08x", rem_flags);
321 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
322 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
325 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
327 if (entry->wFlags & PROCESS_HEAP_REGION)
329 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
330 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
331 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
332 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
336 /***********************************************************************
339 * Pointer to the heap
342 static HEAP *HEAP_GetPtr(
343 HANDLE heap /* [in] Handle to the heap */
345 HEAP *heapPtr = (HEAP *)heap;
346 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
348 ERR("Invalid heap %p!\n", heap );
351 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
353 HEAP_Dump( heapPtr );
361 /***********************************************************************
362 * HEAP_InsertFreeBlock
364 * Insert a free block into the free list.
366 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
368 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
371 /* insert at end of free list, i.e. before the next free list entry */
373 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
374 list_add_before( &pEntry->arena.entry, &pArena->entry );
378 /* insert at head of free list */
379 list_add_after( &pEntry->arena.entry, &pArena->entry );
381 pArena->size |= ARENA_FLAG_FREE;
385 /***********************************************************************
387 * Find the sub-heap containing a given address.
393 static SUBHEAP *HEAP_FindSubHeap(
394 const HEAP *heap, /* [in] Heap pointer */
395 LPCVOID ptr ) /* [in] Address */
398 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
399 if (((const char *)ptr >= (const char *)sub->base) &&
400 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
406 /***********************************************************************
409 * Make sure the heap storage is committed for a given size in the specified arena.
411 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
413 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
414 SIZE_T size = (char *)ptr - (char *)subheap->base;
415 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
416 if (size > subheap->size) size = subheap->size;
417 if (size <= subheap->commitSize) return TRUE;
418 size -= subheap->commitSize;
419 ptr = (char *)subheap->base + subheap->commitSize;
420 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
421 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
423 WARN("Could not commit %08lx bytes at %p for heap %p\n",
424 size, ptr, subheap->heap );
427 subheap->commitSize += size;
432 /***********************************************************************
435 * If possible, decommit the heap storage from (including) 'ptr'.
437 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
440 SIZE_T decommit_size;
441 SIZE_T size = (char *)ptr - (char *)subheap->base;
443 /* round to next block and add one full block */
444 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
445 if (size >= subheap->commitSize) return TRUE;
446 decommit_size = subheap->commitSize - size;
447 addr = (char *)subheap->base + size;
449 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
451 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
452 decommit_size, (char *)subheap->base + size, subheap->heap );
455 subheap->commitSize -= decommit_size;
460 /***********************************************************************
461 * HEAP_CreateFreeBlock
463 * Create a free block at a specified address. 'size' is the size of the
464 * whole block, including the new arena.
466 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
472 /* Create a free arena */
473 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
474 pFree = (ARENA_FREE *)ptr;
475 pFree->magic = ARENA_FREE_MAGIC;
477 /* If debugging, erase the freed block content */
479 pEnd = (char *)ptr + size;
480 if (pEnd > (char *)subheap->base + subheap->commitSize)
481 pEnd = (char *)subheap->base + subheap->commitSize;
482 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
484 /* Check if next block is free also */
486 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
487 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
489 /* Remove the next arena from the free list */
490 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
491 list_remove( &pNext->entry );
492 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
493 mark_block_free( pNext, sizeof(ARENA_FREE) );
496 /* Set the next block PREV_FREE flag and pointer */
498 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
501 DWORD *pNext = (DWORD *)((char *)ptr + size);
502 *pNext |= ARENA_FLAG_PREV_FREE;
503 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
504 *((ARENA_FREE **)pNext - 1) = pFree;
507 /* Last, insert the new block into the free list */
509 pFree->size = size - sizeof(*pFree);
510 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
514 /***********************************************************************
515 * HEAP_MakeInUseBlockFree
517 * Turn an in-use block into a free block. Can also decommit the end of
518 * the heap, and possibly even free the sub-heap altogether.
520 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
523 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
525 /* Check if we can merge with previous block */
527 if (pArena->size & ARENA_FLAG_PREV_FREE)
529 pFree = *((ARENA_FREE **)pArena - 1);
530 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
531 /* Remove it from the free list */
532 list_remove( &pFree->entry );
534 else pFree = (ARENA_FREE *)pArena;
536 /* Create a free block */
538 HEAP_CreateFreeBlock( subheap, pFree, size );
539 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
540 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
541 return; /* Not the last block, so nothing more to do */
543 /* Free the whole sub-heap if it's empty and not the original one */
545 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
546 (subheap != &subheap->heap->subheap))
549 void *addr = subheap->base;
550 /* Remove the free block from the list */
551 list_remove( &pFree->entry );
552 /* Remove the subheap from the list */
553 list_remove( &subheap->entry );
554 /* Free the memory */
556 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
560 /* Decommit the end of the heap */
562 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
566 /***********************************************************************
569 * Shrink an in-use block.
571 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
573 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
575 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
576 (pArena->size & ARENA_SIZE_MASK) - size );
577 /* assign size plus previous arena flags */
578 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
582 /* Turn off PREV_FREE flag in next block */
583 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
584 if (pNext < (char *)subheap->base + subheap->size)
585 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
589 /***********************************************************************
592 static SUBHEAP *HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
593 SIZE_T commitSize, SIZE_T totalSize )
596 FREE_LIST_ENTRY *pEntry;
601 if (flags & HEAP_SHARED)
602 commitSize = totalSize; /* always commit everything in a shared heap */
603 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
604 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
606 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
612 /* If this is a secondary subheap, insert it into list */
614 subheap = (SUBHEAP *)address;
615 subheap->base = address;
616 subheap->heap = heap;
617 subheap->size = totalSize;
618 subheap->commitSize = commitSize;
619 subheap->magic = SUBHEAP_MAGIC;
620 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
621 list_add_head( &heap->subheap_list, &subheap->entry );
625 /* If this is a primary subheap, initialize main heap */
627 heap = (HEAP *)address;
629 heap->magic = HEAP_MAGIC;
630 list_init( &heap->subheap_list );
632 subheap = &heap->subheap;
633 subheap->base = address;
634 subheap->heap = heap;
635 subheap->size = totalSize;
636 subheap->commitSize = commitSize;
637 subheap->magic = SUBHEAP_MAGIC;
638 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
639 list_add_head( &heap->subheap_list, &subheap->entry );
641 /* Build the free lists */
643 list_init( &heap->freeList[0].arena.entry );
644 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
646 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
647 pEntry->arena.magic = ARENA_FREE_MAGIC;
648 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
651 /* Initialize critical section */
653 if (!processHeap) /* do it by hand to avoid memory allocations */
655 heap->critSection.DebugInfo = &process_heap_critsect_debug;
656 heap->critSection.LockCount = -1;
657 heap->critSection.RecursionCount = 0;
658 heap->critSection.OwningThread = 0;
659 heap->critSection.LockSemaphore = 0;
660 heap->critSection.SpinCount = 0;
661 process_heap_critsect_debug.CriticalSection = &heap->critSection;
665 RtlInitializeCriticalSection( &heap->critSection );
666 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
669 if (flags & HEAP_SHARED)
671 /* let's assume that only one thread at a time will try to do this */
672 HANDLE sem = heap->critSection.LockSemaphore;
673 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
675 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
676 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
677 heap->critSection.LockSemaphore = sem;
678 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
679 heap->critSection.DebugInfo = NULL;
683 /* Create the first free block */
685 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
686 subheap->size - subheap->headerSize );
691 /***********************************************************************
694 * Create a sub-heap of the given size.
695 * If heap == NULL, creates a main heap.
697 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
698 SIZE_T commitSize, SIZE_T totalSize )
700 LPVOID address = base;
703 /* round-up sizes on a 64K boundary */
704 totalSize = (totalSize + 0xffff) & 0xffff0000;
705 commitSize = (commitSize + 0xffff) & 0xffff0000;
706 if (!commitSize) commitSize = 0x10000;
707 if (totalSize < commitSize) totalSize = commitSize;
711 /* allocate the memory block */
712 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
713 MEM_RESERVE, get_protection_type( flags ) ))
715 WARN("Could not allocate %08lx bytes\n", totalSize );
720 /* Initialize subheap */
722 if (!(ret = HEAP_InitSubHeap( heap, address, flags, commitSize, totalSize )))
725 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
731 /***********************************************************************
734 * Find a free block at least as large as the requested size, and make sure
735 * the requested size is committed.
737 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
738 SUBHEAP **ppSubHeap )
743 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
745 /* Find a suitable free list, and in it find a block large enough */
747 ptr = &pEntry->arena.entry;
748 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
750 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
751 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
752 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
753 if (arena_size >= size)
755 subheap = HEAP_FindSubHeap( heap, pArena );
756 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
757 *ppSubHeap = subheap;
762 /* If no block was found, attempt to grow the heap */
764 if (!(heap->flags & HEAP_GROWABLE))
766 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
769 /* make sure that we have a big enough size *committed* to fit another
770 * last free arena in !
771 * So just one heap struct, one first free arena which will eventually
772 * get used, and a second free arena that might get assigned all remaining
773 * free space in HEAP_ShrinkBlock() */
774 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
775 if (total_size < size) return NULL; /* overflow */
777 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
778 max( HEAP_DEF_SIZE, total_size ) )))
781 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
782 subheap, total_size, heap );
784 *ppSubHeap = subheap;
785 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
789 /***********************************************************************
790 * HEAP_IsValidArenaPtr
792 * Check that the pointer is inside the range possible for arenas.
794 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
797 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
798 if (!subheap) return FALSE;
799 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
800 if (subheap != &heap->subheap) return FALSE;
801 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
802 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
807 /***********************************************************************
808 * HEAP_ValidateFreeArena
810 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
812 ARENA_FREE *prev, *next;
813 char *heapEnd = (char *)subheap->base + subheap->size;
815 /* Check for unaligned pointers */
816 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
818 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
822 /* Check magic number */
823 if (pArena->magic != ARENA_FREE_MAGIC)
825 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
828 /* Check size flags */
829 if (!(pArena->size & ARENA_FLAG_FREE) ||
830 (pArena->size & ARENA_FLAG_PREV_FREE))
832 ERR("Heap %p: bad flags %08x for free arena %p\n",
833 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
836 /* Check arena size */
837 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
839 ERR("Heap %p: bad size %08x for free arena %p\n",
840 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
843 /* Check that next pointer is valid */
844 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
845 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
847 ERR("Heap %p: bad next ptr %p for arena %p\n",
848 subheap->heap, next, pArena );
851 /* Check that next arena is free */
852 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
854 ERR("Heap %p: next arena %p invalid for %p\n",
855 subheap->heap, next, pArena );
858 /* Check that prev pointer is valid */
859 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
860 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
862 ERR("Heap %p: bad prev ptr %p for arena %p\n",
863 subheap->heap, prev, pArena );
866 /* Check that prev arena is free */
867 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
869 /* this often means that the prev arena got overwritten
870 * by a memory write before that prev arena */
871 ERR("Heap %p: prev arena %p invalid for %p\n",
872 subheap->heap, prev, pArena );
875 /* Check that next block has PREV_FREE flag */
876 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
878 if (!(*(DWORD *)((char *)(pArena + 1) +
879 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
881 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
882 subheap->heap, pArena );
885 /* Check next block back pointer */
886 if (*((ARENA_FREE **)((char *)(pArena + 1) +
887 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
889 ERR("Heap %p: arena %p has wrong back ptr %p\n",
890 subheap->heap, pArena,
891 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
899 /***********************************************************************
900 * HEAP_ValidateInUseArena
902 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
904 const char *heapEnd = (const char *)subheap->base + subheap->size;
906 /* Check for unaligned pointers */
907 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
909 if ( quiet == NOISY )
911 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
912 if ( TRACE_ON(heap) )
913 HEAP_Dump( subheap->heap );
915 else if ( WARN_ON(heap) )
917 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
918 if ( TRACE_ON(heap) )
919 HEAP_Dump( subheap->heap );
924 /* Check magic number */
925 if (pArena->magic != ARENA_INUSE_MAGIC)
927 if (quiet == NOISY) {
928 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
930 HEAP_Dump( subheap->heap );
931 } else if (WARN_ON(heap)) {
932 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
934 HEAP_Dump( subheap->heap );
938 /* Check size flags */
939 if (pArena->size & ARENA_FLAG_FREE)
941 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
942 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
945 /* Check arena size */
946 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
948 ERR("Heap %p: bad size %08x for in-use arena %p\n",
949 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
952 /* Check next arena PREV_FREE flag */
953 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
954 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
956 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
957 subheap->heap, pArena );
960 /* Check prev free arena */
961 if (pArena->size & ARENA_FLAG_PREV_FREE)
963 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
964 /* Check prev pointer */
965 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
967 ERR("Heap %p: bad back ptr %p for arena %p\n",
968 subheap->heap, pPrev, pArena );
971 /* Check that prev arena is free */
972 if (!(pPrev->size & ARENA_FLAG_FREE) ||
973 (pPrev->magic != ARENA_FREE_MAGIC))
975 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
976 subheap->heap, pPrev, pArena );
979 /* Check that prev arena is really the previous block */
980 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
982 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
983 subheap->heap, pPrev, pArena );
991 /***********************************************************************
992 * HEAP_IsRealArena [Internal]
993 * Validates a block is a valid arena.
999 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1000 DWORD flags, /* [in] Bit flags that control access during operation */
1001 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1002 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1003 * does not complain */
1008 flags &= HEAP_NO_SERIALIZE;
1009 flags |= heapPtr->flags;
1010 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1011 if (!(flags & HEAP_NO_SERIALIZE))
1012 RtlEnterCriticalSection( &heapPtr->critSection );
1014 if (block) /* only check this single memory block */
1016 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1018 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1019 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1022 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1023 else if (WARN_ON(heap))
1024 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1027 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1029 if (!(flags & HEAP_NO_SERIALIZE))
1030 RtlLeaveCriticalSection( &heapPtr->critSection );
1034 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1036 char *ptr = (char *)subheap->base + subheap->headerSize;
1037 while (ptr < (char *)subheap->base + subheap->size)
1039 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1041 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1045 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1049 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1053 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1059 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1064 /***********************************************************************
1065 * RtlCreateHeap (NTDLL.@)
1067 * Create a new Heap.
1070 * flags [I] HEAP_ flags from "winnt.h"
1071 * addr [I] Desired base address
1072 * totalSize [I] Total size of the heap, or 0 for a growable heap
1073 * commitSize [I] Amount of heap space to commit
1074 * unknown [I] Not yet understood
1075 * definition [I] Heap definition
1078 * Success: A HANDLE to the newly created heap.
1079 * Failure: a NULL HANDLE.
1081 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1082 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1086 /* Allocate the heap block */
1090 totalSize = HEAP_DEF_SIZE;
1091 flags |= HEAP_GROWABLE;
1094 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1096 /* link it into the per-process heap list */
1099 HEAP *heapPtr = subheap->heap;
1100 RtlEnterCriticalSection( &processHeap->critSection );
1101 list_add_head( &processHeap->entry, &heapPtr->entry );
1102 RtlLeaveCriticalSection( &processHeap->critSection );
1106 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1107 list_init( &processHeap->entry );
1108 /* make sure structure alignment is correct */
1109 assert( (ULONG_PTR)&processHeap->freeList % ALIGNMENT == 0 );
1112 return (HANDLE)subheap->heap;
1116 /***********************************************************************
1117 * RtlDestroyHeap (NTDLL.@)
1119 * Destroy a Heap created with RtlCreateHeap().
1122 * heap [I] Heap to destroy.
1125 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1126 * Failure: The Heap handle, if heap is the process heap.
1128 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1130 HEAP *heapPtr = HEAP_GetPtr( heap );
1131 SUBHEAP *subheap, *next;
1135 TRACE("%p\n", heap );
1136 if (!heapPtr) return heap;
1138 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1140 /* remove it from the per-process list */
1141 RtlEnterCriticalSection( &processHeap->critSection );
1142 list_remove( &heapPtr->entry );
1143 RtlLeaveCriticalSection( &processHeap->critSection );
1145 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1146 RtlDeleteCriticalSection( &heapPtr->critSection );
1148 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1150 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1151 list_remove( &subheap->entry );
1153 addr = subheap->base;
1154 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1157 addr = heapPtr->subheap.base;
1158 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1163 /***********************************************************************
1164 * RtlAllocateHeap (NTDLL.@)
1166 * Allocate a memory block from a Heap.
1169 * heap [I] Heap to allocate block from
1170 * flags [I] HEAP_ flags from "winnt.h"
1171 * size [I] Size of the memory block to allocate
1174 * Success: A pointer to the newly allocated block
1178 * This call does not SetLastError().
1180 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1183 ARENA_INUSE *pInUse;
1185 HEAP *heapPtr = HEAP_GetPtr( heap );
1186 SIZE_T rounded_size;
1188 /* Validate the parameters */
1190 if (!heapPtr) return NULL;
1191 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1192 flags |= heapPtr->flags;
1193 rounded_size = ROUND_SIZE(size);
1194 if (rounded_size < size) /* overflow */
1196 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1199 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1201 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1202 /* Locate a suitable free block */
1204 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1206 TRACE("(%p,%08x,%08lx): returning NULL\n",
1207 heap, flags, size );
1208 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1209 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1213 /* Remove the arena from the free list */
1215 list_remove( &pArena->entry );
1217 /* Build the in-use arena */
1219 pInUse = (ARENA_INUSE *)pArena;
1221 /* in-use arena is smaller than free arena,
1222 * so we have to add the difference to the size */
1223 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1224 pInUse->magic = ARENA_INUSE_MAGIC;
1226 /* Shrink the block */
1228 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1229 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1231 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1233 if (flags & HEAP_ZERO_MEMORY)
1234 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1236 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1238 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1240 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1241 return (LPVOID)(pInUse + 1);
1245 /***********************************************************************
1246 * RtlFreeHeap (NTDLL.@)
1248 * Free a memory block allocated with RtlAllocateHeap().
1251 * heap [I] Heap that block was allocated from
1252 * flags [I] HEAP_ flags from "winnt.h"
1253 * ptr [I] Block to free
1256 * Success: TRUE, if ptr is NULL or was freed successfully.
1259 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1261 ARENA_INUSE *pInUse;
1265 /* Validate the parameters */
1267 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1269 heapPtr = HEAP_GetPtr( heap );
1272 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1276 flags &= HEAP_NO_SERIALIZE;
1277 flags |= heapPtr->flags;
1278 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1280 /* Some sanity checks */
1282 pInUse = (ARENA_INUSE *)ptr - 1;
1283 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse ))) goto error;
1284 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1285 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1287 /* Turn the block into a free block */
1291 HEAP_MakeInUseBlockFree( subheap, pInUse );
1293 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1295 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1299 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1300 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1301 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1306 /***********************************************************************
1307 * RtlReAllocateHeap (NTDLL.@)
1309 * Change the size of a memory block allocated with RtlAllocateHeap().
1312 * heap [I] Heap that block was allocated from
1313 * flags [I] HEAP_ flags from "winnt.h"
1314 * ptr [I] Block to resize
1315 * size [I] Size of the memory block to allocate
1318 * Success: A pointer to the resized block (which may be different).
1321 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1323 ARENA_INUSE *pArena;
1326 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1328 if (!ptr) return NULL;
1329 if (!(heapPtr = HEAP_GetPtr( heap )))
1331 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1335 /* Validate the parameters */
1337 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1338 HEAP_REALLOC_IN_PLACE_ONLY;
1339 flags |= heapPtr->flags;
1340 rounded_size = ROUND_SIZE(size);
1341 if (rounded_size < size) /* overflow */
1343 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1344 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1347 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1349 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1351 pArena = (ARENA_INUSE *)ptr - 1;
1352 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena ))) goto error;
1353 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1354 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1356 /* Check if we need to grow the block */
1358 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1359 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1360 if (rounded_size > oldBlockSize)
1362 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1363 if ((pNext < (char *)subheap->base + subheap->size) &&
1364 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1365 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1367 /* The next block is free and large enough */
1368 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1369 list_remove( &pFree->entry );
1370 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1371 if (!HEAP_Commit( subheap, pArena, rounded_size ))
1373 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1374 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1375 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1378 notify_free( pArena + 1 );
1379 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1380 notify_alloc( pArena + 1, size, FALSE );
1381 /* FIXME: this is wrong as we may lose old VBits settings */
1382 mark_block_initialized( pArena + 1, oldActualSize );
1384 else /* Do it the hard way */
1387 ARENA_INUSE *pInUse;
1388 SUBHEAP *newsubheap;
1390 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1391 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1393 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1394 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1395 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1399 /* Build the in-use arena */
1401 list_remove( &pNew->entry );
1402 pInUse = (ARENA_INUSE *)pNew;
1403 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1404 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1405 pInUse->magic = ARENA_INUSE_MAGIC;
1406 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1408 mark_block_initialized( pInUse + 1, oldActualSize );
1409 notify_alloc( pInUse + 1, size, FALSE );
1410 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1412 /* Free the previous block */
1414 notify_free( pArena + 1 );
1415 HEAP_MakeInUseBlockFree( subheap, pArena );
1416 subheap = newsubheap;
1422 /* Shrink the block */
1423 notify_free( pArena + 1 );
1424 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1425 notify_alloc( pArena + 1, size, FALSE );
1426 /* FIXME: this is wrong as we may lose old VBits settings */
1427 mark_block_initialized( pArena + 1, size );
1430 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1432 /* Clear the extra bytes if needed */
1434 if ((pArena->size & ARENA_SIZE_MASK) > oldActualSize)
1436 if (flags & HEAP_ZERO_MEMORY)
1437 clear_block( (char *)(pArena + 1) + oldActualSize,
1438 (pArena->size & ARENA_SIZE_MASK) - oldActualSize );
1440 mark_block_uninitialized( (char *)(pArena + 1) + oldActualSize,
1441 (pArena->size & ARENA_SIZE_MASK) - oldActualSize );
1444 /* Return the new arena */
1446 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1448 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1449 return (LPVOID)(pArena + 1);
1452 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1453 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1454 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1459 /***********************************************************************
1460 * RtlCompactHeap (NTDLL.@)
1462 * Compact the free space in a Heap.
1465 * heap [I] Heap that block was allocated from
1466 * flags [I] HEAP_ flags from "winnt.h"
1469 * The number of bytes compacted.
1472 * This function is a harmless stub.
1474 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1476 static BOOL reported;
1477 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1482 /***********************************************************************
1483 * RtlLockHeap (NTDLL.@)
1488 * heap [I] Heap to lock
1491 * Success: TRUE. The Heap is locked.
1492 * Failure: FALSE, if heap is invalid.
1494 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1496 HEAP *heapPtr = HEAP_GetPtr( heap );
1497 if (!heapPtr) return FALSE;
1498 RtlEnterCriticalSection( &heapPtr->critSection );
1503 /***********************************************************************
1504 * RtlUnlockHeap (NTDLL.@)
1509 * heap [I] Heap to unlock
1512 * Success: TRUE. The Heap is unlocked.
1513 * Failure: FALSE, if heap is invalid.
1515 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1517 HEAP *heapPtr = HEAP_GetPtr( heap );
1518 if (!heapPtr) return FALSE;
1519 RtlLeaveCriticalSection( &heapPtr->critSection );
1524 /***********************************************************************
1525 * RtlSizeHeap (NTDLL.@)
1527 * Get the actual size of a memory block allocated from a Heap.
1530 * heap [I] Heap that block was allocated from
1531 * flags [I] HEAP_ flags from "winnt.h"
1532 * ptr [I] Block to get the size of
1535 * Success: The size of the block.
1536 * Failure: -1, heap or ptr are invalid.
1539 * The size may be bigger than what was passed to RtlAllocateHeap().
1541 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1544 HEAP *heapPtr = HEAP_GetPtr( heap );
1548 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1551 flags &= HEAP_NO_SERIALIZE;
1552 flags |= heapPtr->flags;
1553 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1554 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1556 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1561 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1562 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1564 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1566 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1571 /***********************************************************************
1572 * RtlValidateHeap (NTDLL.@)
1574 * Determine if a block is a valid allocation from a heap.
1577 * heap [I] Heap that block was allocated from
1578 * flags [I] HEAP_ flags from "winnt.h"
1579 * ptr [I] Block to check
1582 * Success: TRUE. The block was allocated from heap.
1583 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1585 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1587 HEAP *heapPtr = HEAP_GetPtr( heap );
1588 if (!heapPtr) return FALSE;
1589 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1593 /***********************************************************************
1594 * RtlWalkHeap (NTDLL.@)
1597 * The PROCESS_HEAP_ENTRY flag values seem different between this
1598 * function and HeapWalk(). To be checked.
1600 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1602 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1603 HEAP *heapPtr = HEAP_GetPtr(heap);
1604 SUBHEAP *sub, *currentheap = NULL;
1607 int region_index = 0;
1609 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1611 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1613 /* set ptr to the next arena to be examined */
1615 if (!entry->lpData) /* first call (init) ? */
1617 TRACE("begin walking of heap %p.\n", heap);
1618 currentheap = &heapPtr->subheap;
1619 ptr = (char*)currentheap->base + currentheap->headerSize;
1623 ptr = entry->lpData;
1624 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1626 if ((ptr >= (char *)sub->base) &&
1627 (ptr < (char *)sub->base + sub->size))
1634 if (currentheap == NULL)
1636 ERR("no matching subheap found, shouldn't happen !\n");
1637 ret = STATUS_NO_MORE_ENTRIES;
1641 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1643 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1644 ptr += pArena->size & ARENA_SIZE_MASK;
1646 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1648 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1649 ptr += pArena->size & ARENA_SIZE_MASK;
1652 ptr += entry->cbData; /* point to next arena */
1654 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1655 { /* proceed with next subheap */
1656 struct list *next = list_next( &heapPtr->subheap_list, ¤theap->entry );
1658 { /* successfully finished */
1659 TRACE("end reached.\n");
1660 ret = STATUS_NO_MORE_ENTRIES;
1663 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1664 ptr = (char *)currentheap->base + currentheap->headerSize;
1669 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1671 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1673 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1675 entry->lpData = pArena + 1;
1676 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1677 entry->cbOverhead = sizeof(ARENA_FREE);
1678 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1682 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1684 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1686 entry->lpData = pArena + 1;
1687 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1688 entry->cbOverhead = sizeof(ARENA_INUSE);
1689 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1690 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1691 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1694 entry->iRegionIndex = region_index;
1696 /* first element of heap ? */
1697 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1699 entry->wFlags |= PROCESS_HEAP_REGION;
1700 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1701 entry->u.Region.dwUnCommittedSize =
1702 currentheap->size - currentheap->commitSize;
1703 entry->u.Region.lpFirstBlock = /* first valid block */
1704 (char *)currentheap->base + currentheap->headerSize;
1705 entry->u.Region.lpLastBlock = /* first invalid block */
1706 (char *)currentheap->base + currentheap->size;
1708 ret = STATUS_SUCCESS;
1709 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1712 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1717 /***********************************************************************
1718 * RtlGetProcessHeaps (NTDLL.@)
1720 * Get the Heaps belonging to the current process.
1723 * count [I] size of heaps
1724 * heaps [O] Destination array for heap HANDLE's
1727 * Success: The number of Heaps allocated by the process.
1730 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1732 ULONG total = 1; /* main heap */
1735 RtlEnterCriticalSection( &processHeap->critSection );
1736 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1739 *heaps++ = processHeap;
1740 LIST_FOR_EACH( ptr, &processHeap->entry )
1741 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1743 RtlLeaveCriticalSection( &processHeap->critSection );