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 #ifdef VALGRIND_MAKE_NOACCESS
144 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
148 /* mark a block of memory as initialized for debugging purposes */
149 static inline void mark_block_initialized( void *ptr, SIZE_T size )
151 #ifdef VALGRIND_MAKE_READABLE
152 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
156 /* mark a block of memory as uninitialized for debugging purposes */
157 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
159 #ifdef VALGRIND_MAKE_WRITABLE
160 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
162 if (TRACE_ON(heap) || WARN_ON(heap))
164 memset( ptr, ARENA_INUSE_FILLER, size );
165 #ifdef VALGRIND_MAKE_WRITABLE
166 /* make it uninitialized to valgrind again */
167 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
172 /* clear contents of a block of memory */
173 static inline void clear_block( void *ptr, SIZE_T size )
175 mark_block_initialized( ptr, size );
176 memset( ptr, 0, size );
179 /* notify that a new block of memory has been allocated for debugging purposes */
180 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
182 #ifdef VALGRIND_MALLOCLIKE_BLOCK
183 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
187 /* notify that a block of memory has been freed for debugging purposes */
188 static inline void notify_free( void *ptr )
190 #ifdef VALGRIND_FREELIKE_BLOCK
191 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
195 /* locate a free list entry of the appropriate size */
196 /* size is the size of the whole block including the arena header */
197 static inline unsigned int get_freelist_index( SIZE_T size )
201 size -= sizeof(ARENA_FREE);
202 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
206 /* get the memory protection type to use for a given heap */
207 static inline ULONG get_protection_type( DWORD flags )
209 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
212 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
214 0, 0, NULL, /* will be set later */
215 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
216 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
220 /***********************************************************************
223 static void HEAP_Dump( HEAP *heap )
229 DPRINTF( "Heap: %p\n", heap );
230 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
231 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
233 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
234 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
235 DPRINTF( "%p free %08lx prev=%p next=%p\n",
236 &heap->freeList[i].arena, HEAP_freeListSizes[i],
237 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
238 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
240 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
242 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
243 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
244 subheap, subheap->base, subheap->size, subheap->commitSize );
246 DPRINTF( "\n Block Arena Stat Size Id\n" );
247 ptr = (char *)subheap->base + subheap->headerSize;
248 while (ptr < (char *)subheap->base + subheap->size)
250 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
252 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
253 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
254 pArena, pArena->magic,
255 pArena->size & ARENA_SIZE_MASK,
256 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
257 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
258 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
259 arenaSize += sizeof(ARENA_FREE);
260 freeSize += pArena->size & ARENA_SIZE_MASK;
262 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
264 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
265 DPRINTF( "%p %08x Used %08x back=%p\n",
266 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
267 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
268 arenaSize += sizeof(ARENA_INUSE);
269 usedSize += pArena->size & ARENA_SIZE_MASK;
273 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
274 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
275 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
276 arenaSize += sizeof(ARENA_INUSE);
277 usedSize += pArena->size & ARENA_SIZE_MASK;
280 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
281 subheap->size, subheap->commitSize, freeSize, usedSize,
282 arenaSize, (arenaSize * 100) / subheap->size );
287 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
290 TRACE( "Dumping entry %p\n", entry );
291 TRACE( "lpData\t\t: %p\n", entry->lpData );
292 TRACE( "cbData\t\t: %08x\n", entry->cbData);
293 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
294 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
295 TRACE( "WFlags\t\t: ");
296 if (entry->wFlags & PROCESS_HEAP_REGION)
297 TRACE( "PROCESS_HEAP_REGION ");
298 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
299 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
300 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
301 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
302 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
303 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
304 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
305 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
306 rem_flags = entry->wFlags &
307 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
308 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
309 PROCESS_HEAP_ENTRY_DDESHARE);
311 TRACE( "Unknown %08x", rem_flags);
313 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
314 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
317 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
319 if (entry->wFlags & PROCESS_HEAP_REGION)
321 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
322 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
323 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
324 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
328 /***********************************************************************
331 * Pointer to the heap
334 static HEAP *HEAP_GetPtr(
335 HANDLE heap /* [in] Handle to the heap */
337 HEAP *heapPtr = (HEAP *)heap;
338 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
340 ERR("Invalid heap %p!\n", heap );
343 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
345 HEAP_Dump( heapPtr );
353 /***********************************************************************
354 * HEAP_InsertFreeBlock
356 * Insert a free block into the free list.
358 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
360 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
363 /* insert at end of free list, i.e. before the next free list entry */
365 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
366 list_add_before( &pEntry->arena.entry, &pArena->entry );
370 /* insert at head of free list */
371 list_add_after( &pEntry->arena.entry, &pArena->entry );
373 pArena->size |= ARENA_FLAG_FREE;
377 /***********************************************************************
379 * Find the sub-heap containing a given address.
385 static SUBHEAP *HEAP_FindSubHeap(
386 const HEAP *heap, /* [in] Heap pointer */
387 LPCVOID ptr ) /* [in] Address */
390 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
391 if (((const char *)ptr >= (const char *)sub->base) &&
392 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
398 /***********************************************************************
401 * Make sure the heap storage is committed for a given size in the specified arena.
403 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
405 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
406 SIZE_T size = (char *)ptr - (char *)subheap->base;
407 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
408 if (size > subheap->size) size = subheap->size;
409 if (size <= subheap->commitSize) return TRUE;
410 size -= subheap->commitSize;
411 ptr = (char *)subheap->base + subheap->commitSize;
412 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
413 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
415 WARN("Could not commit %08lx bytes at %p for heap %p\n",
416 size, ptr, subheap->heap );
419 subheap->commitSize += size;
424 /***********************************************************************
427 * If possible, decommit the heap storage from (including) 'ptr'.
429 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
432 SIZE_T decommit_size;
433 SIZE_T size = (char *)ptr - (char *)subheap->base;
435 /* round to next block and add one full block */
436 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
437 if (size >= subheap->commitSize) return TRUE;
438 decommit_size = subheap->commitSize - size;
439 addr = (char *)subheap->base + size;
441 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
443 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
444 decommit_size, (char *)subheap->base + size, subheap->heap );
447 subheap->commitSize -= decommit_size;
452 /***********************************************************************
453 * HEAP_CreateFreeBlock
455 * Create a free block at a specified address. 'size' is the size of the
456 * whole block, including the new arena.
458 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
464 /* Create a free arena */
465 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
466 pFree = (ARENA_FREE *)ptr;
467 pFree->magic = ARENA_FREE_MAGIC;
469 /* If debugging, erase the freed block content */
471 pEnd = (char *)ptr + size;
472 if (pEnd > (char *)subheap->base + subheap->commitSize)
473 pEnd = (char *)subheap->base + subheap->commitSize;
474 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
476 /* Check if next block is free also */
478 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
479 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
481 /* Remove the next arena from the free list */
482 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
483 list_remove( &pNext->entry );
484 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
485 mark_block_free( pNext, sizeof(ARENA_FREE) );
488 /* Set the next block PREV_FREE flag and pointer */
490 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
493 DWORD *pNext = (DWORD *)((char *)ptr + size);
494 *pNext |= ARENA_FLAG_PREV_FREE;
495 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
496 *((ARENA_FREE **)pNext - 1) = pFree;
499 /* Last, insert the new block into the free list */
501 pFree->size = size - sizeof(*pFree);
502 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
506 /***********************************************************************
507 * HEAP_MakeInUseBlockFree
509 * Turn an in-use block into a free block. Can also decommit the end of
510 * the heap, and possibly even free the sub-heap altogether.
512 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
515 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
517 /* Check if we can merge with previous block */
519 if (pArena->size & ARENA_FLAG_PREV_FREE)
521 pFree = *((ARENA_FREE **)pArena - 1);
522 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
523 /* Remove it from the free list */
524 list_remove( &pFree->entry );
526 else pFree = (ARENA_FREE *)pArena;
528 /* Create a free block */
530 HEAP_CreateFreeBlock( subheap, pFree, size );
531 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
532 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
533 return; /* Not the last block, so nothing more to do */
535 /* Free the whole sub-heap if it's empty and not the original one */
537 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
538 (subheap != &subheap->heap->subheap))
541 void *addr = subheap->base;
542 /* Remove the free block from the list */
543 list_remove( &pFree->entry );
544 /* Remove the subheap from the list */
545 list_remove( &subheap->entry );
546 /* Free the memory */
548 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
552 /* Decommit the end of the heap */
554 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
558 /***********************************************************************
561 * Shrink an in-use block.
563 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
565 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
567 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
568 (pArena->size & ARENA_SIZE_MASK) - size );
569 /* assign size plus previous arena flags */
570 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
574 /* Turn off PREV_FREE flag in next block */
575 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
576 if (pNext < (char *)subheap->base + subheap->size)
577 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
581 /***********************************************************************
584 static SUBHEAP *HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
585 SIZE_T commitSize, SIZE_T totalSize )
588 FREE_LIST_ENTRY *pEntry;
593 if (flags & HEAP_SHARED)
594 commitSize = totalSize; /* always commit everything in a shared heap */
595 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
596 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
598 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
604 /* If this is a secondary subheap, insert it into list */
606 subheap = (SUBHEAP *)address;
607 subheap->base = address;
608 subheap->heap = heap;
609 subheap->size = totalSize;
610 subheap->commitSize = commitSize;
611 subheap->magic = SUBHEAP_MAGIC;
612 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
613 list_add_head( &heap->subheap_list, &subheap->entry );
617 /* If this is a primary subheap, initialize main heap */
619 heap = (HEAP *)address;
621 heap->magic = HEAP_MAGIC;
622 list_init( &heap->subheap_list );
624 subheap = &heap->subheap;
625 subheap->base = address;
626 subheap->heap = heap;
627 subheap->size = totalSize;
628 subheap->commitSize = commitSize;
629 subheap->magic = SUBHEAP_MAGIC;
630 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
631 list_add_head( &heap->subheap_list, &subheap->entry );
633 /* Build the free lists */
635 list_init( &heap->freeList[0].arena.entry );
636 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
638 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
639 pEntry->arena.magic = ARENA_FREE_MAGIC;
640 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
643 /* Initialize critical section */
645 if (!processHeap) /* do it by hand to avoid memory allocations */
647 heap->critSection.DebugInfo = &process_heap_critsect_debug;
648 heap->critSection.LockCount = -1;
649 heap->critSection.RecursionCount = 0;
650 heap->critSection.OwningThread = 0;
651 heap->critSection.LockSemaphore = 0;
652 heap->critSection.SpinCount = 0;
653 process_heap_critsect_debug.CriticalSection = &heap->critSection;
657 RtlInitializeCriticalSection( &heap->critSection );
658 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
661 if (flags & HEAP_SHARED)
663 /* let's assume that only one thread at a time will try to do this */
664 HANDLE sem = heap->critSection.LockSemaphore;
665 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
667 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
668 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
669 heap->critSection.LockSemaphore = sem;
670 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
671 heap->critSection.DebugInfo = NULL;
675 /* Create the first free block */
677 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
678 subheap->size - subheap->headerSize );
683 /***********************************************************************
686 * Create a sub-heap of the given size.
687 * If heap == NULL, creates a main heap.
689 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
690 SIZE_T commitSize, SIZE_T totalSize )
692 LPVOID address = base;
695 /* round-up sizes on a 64K boundary */
696 totalSize = (totalSize + 0xffff) & 0xffff0000;
697 commitSize = (commitSize + 0xffff) & 0xffff0000;
698 if (!commitSize) commitSize = 0x10000;
699 if (totalSize < commitSize) totalSize = commitSize;
703 /* allocate the memory block */
704 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
705 MEM_RESERVE, get_protection_type( flags ) ))
707 WARN("Could not allocate %08lx bytes\n", totalSize );
712 /* Initialize subheap */
714 if (!(ret = HEAP_InitSubHeap( heap, address, flags, commitSize, totalSize )))
717 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
723 /***********************************************************************
726 * Find a free block at least as large as the requested size, and make sure
727 * the requested size is committed.
729 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
730 SUBHEAP **ppSubHeap )
735 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
737 /* Find a suitable free list, and in it find a block large enough */
739 ptr = &pEntry->arena.entry;
740 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
742 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
743 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
744 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
745 if (arena_size >= size)
747 subheap = HEAP_FindSubHeap( heap, pArena );
748 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
749 *ppSubHeap = subheap;
754 /* If no block was found, attempt to grow the heap */
756 if (!(heap->flags & HEAP_GROWABLE))
758 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
761 /* make sure that we have a big enough size *committed* to fit another
762 * last free arena in !
763 * So just one heap struct, one first free arena which will eventually
764 * get used, and a second free arena that might get assigned all remaining
765 * free space in HEAP_ShrinkBlock() */
766 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
767 if (total_size < size) return NULL; /* overflow */
769 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
770 max( HEAP_DEF_SIZE, total_size ) )))
773 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
774 subheap, total_size, heap );
776 *ppSubHeap = subheap;
777 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
781 /***********************************************************************
782 * HEAP_IsValidArenaPtr
784 * Check that the pointer is inside the range possible for arenas.
786 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
789 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
790 if (!subheap) return FALSE;
791 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
792 if (subheap != &heap->subheap) return FALSE;
793 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
794 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
799 /***********************************************************************
800 * HEAP_ValidateFreeArena
802 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
804 ARENA_FREE *prev, *next;
805 char *heapEnd = (char *)subheap->base + subheap->size;
807 /* Check for unaligned pointers */
808 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
810 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
814 /* Check magic number */
815 if (pArena->magic != ARENA_FREE_MAGIC)
817 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
820 /* Check size flags */
821 if (!(pArena->size & ARENA_FLAG_FREE) ||
822 (pArena->size & ARENA_FLAG_PREV_FREE))
824 ERR("Heap %p: bad flags %08x for free arena %p\n",
825 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
828 /* Check arena size */
829 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
831 ERR("Heap %p: bad size %08x for free arena %p\n",
832 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
835 /* Check that next pointer is valid */
836 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
837 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
839 ERR("Heap %p: bad next ptr %p for arena %p\n",
840 subheap->heap, next, pArena );
843 /* Check that next arena is free */
844 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
846 ERR("Heap %p: next arena %p invalid for %p\n",
847 subheap->heap, next, pArena );
850 /* Check that prev pointer is valid */
851 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
852 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
854 ERR("Heap %p: bad prev ptr %p for arena %p\n",
855 subheap->heap, prev, pArena );
858 /* Check that prev arena is free */
859 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
861 /* this often means that the prev arena got overwritten
862 * by a memory write before that prev arena */
863 ERR("Heap %p: prev arena %p invalid for %p\n",
864 subheap->heap, prev, pArena );
867 /* Check that next block has PREV_FREE flag */
868 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
870 if (!(*(DWORD *)((char *)(pArena + 1) +
871 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
873 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
874 subheap->heap, pArena );
877 /* Check next block back pointer */
878 if (*((ARENA_FREE **)((char *)(pArena + 1) +
879 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
881 ERR("Heap %p: arena %p has wrong back ptr %p\n",
882 subheap->heap, pArena,
883 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
891 /***********************************************************************
892 * HEAP_ValidateInUseArena
894 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
896 const char *heapEnd = (const char *)subheap->base + subheap->size;
898 /* Check for unaligned pointers */
899 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
901 if ( quiet == NOISY )
903 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
904 if ( TRACE_ON(heap) )
905 HEAP_Dump( subheap->heap );
907 else if ( WARN_ON(heap) )
909 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
910 if ( TRACE_ON(heap) )
911 HEAP_Dump( subheap->heap );
916 /* Check magic number */
917 if (pArena->magic != ARENA_INUSE_MAGIC)
919 if (quiet == NOISY) {
920 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
922 HEAP_Dump( subheap->heap );
923 } else if (WARN_ON(heap)) {
924 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
926 HEAP_Dump( subheap->heap );
930 /* Check size flags */
931 if (pArena->size & ARENA_FLAG_FREE)
933 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
934 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
937 /* Check arena size */
938 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
940 ERR("Heap %p: bad size %08x for in-use arena %p\n",
941 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
944 /* Check next arena PREV_FREE flag */
945 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
946 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
948 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
949 subheap->heap, pArena );
952 /* Check prev free arena */
953 if (pArena->size & ARENA_FLAG_PREV_FREE)
955 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
956 /* Check prev pointer */
957 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
959 ERR("Heap %p: bad back ptr %p for arena %p\n",
960 subheap->heap, pPrev, pArena );
963 /* Check that prev arena is free */
964 if (!(pPrev->size & ARENA_FLAG_FREE) ||
965 (pPrev->magic != ARENA_FREE_MAGIC))
967 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
968 subheap->heap, pPrev, pArena );
971 /* Check that prev arena is really the previous block */
972 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
974 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
975 subheap->heap, pPrev, pArena );
983 /***********************************************************************
984 * HEAP_IsRealArena [Internal]
985 * Validates a block is a valid arena.
991 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
992 DWORD flags, /* [in] Bit flags that control access during operation */
993 LPCVOID block, /* [in] Optional pointer to memory block to validate */
994 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
995 * does not complain */
1000 flags &= HEAP_NO_SERIALIZE;
1001 flags |= heapPtr->flags;
1002 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1003 if (!(flags & HEAP_NO_SERIALIZE))
1004 RtlEnterCriticalSection( &heapPtr->critSection );
1006 if (block) /* only check this single memory block */
1008 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1010 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1011 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1014 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1015 else if (WARN_ON(heap))
1016 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1019 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1021 if (!(flags & HEAP_NO_SERIALIZE))
1022 RtlLeaveCriticalSection( &heapPtr->critSection );
1026 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1028 char *ptr = (char *)subheap->base + subheap->headerSize;
1029 while (ptr < (char *)subheap->base + subheap->size)
1031 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1033 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1037 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1041 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1045 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1051 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1056 /***********************************************************************
1057 * RtlCreateHeap (NTDLL.@)
1059 * Create a new Heap.
1062 * flags [I] HEAP_ flags from "winnt.h"
1063 * addr [I] Desired base address
1064 * totalSize [I] Total size of the heap, or 0 for a growable heap
1065 * commitSize [I] Amount of heap space to commit
1066 * unknown [I] Not yet understood
1067 * definition [I] Heap definition
1070 * Success: A HANDLE to the newly created heap.
1071 * Failure: a NULL HANDLE.
1073 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1074 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1078 /* Allocate the heap block */
1082 totalSize = HEAP_DEF_SIZE;
1083 flags |= HEAP_GROWABLE;
1086 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1088 /* link it into the per-process heap list */
1091 HEAP *heapPtr = subheap->heap;
1092 RtlEnterCriticalSection( &processHeap->critSection );
1093 list_add_head( &processHeap->entry, &heapPtr->entry );
1094 RtlLeaveCriticalSection( &processHeap->critSection );
1098 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1099 list_init( &processHeap->entry );
1100 /* make sure structure alignment is correct */
1101 assert( (ULONG_PTR)&processHeap->freeList % ALIGNMENT == 0 );
1104 return (HANDLE)subheap->heap;
1108 /***********************************************************************
1109 * RtlDestroyHeap (NTDLL.@)
1111 * Destroy a Heap created with RtlCreateHeap().
1114 * heap [I] Heap to destroy.
1117 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1118 * Failure: The Heap handle, if heap is the process heap.
1120 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1122 HEAP *heapPtr = HEAP_GetPtr( heap );
1123 SUBHEAP *subheap, *next;
1127 TRACE("%p\n", heap );
1128 if (!heapPtr) return heap;
1130 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1132 /* remove it from the per-process list */
1133 RtlEnterCriticalSection( &processHeap->critSection );
1134 list_remove( &heapPtr->entry );
1135 RtlLeaveCriticalSection( &processHeap->critSection );
1137 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1138 RtlDeleteCriticalSection( &heapPtr->critSection );
1140 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1142 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1143 list_remove( &subheap->entry );
1145 addr = subheap->base;
1146 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1149 addr = heapPtr->subheap.base;
1150 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1155 /***********************************************************************
1156 * RtlAllocateHeap (NTDLL.@)
1158 * Allocate a memory block from a Heap.
1161 * heap [I] Heap to allocate block from
1162 * flags [I] HEAP_ flags from "winnt.h"
1163 * size [I] Size of the memory block to allocate
1166 * Success: A pointer to the newly allocated block
1170 * This call does not SetLastError().
1172 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1175 ARENA_INUSE *pInUse;
1177 HEAP *heapPtr = HEAP_GetPtr( heap );
1178 SIZE_T rounded_size;
1180 /* Validate the parameters */
1182 if (!heapPtr) return NULL;
1183 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1184 flags |= heapPtr->flags;
1185 rounded_size = ROUND_SIZE(size);
1186 if (rounded_size < size) /* overflow */
1188 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1191 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1193 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1194 /* Locate a suitable free block */
1196 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1198 TRACE("(%p,%08x,%08lx): returning NULL\n",
1199 heap, flags, size );
1200 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1201 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1205 /* Remove the arena from the free list */
1207 list_remove( &pArena->entry );
1209 /* Build the in-use arena */
1211 pInUse = (ARENA_INUSE *)pArena;
1213 /* in-use arena is smaller than free arena,
1214 * so we have to add the difference to the size */
1215 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1216 pInUse->magic = ARENA_INUSE_MAGIC;
1218 /* Shrink the block */
1220 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1221 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1223 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1225 if (flags & HEAP_ZERO_MEMORY)
1226 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1228 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1230 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1232 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1233 return (LPVOID)(pInUse + 1);
1237 /***********************************************************************
1238 * RtlFreeHeap (NTDLL.@)
1240 * Free a memory block allocated with RtlAllocateHeap().
1243 * heap [I] Heap that block was allocated from
1244 * flags [I] HEAP_ flags from "winnt.h"
1245 * ptr [I] Block to free
1248 * Success: TRUE, if ptr is NULL or was freed successfully.
1251 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1253 ARENA_INUSE *pInUse;
1257 /* Validate the parameters */
1259 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1261 heapPtr = HEAP_GetPtr( heap );
1264 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1268 flags &= HEAP_NO_SERIALIZE;
1269 flags |= heapPtr->flags;
1270 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1272 /* Some sanity checks */
1274 pInUse = (ARENA_INUSE *)ptr - 1;
1275 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse ))) goto error;
1276 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1277 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1279 /* Turn the block into a free block */
1283 HEAP_MakeInUseBlockFree( subheap, pInUse );
1285 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1287 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1291 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1292 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1293 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1298 /***********************************************************************
1299 * RtlReAllocateHeap (NTDLL.@)
1301 * Change the size of a memory block allocated with RtlAllocateHeap().
1304 * heap [I] Heap that block was allocated from
1305 * flags [I] HEAP_ flags from "winnt.h"
1306 * ptr [I] Block to resize
1307 * size [I] Size of the memory block to allocate
1310 * Success: A pointer to the resized block (which may be different).
1313 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1315 ARENA_INUSE *pArena;
1318 SIZE_T oldSize, rounded_size;
1320 if (!ptr) return NULL;
1321 if (!(heapPtr = HEAP_GetPtr( heap )))
1323 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1327 /* Validate the parameters */
1329 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1330 HEAP_REALLOC_IN_PLACE_ONLY;
1331 flags |= heapPtr->flags;
1332 rounded_size = ROUND_SIZE(size);
1333 if (rounded_size < size) /* overflow */
1335 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1336 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1339 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1341 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1343 pArena = (ARENA_INUSE *)ptr - 1;
1344 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena ))) goto error;
1345 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1346 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1348 /* Check if we need to grow the block */
1350 oldSize = (pArena->size & ARENA_SIZE_MASK);
1351 if (rounded_size > oldSize)
1353 char *pNext = (char *)(pArena + 1) + oldSize;
1354 if ((pNext < (char *)subheap->base + subheap->size) &&
1355 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1356 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1358 /* The next block is free and large enough */
1359 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1360 list_remove( &pFree->entry );
1361 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1362 if (!HEAP_Commit( subheap, pArena, rounded_size ))
1364 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1365 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1366 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1369 notify_free( pArena + 1 );
1370 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1371 notify_alloc( pArena + 1, size, FALSE );
1372 /* FIXME: this is wrong as we may lose old VBits settings */
1373 mark_block_initialized( pArena + 1, oldSize );
1375 else /* Do it the hard way */
1378 ARENA_INUSE *pInUse;
1379 SUBHEAP *newsubheap;
1381 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1382 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1384 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1385 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1386 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1390 /* Build the in-use arena */
1392 list_remove( &pNew->entry );
1393 pInUse = (ARENA_INUSE *)pNew;
1394 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1395 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1396 pInUse->magic = ARENA_INUSE_MAGIC;
1397 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1398 mark_block_initialized( pInUse + 1, oldSize );
1399 notify_alloc( pInUse + 1, size, FALSE );
1400 memcpy( pInUse + 1, pArena + 1, oldSize );
1402 /* Free the previous block */
1404 notify_free( pArena + 1 );
1405 HEAP_MakeInUseBlockFree( subheap, pArena );
1406 subheap = newsubheap;
1412 /* Shrink the block */
1413 notify_free( pArena + 1 );
1414 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1415 notify_alloc( pArena + 1, size, FALSE );
1416 /* FIXME: this is wrong as we may lose old VBits settings */
1417 mark_block_initialized( pArena + 1, size );
1420 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1422 /* Clear the extra bytes if needed */
1424 if (rounded_size > oldSize)
1426 if (flags & HEAP_ZERO_MEMORY)
1427 clear_block( (char *)(pArena + 1) + oldSize,
1428 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1430 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1431 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1434 /* Return the new arena */
1436 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1438 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1439 return (LPVOID)(pArena + 1);
1442 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1443 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1444 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1449 /***********************************************************************
1450 * RtlCompactHeap (NTDLL.@)
1452 * Compact the free space in a Heap.
1455 * heap [I] Heap that block was allocated from
1456 * flags [I] HEAP_ flags from "winnt.h"
1459 * The number of bytes compacted.
1462 * This function is a harmless stub.
1464 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1466 static BOOL reported;
1467 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1472 /***********************************************************************
1473 * RtlLockHeap (NTDLL.@)
1478 * heap [I] Heap to lock
1481 * Success: TRUE. The Heap is locked.
1482 * Failure: FALSE, if heap is invalid.
1484 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1486 HEAP *heapPtr = HEAP_GetPtr( heap );
1487 if (!heapPtr) return FALSE;
1488 RtlEnterCriticalSection( &heapPtr->critSection );
1493 /***********************************************************************
1494 * RtlUnlockHeap (NTDLL.@)
1499 * heap [I] Heap to unlock
1502 * Success: TRUE. The Heap is unlocked.
1503 * Failure: FALSE, if heap is invalid.
1505 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1507 HEAP *heapPtr = HEAP_GetPtr( heap );
1508 if (!heapPtr) return FALSE;
1509 RtlLeaveCriticalSection( &heapPtr->critSection );
1514 /***********************************************************************
1515 * RtlSizeHeap (NTDLL.@)
1517 * Get the actual size of a memory block allocated from a Heap.
1520 * heap [I] Heap that block was allocated from
1521 * flags [I] HEAP_ flags from "winnt.h"
1522 * ptr [I] Block to get the size of
1525 * Success: The size of the block.
1526 * Failure: -1, heap or ptr are invalid.
1529 * The size may be bigger than what was passed to RtlAllocateHeap().
1531 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1534 HEAP *heapPtr = HEAP_GetPtr( heap );
1538 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1541 flags &= HEAP_NO_SERIALIZE;
1542 flags |= heapPtr->flags;
1543 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1544 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1546 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1551 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1552 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1554 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1556 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1561 /***********************************************************************
1562 * RtlValidateHeap (NTDLL.@)
1564 * Determine if a block is a valid allocation from a heap.
1567 * heap [I] Heap that block was allocated from
1568 * flags [I] HEAP_ flags from "winnt.h"
1569 * ptr [I] Block to check
1572 * Success: TRUE. The block was allocated from heap.
1573 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1575 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1577 HEAP *heapPtr = HEAP_GetPtr( heap );
1578 if (!heapPtr) return FALSE;
1579 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1583 /***********************************************************************
1584 * RtlWalkHeap (NTDLL.@)
1587 * The PROCESS_HEAP_ENTRY flag values seem different between this
1588 * function and HeapWalk(). To be checked.
1590 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1592 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1593 HEAP *heapPtr = HEAP_GetPtr(heap);
1594 SUBHEAP *sub, *currentheap = NULL;
1597 int region_index = 0;
1599 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1601 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1603 /* set ptr to the next arena to be examined */
1605 if (!entry->lpData) /* first call (init) ? */
1607 TRACE("begin walking of heap %p.\n", heap);
1608 currentheap = &heapPtr->subheap;
1609 ptr = (char*)currentheap->base + currentheap->headerSize;
1613 ptr = entry->lpData;
1614 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1616 if (((char *)ptr >= (char *)sub->base) &&
1617 ((char *)ptr < (char *)sub->base + sub->size))
1624 if (currentheap == NULL)
1626 ERR("no matching subheap found, shouldn't happen !\n");
1627 ret = STATUS_NO_MORE_ENTRIES;
1631 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1633 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1634 ptr += pArena->size & ARENA_SIZE_MASK;
1636 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1638 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1639 ptr += pArena->size & ARENA_SIZE_MASK;
1642 ptr += entry->cbData; /* point to next arena */
1644 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1645 { /* proceed with next subheap */
1646 struct list *next = list_next( &heapPtr->subheap_list, ¤theap->entry );
1648 { /* successfully finished */
1649 TRACE("end reached.\n");
1650 ret = STATUS_NO_MORE_ENTRIES;
1653 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1654 ptr = (char *)currentheap->base + currentheap->headerSize;
1659 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1661 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1663 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1665 entry->lpData = pArena + 1;
1666 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1667 entry->cbOverhead = sizeof(ARENA_FREE);
1668 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1672 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1674 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1676 entry->lpData = pArena + 1;
1677 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1678 entry->cbOverhead = sizeof(ARENA_INUSE);
1679 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1680 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1681 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1684 entry->iRegionIndex = region_index;
1686 /* first element of heap ? */
1687 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1689 entry->wFlags |= PROCESS_HEAP_REGION;
1690 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1691 entry->u.Region.dwUnCommittedSize =
1692 currentheap->size - currentheap->commitSize;
1693 entry->u.Region.lpFirstBlock = /* first valid block */
1694 (char *)currentheap->base + currentheap->headerSize;
1695 entry->u.Region.lpLastBlock = /* first invalid block */
1696 (char *)currentheap->base + currentheap->size;
1698 ret = STATUS_SUCCESS;
1699 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1702 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1707 /***********************************************************************
1708 * RtlGetProcessHeaps (NTDLL.@)
1710 * Get the Heaps belonging to the current process.
1713 * count [I] size of heaps
1714 * heaps [O] Destination array for heap HANDLE's
1717 * Success: The number of Heaps allocated by the process.
1720 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1722 ULONG total = 1; /* main heap */
1725 RtlEnterCriticalSection( &processHeap->critSection );
1726 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1729 *heaps++ = processHeap;
1730 LIST_FOR_EACH( ptr, &processHeap->entry )
1731 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1733 RtlLeaveCriticalSection( &processHeap->critSection );