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 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 free %08x prev=%p next=%p\n",
254 pArena, pArena->size & ARENA_SIZE_MASK,
255 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
256 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
257 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
258 arenaSize += sizeof(ARENA_FREE);
259 freeSize += pArena->size & ARENA_SIZE_MASK;
261 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
263 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
264 DPRINTF( "%p Used %08x back=%p\n",
265 pArena, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
266 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
267 arenaSize += sizeof(ARENA_INUSE);
268 usedSize += pArena->size & ARENA_SIZE_MASK;
272 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
273 DPRINTF( "%p used %08x\n", pArena, pArena->size & ARENA_SIZE_MASK );
274 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
275 arenaSize += sizeof(ARENA_INUSE);
276 usedSize += pArena->size & ARENA_SIZE_MASK;
279 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
280 subheap->size, subheap->commitSize, freeSize, usedSize,
281 arenaSize, (arenaSize * 100) / subheap->size );
286 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
289 TRACE( "Dumping entry %p\n", entry );
290 TRACE( "lpData\t\t: %p\n", entry->lpData );
291 TRACE( "cbData\t\t: %08x\n", entry->cbData);
292 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
293 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
294 TRACE( "WFlags\t\t: ");
295 if (entry->wFlags & PROCESS_HEAP_REGION)
296 TRACE( "PROCESS_HEAP_REGION ");
297 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
298 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
299 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
300 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
301 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
302 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
303 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
304 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
305 rem_flags = entry->wFlags &
306 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
307 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
308 PROCESS_HEAP_ENTRY_DDESHARE);
310 TRACE( "Unknown %08x", rem_flags);
312 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
313 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
316 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
318 if (entry->wFlags & PROCESS_HEAP_REGION)
320 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
321 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
322 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
323 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
327 /***********************************************************************
330 * Pointer to the heap
333 static HEAP *HEAP_GetPtr(
334 HANDLE heap /* [in] Handle to the heap */
336 HEAP *heapPtr = (HEAP *)heap;
337 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
339 ERR("Invalid heap %p!\n", heap );
342 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
344 HEAP_Dump( heapPtr );
352 /***********************************************************************
353 * HEAP_InsertFreeBlock
355 * Insert a free block into the free list.
357 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
359 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
362 /* insert at end of free list, i.e. before the next free list entry */
364 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
365 list_add_before( &pEntry->arena.entry, &pArena->entry );
369 /* insert at head of free list */
370 list_add_after( &pEntry->arena.entry, &pArena->entry );
372 pArena->size |= ARENA_FLAG_FREE;
376 /***********************************************************************
378 * Find the sub-heap containing a given address.
384 static SUBHEAP *HEAP_FindSubHeap(
385 const HEAP *heap, /* [in] Heap pointer */
386 LPCVOID ptr ) /* [in] Address */
389 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
390 if (((const char *)ptr >= (const char *)sub->base) &&
391 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
397 /***********************************************************************
400 * Make sure the heap storage is committed for a given size in the specified arena.
402 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
404 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
405 SIZE_T size = (char *)ptr - (char *)subheap->base;
406 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
407 if (size > subheap->size) size = subheap->size;
408 if (size <= subheap->commitSize) return TRUE;
409 size -= subheap->commitSize;
410 ptr = (char *)subheap->base + subheap->commitSize;
411 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
412 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
414 WARN("Could not commit %08lx bytes at %p for heap %p\n",
415 size, ptr, subheap->heap );
418 subheap->commitSize += size;
423 /***********************************************************************
426 * If possible, decommit the heap storage from (including) 'ptr'.
428 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
431 SIZE_T decommit_size;
432 SIZE_T size = (char *)ptr - (char *)subheap->base;
434 /* round to next block and add one full block */
435 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
436 if (size >= subheap->commitSize) return TRUE;
437 decommit_size = subheap->commitSize - size;
438 addr = (char *)subheap->base + size;
440 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
442 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
443 decommit_size, (char *)subheap->base + size, subheap->heap );
446 subheap->commitSize -= decommit_size;
451 /***********************************************************************
452 * HEAP_CreateFreeBlock
454 * Create a free block at a specified address. 'size' is the size of the
455 * whole block, including the new arena.
457 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
463 /* Create a free arena */
464 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
465 pFree = (ARENA_FREE *)ptr;
466 pFree->magic = ARENA_FREE_MAGIC;
468 /* If debugging, erase the freed block content */
470 pEnd = (char *)ptr + size;
471 if (pEnd > (char *)subheap->base + subheap->commitSize)
472 pEnd = (char *)subheap->base + subheap->commitSize;
473 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
475 /* Check if next block is free also */
477 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
478 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
480 /* Remove the next arena from the free list */
481 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
482 list_remove( &pNext->entry );
483 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
484 mark_block_free( pNext, sizeof(ARENA_FREE) );
487 /* Set the next block PREV_FREE flag and pointer */
489 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
492 DWORD *pNext = (DWORD *)((char *)ptr + size);
493 *pNext |= ARENA_FLAG_PREV_FREE;
494 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
495 *((ARENA_FREE **)pNext - 1) = pFree;
498 /* Last, insert the new block into the free list */
500 pFree->size = size - sizeof(*pFree);
501 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
505 /***********************************************************************
506 * HEAP_MakeInUseBlockFree
508 * Turn an in-use block into a free block. Can also decommit the end of
509 * the heap, and possibly even free the sub-heap altogether.
511 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
514 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
516 /* Check if we can merge with previous block */
518 if (pArena->size & ARENA_FLAG_PREV_FREE)
520 pFree = *((ARENA_FREE **)pArena - 1);
521 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
522 /* Remove it from the free list */
523 list_remove( &pFree->entry );
525 else pFree = (ARENA_FREE *)pArena;
527 /* Create a free block */
529 HEAP_CreateFreeBlock( subheap, pFree, size );
530 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
531 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
532 return; /* Not the last block, so nothing more to do */
534 /* Free the whole sub-heap if it's empty and not the original one */
536 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
537 (subheap != &subheap->heap->subheap))
540 void *addr = subheap->base;
541 /* Remove the free block from the list */
542 list_remove( &pFree->entry );
543 /* Remove the subheap from the list */
544 list_remove( &subheap->entry );
545 /* Free the memory */
547 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
551 /* Decommit the end of the heap */
553 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
557 /***********************************************************************
560 * Shrink an in-use block.
562 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
564 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
566 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
567 (pArena->size & ARENA_SIZE_MASK) - size );
568 /* assign size plus previous arena flags */
569 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
573 /* Turn off PREV_FREE flag in next block */
574 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
575 if (pNext < (char *)subheap->base + subheap->size)
576 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
580 /***********************************************************************
583 static SUBHEAP *HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
584 SIZE_T commitSize, SIZE_T totalSize )
587 FREE_LIST_ENTRY *pEntry;
592 if (flags & HEAP_SHARED)
593 commitSize = totalSize; /* always commit everything in a shared heap */
594 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
595 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
597 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
603 /* If this is a secondary subheap, insert it into list */
605 subheap = (SUBHEAP *)address;
606 subheap->base = address;
607 subheap->heap = heap;
608 subheap->size = totalSize;
609 subheap->commitSize = commitSize;
610 subheap->magic = SUBHEAP_MAGIC;
611 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
612 list_add_head( &heap->subheap_list, &subheap->entry );
616 /* If this is a primary subheap, initialize main heap */
618 heap = (HEAP *)address;
620 heap->magic = HEAP_MAGIC;
621 list_init( &heap->subheap_list );
623 subheap = &heap->subheap;
624 subheap->base = address;
625 subheap->heap = heap;
626 subheap->size = totalSize;
627 subheap->commitSize = commitSize;
628 subheap->magic = SUBHEAP_MAGIC;
629 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
630 list_add_head( &heap->subheap_list, &subheap->entry );
632 /* Build the free lists */
634 list_init( &heap->freeList[0].arena.entry );
635 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
637 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
638 pEntry->arena.magic = ARENA_FREE_MAGIC;
639 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
642 /* Initialize critical section */
644 if (!processHeap) /* do it by hand to avoid memory allocations */
646 heap->critSection.DebugInfo = &process_heap_critsect_debug;
647 heap->critSection.LockCount = -1;
648 heap->critSection.RecursionCount = 0;
649 heap->critSection.OwningThread = 0;
650 heap->critSection.LockSemaphore = 0;
651 heap->critSection.SpinCount = 0;
652 process_heap_critsect_debug.CriticalSection = &heap->critSection;
656 RtlInitializeCriticalSection( &heap->critSection );
657 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
660 if (flags & HEAP_SHARED)
662 /* let's assume that only one thread at a time will try to do this */
663 HANDLE sem = heap->critSection.LockSemaphore;
664 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
666 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
667 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
668 heap->critSection.LockSemaphore = sem;
669 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
670 heap->critSection.DebugInfo = NULL;
674 /* Create the first free block */
676 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
677 subheap->size - subheap->headerSize );
682 /***********************************************************************
685 * Create a sub-heap of the given size.
686 * If heap == NULL, creates a main heap.
688 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
689 SIZE_T commitSize, SIZE_T totalSize )
691 LPVOID address = base;
694 /* round-up sizes on a 64K boundary */
695 totalSize = (totalSize + 0xffff) & 0xffff0000;
696 commitSize = (commitSize + 0xffff) & 0xffff0000;
697 if (!commitSize) commitSize = 0x10000;
698 if (totalSize < commitSize) totalSize = commitSize;
702 /* allocate the memory block */
703 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
704 MEM_RESERVE, get_protection_type( flags ) ))
706 WARN("Could not allocate %08lx bytes\n", totalSize );
711 /* Initialize subheap */
713 if (!(ret = HEAP_InitSubHeap( heap, address, flags, commitSize, totalSize )))
716 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
722 /***********************************************************************
725 * Find a free block at least as large as the requested size, and make sure
726 * the requested size is committed.
728 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
729 SUBHEAP **ppSubHeap )
734 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
736 /* Find a suitable free list, and in it find a block large enough */
738 ptr = &pEntry->arena.entry;
739 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
741 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
742 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
743 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
744 if (arena_size >= size)
746 subheap = HEAP_FindSubHeap( heap, pArena );
747 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
748 *ppSubHeap = subheap;
753 /* If no block was found, attempt to grow the heap */
755 if (!(heap->flags & HEAP_GROWABLE))
757 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
760 /* make sure that we have a big enough size *committed* to fit another
761 * last free arena in !
762 * So just one heap struct, one first free arena which will eventually
763 * get used, and a second free arena that might get assigned all remaining
764 * free space in HEAP_ShrinkBlock() */
765 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
766 if (total_size < size) return NULL; /* overflow */
768 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
769 max( HEAP_DEF_SIZE, total_size ) )))
772 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
773 subheap, total_size, heap );
775 *ppSubHeap = subheap;
776 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
780 /***********************************************************************
781 * HEAP_IsValidArenaPtr
783 * Check that the pointer is inside the range possible for arenas.
785 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
788 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
789 if (!subheap) return FALSE;
790 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
791 if (subheap != &heap->subheap) return FALSE;
792 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
793 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
798 /***********************************************************************
799 * HEAP_ValidateFreeArena
801 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
803 ARENA_FREE *prev, *next;
804 char *heapEnd = (char *)subheap->base + subheap->size;
806 /* Check for unaligned pointers */
807 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
809 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
813 /* Check magic number */
814 if (pArena->magic != ARENA_FREE_MAGIC)
816 ERR("Heap %p: invalid free arena magic for %p\n", subheap->heap, pArena );
819 /* Check size flags */
820 if (!(pArena->size & ARENA_FLAG_FREE) ||
821 (pArena->size & ARENA_FLAG_PREV_FREE))
823 ERR("Heap %p: bad flags %08x for free arena %p\n",
824 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
827 /* Check arena size */
828 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
830 ERR("Heap %p: bad size %08x for free arena %p\n",
831 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
834 /* Check that next pointer is valid */
835 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
836 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
838 ERR("Heap %p: bad next ptr %p for arena %p\n",
839 subheap->heap, next, pArena );
842 /* Check that next arena is free */
843 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
845 ERR("Heap %p: next arena %p invalid for %p\n",
846 subheap->heap, next, pArena );
849 /* Check that prev pointer is valid */
850 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
851 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
853 ERR("Heap %p: bad prev ptr %p for arena %p\n",
854 subheap->heap, prev, pArena );
857 /* Check that prev arena is free */
858 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
860 /* this often means that the prev arena got overwritten
861 * by a memory write before that prev arena */
862 ERR("Heap %p: prev arena %p invalid for %p\n",
863 subheap->heap, prev, pArena );
866 /* Check that next block has PREV_FREE flag */
867 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
869 if (!(*(DWORD *)((char *)(pArena + 1) +
870 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
872 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
873 subheap->heap, pArena );
876 /* Check next block back pointer */
877 if (*((ARENA_FREE **)((char *)(pArena + 1) +
878 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
880 ERR("Heap %p: arena %p has wrong back ptr %p\n",
881 subheap->heap, pArena,
882 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
890 /***********************************************************************
891 * HEAP_ValidateInUseArena
893 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
895 const char *heapEnd = (const char *)subheap->base + subheap->size;
897 /* Check for unaligned pointers */
898 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
900 if ( quiet == NOISY )
902 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
903 if ( TRACE_ON(heap) )
904 HEAP_Dump( subheap->heap );
906 else if ( WARN_ON(heap) )
908 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
909 if ( TRACE_ON(heap) )
910 HEAP_Dump( subheap->heap );
915 /* Check magic number */
916 if (pArena->magic != ARENA_INUSE_MAGIC)
918 if (quiet == NOISY) {
919 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
921 HEAP_Dump( subheap->heap );
922 } else if (WARN_ON(heap)) {
923 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
925 HEAP_Dump( subheap->heap );
929 /* Check size flags */
930 if (pArena->size & ARENA_FLAG_FREE)
932 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
933 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
936 /* Check arena size */
937 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
939 ERR("Heap %p: bad size %08x for in-use arena %p\n",
940 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
943 /* Check next arena PREV_FREE flag */
944 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
945 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
947 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
948 subheap->heap, pArena );
951 /* Check prev free arena */
952 if (pArena->size & ARENA_FLAG_PREV_FREE)
954 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
955 /* Check prev pointer */
956 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
958 ERR("Heap %p: bad back ptr %p for arena %p\n",
959 subheap->heap, pPrev, pArena );
962 /* Check that prev arena is free */
963 if (!(pPrev->size & ARENA_FLAG_FREE) ||
964 (pPrev->magic != ARENA_FREE_MAGIC))
966 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
967 subheap->heap, pPrev, pArena );
970 /* Check that prev arena is really the previous block */
971 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
973 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
974 subheap->heap, pPrev, pArena );
982 /***********************************************************************
983 * HEAP_IsRealArena [Internal]
984 * Validates a block is a valid arena.
990 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
991 DWORD flags, /* [in] Bit flags that control access during operation */
992 LPCVOID block, /* [in] Optional pointer to memory block to validate */
993 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
994 * does not complain */
999 flags &= HEAP_NO_SERIALIZE;
1000 flags |= heapPtr->flags;
1001 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1002 if (!(flags & HEAP_NO_SERIALIZE))
1003 RtlEnterCriticalSection( &heapPtr->critSection );
1005 if (block) /* only check this single memory block */
1007 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1009 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1010 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1013 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1014 else if (WARN_ON(heap))
1015 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1018 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1020 if (!(flags & HEAP_NO_SERIALIZE))
1021 RtlLeaveCriticalSection( &heapPtr->critSection );
1025 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1027 char *ptr = (char *)subheap->base + subheap->headerSize;
1028 while (ptr < (char *)subheap->base + subheap->size)
1030 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1032 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1036 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1040 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1044 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1050 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1055 /***********************************************************************
1056 * RtlCreateHeap (NTDLL.@)
1058 * Create a new Heap.
1061 * flags [I] HEAP_ flags from "winnt.h"
1062 * addr [I] Desired base address
1063 * totalSize [I] Total size of the heap, or 0 for a growable heap
1064 * commitSize [I] Amount of heap space to commit
1065 * unknown [I] Not yet understood
1066 * definition [I] Heap definition
1069 * Success: A HANDLE to the newly created heap.
1070 * Failure: a NULL HANDLE.
1072 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1073 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1077 /* Allocate the heap block */
1081 totalSize = HEAP_DEF_SIZE;
1082 flags |= HEAP_GROWABLE;
1085 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1087 /* link it into the per-process heap list */
1090 HEAP *heapPtr = subheap->heap;
1091 RtlEnterCriticalSection( &processHeap->critSection );
1092 list_add_head( &processHeap->entry, &heapPtr->entry );
1093 RtlLeaveCriticalSection( &processHeap->critSection );
1097 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1098 list_init( &processHeap->entry );
1099 /* make sure structure alignment is correct */
1100 assert( (ULONG_PTR)&processHeap->freeList % ALIGNMENT == 0 );
1103 return (HANDLE)subheap->heap;
1107 /***********************************************************************
1108 * RtlDestroyHeap (NTDLL.@)
1110 * Destroy a Heap created with RtlCreateHeap().
1113 * heap [I] Heap to destroy.
1116 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1117 * Failure: The Heap handle, if heap is the process heap.
1119 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1121 HEAP *heapPtr = HEAP_GetPtr( heap );
1122 SUBHEAP *subheap, *next;
1126 TRACE("%p\n", heap );
1127 if (!heapPtr) return heap;
1129 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1131 /* remove it from the per-process list */
1132 RtlEnterCriticalSection( &processHeap->critSection );
1133 list_remove( &heapPtr->entry );
1134 RtlLeaveCriticalSection( &processHeap->critSection );
1136 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1137 RtlDeleteCriticalSection( &heapPtr->critSection );
1139 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1141 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1142 list_remove( &subheap->entry );
1144 addr = subheap->base;
1145 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1148 addr = heapPtr->subheap.base;
1149 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1154 /***********************************************************************
1155 * RtlAllocateHeap (NTDLL.@)
1157 * Allocate a memory block from a Heap.
1160 * heap [I] Heap to allocate block from
1161 * flags [I] HEAP_ flags from "winnt.h"
1162 * size [I] Size of the memory block to allocate
1165 * Success: A pointer to the newly allocated block
1169 * This call does not SetLastError().
1171 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1174 ARENA_INUSE *pInUse;
1176 HEAP *heapPtr = HEAP_GetPtr( heap );
1177 SIZE_T rounded_size;
1179 /* Validate the parameters */
1181 if (!heapPtr) return NULL;
1182 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1183 flags |= heapPtr->flags;
1184 rounded_size = ROUND_SIZE(size);
1185 if (rounded_size < size) /* overflow */
1187 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1190 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1192 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1193 /* Locate a suitable free block */
1195 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1197 TRACE("(%p,%08x,%08lx): returning NULL\n",
1198 heap, flags, size );
1199 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1200 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1204 /* Remove the arena from the free list */
1206 list_remove( &pArena->entry );
1208 /* Build the in-use arena */
1210 pInUse = (ARENA_INUSE *)pArena;
1212 /* in-use arena is smaller than free arena,
1213 * so we have to add the difference to the size */
1214 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1215 pInUse->magic = ARENA_INUSE_MAGIC;
1217 /* Shrink the block */
1219 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1220 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1222 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1224 if (flags & HEAP_ZERO_MEMORY)
1225 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1227 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1229 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1231 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1232 return (LPVOID)(pInUse + 1);
1236 /***********************************************************************
1237 * RtlFreeHeap (NTDLL.@)
1239 * Free a memory block allocated with RtlAllocateHeap().
1242 * heap [I] Heap that block was allocated from
1243 * flags [I] HEAP_ flags from "winnt.h"
1244 * ptr [I] Block to free
1247 * Success: TRUE, if ptr is NULL or was freed successfully.
1250 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1252 ARENA_INUSE *pInUse;
1256 /* Validate the parameters */
1258 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1260 heapPtr = HEAP_GetPtr( heap );
1263 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1267 flags &= HEAP_NO_SERIALIZE;
1268 flags |= heapPtr->flags;
1269 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1271 /* Some sanity checks */
1273 pInUse = (ARENA_INUSE *)ptr - 1;
1274 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse ))) goto error;
1275 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1276 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1278 /* Turn the block into a free block */
1282 HEAP_MakeInUseBlockFree( subheap, pInUse );
1284 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1286 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1290 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1291 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1292 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1297 /***********************************************************************
1298 * RtlReAllocateHeap (NTDLL.@)
1300 * Change the size of a memory block allocated with RtlAllocateHeap().
1303 * heap [I] Heap that block was allocated from
1304 * flags [I] HEAP_ flags from "winnt.h"
1305 * ptr [I] Block to resize
1306 * size [I] Size of the memory block to allocate
1309 * Success: A pointer to the resized block (which may be different).
1312 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1314 ARENA_INUSE *pArena;
1317 SIZE_T oldSize, rounded_size;
1319 if (!ptr) return NULL;
1320 if (!(heapPtr = HEAP_GetPtr( heap )))
1322 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1326 /* Validate the parameters */
1328 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1329 HEAP_REALLOC_IN_PLACE_ONLY;
1330 flags |= heapPtr->flags;
1331 rounded_size = ROUND_SIZE(size);
1332 if (rounded_size < size) /* overflow */
1334 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1335 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1338 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1340 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1342 pArena = (ARENA_INUSE *)ptr - 1;
1343 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena ))) goto error;
1344 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1345 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1347 /* Check if we need to grow the block */
1349 oldSize = (pArena->size & ARENA_SIZE_MASK);
1350 if (rounded_size > oldSize)
1352 char *pNext = (char *)(pArena + 1) + oldSize;
1353 if ((pNext < (char *)subheap->base + subheap->size) &&
1354 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1355 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1357 /* The next block is free and large enough */
1358 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1359 list_remove( &pFree->entry );
1360 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1361 if (!HEAP_Commit( subheap, pArena, rounded_size ))
1363 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1364 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1365 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1368 notify_free( pArena + 1 );
1369 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1370 notify_alloc( pArena + 1, size, FALSE );
1371 /* FIXME: this is wrong as we may lose old VBits settings */
1372 mark_block_initialized( pArena + 1, oldSize );
1374 else /* Do it the hard way */
1377 ARENA_INUSE *pInUse;
1378 SUBHEAP *newsubheap;
1380 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1381 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1383 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1384 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1385 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1389 /* Build the in-use arena */
1391 list_remove( &pNew->entry );
1392 pInUse = (ARENA_INUSE *)pNew;
1393 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1394 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1395 pInUse->magic = ARENA_INUSE_MAGIC;
1396 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1397 mark_block_initialized( pInUse + 1, oldSize );
1398 notify_alloc( pInUse + 1, size, FALSE );
1399 memcpy( pInUse + 1, pArena + 1, oldSize );
1401 /* Free the previous block */
1403 notify_free( pArena + 1 );
1404 HEAP_MakeInUseBlockFree( subheap, pArena );
1405 subheap = newsubheap;
1411 /* Shrink the block */
1412 notify_free( pArena + 1 );
1413 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1414 notify_alloc( pArena + 1, size, FALSE );
1415 /* FIXME: this is wrong as we may lose old VBits settings */
1416 mark_block_initialized( pArena + 1, size );
1419 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1421 /* Clear the extra bytes if needed */
1423 if (rounded_size > oldSize)
1425 if (flags & HEAP_ZERO_MEMORY)
1426 clear_block( (char *)(pArena + 1) + oldSize,
1427 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1429 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1430 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1433 /* Return the new arena */
1435 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1437 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1438 return (LPVOID)(pArena + 1);
1441 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1442 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1443 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1448 /***********************************************************************
1449 * RtlCompactHeap (NTDLL.@)
1451 * Compact the free space in a Heap.
1454 * heap [I] Heap that block was allocated from
1455 * flags [I] HEAP_ flags from "winnt.h"
1458 * The number of bytes compacted.
1461 * This function is a harmless stub.
1463 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1465 static BOOL reported;
1466 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1471 /***********************************************************************
1472 * RtlLockHeap (NTDLL.@)
1477 * heap [I] Heap to lock
1480 * Success: TRUE. The Heap is locked.
1481 * Failure: FALSE, if heap is invalid.
1483 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1485 HEAP *heapPtr = HEAP_GetPtr( heap );
1486 if (!heapPtr) return FALSE;
1487 RtlEnterCriticalSection( &heapPtr->critSection );
1492 /***********************************************************************
1493 * RtlUnlockHeap (NTDLL.@)
1498 * heap [I] Heap to unlock
1501 * Success: TRUE. The Heap is unlocked.
1502 * Failure: FALSE, if heap is invalid.
1504 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1506 HEAP *heapPtr = HEAP_GetPtr( heap );
1507 if (!heapPtr) return FALSE;
1508 RtlLeaveCriticalSection( &heapPtr->critSection );
1513 /***********************************************************************
1514 * RtlSizeHeap (NTDLL.@)
1516 * Get the actual size of a memory block allocated from a Heap.
1519 * heap [I] Heap that block was allocated from
1520 * flags [I] HEAP_ flags from "winnt.h"
1521 * ptr [I] Block to get the size of
1524 * Success: The size of the block.
1525 * Failure: -1, heap or ptr are invalid.
1528 * The size may be bigger than what was passed to RtlAllocateHeap().
1530 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1533 HEAP *heapPtr = HEAP_GetPtr( heap );
1537 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1540 flags &= HEAP_NO_SERIALIZE;
1541 flags |= heapPtr->flags;
1542 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1543 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1545 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1550 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1551 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1553 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1555 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1560 /***********************************************************************
1561 * RtlValidateHeap (NTDLL.@)
1563 * Determine if a block is a valid allocation from a heap.
1566 * heap [I] Heap that block was allocated from
1567 * flags [I] HEAP_ flags from "winnt.h"
1568 * ptr [I] Block to check
1571 * Success: TRUE. The block was allocated from heap.
1572 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1574 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1576 HEAP *heapPtr = HEAP_GetPtr( heap );
1577 if (!heapPtr) return FALSE;
1578 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1582 /***********************************************************************
1583 * RtlWalkHeap (NTDLL.@)
1586 * The PROCESS_HEAP_ENTRY flag values seem different between this
1587 * function and HeapWalk(). To be checked.
1589 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1591 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1592 HEAP *heapPtr = HEAP_GetPtr(heap);
1593 SUBHEAP *sub, *currentheap = NULL;
1596 int region_index = 0;
1598 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1600 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1602 /* set ptr to the next arena to be examined */
1604 if (!entry->lpData) /* first call (init) ? */
1606 TRACE("begin walking of heap %p.\n", heap);
1607 currentheap = &heapPtr->subheap;
1608 ptr = (char*)currentheap->base + currentheap->headerSize;
1612 ptr = entry->lpData;
1613 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1615 if (((char *)ptr >= (char *)sub->base) &&
1616 ((char *)ptr < (char *)sub->base + sub->size))
1623 if (currentheap == NULL)
1625 ERR("no matching subheap found, shouldn't happen !\n");
1626 ret = STATUS_NO_MORE_ENTRIES;
1630 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1632 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1633 ptr += pArena->size & ARENA_SIZE_MASK;
1635 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1637 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1638 ptr += pArena->size & ARENA_SIZE_MASK;
1641 ptr += entry->cbData; /* point to next arena */
1643 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1644 { /* proceed with next subheap */
1645 struct list *next = list_next( &heapPtr->subheap_list, ¤theap->entry );
1647 { /* successfully finished */
1648 TRACE("end reached.\n");
1649 ret = STATUS_NO_MORE_ENTRIES;
1652 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1653 ptr = (char *)currentheap->base + currentheap->headerSize;
1658 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1660 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1662 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1664 entry->lpData = pArena + 1;
1665 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1666 entry->cbOverhead = sizeof(ARENA_FREE);
1667 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1671 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1673 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1675 entry->lpData = pArena + 1;
1676 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1677 entry->cbOverhead = sizeof(ARENA_INUSE);
1678 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1679 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1680 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1683 entry->iRegionIndex = region_index;
1685 /* first element of heap ? */
1686 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1688 entry->wFlags |= PROCESS_HEAP_REGION;
1689 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1690 entry->u.Region.dwUnCommittedSize =
1691 currentheap->size - currentheap->commitSize;
1692 entry->u.Region.lpFirstBlock = /* first valid block */
1693 (char *)currentheap->base + currentheap->headerSize;
1694 entry->u.Region.lpLastBlock = /* first invalid block */
1695 (char *)currentheap->base + currentheap->size;
1697 ret = STATUS_SUCCESS;
1698 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1701 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1706 /***********************************************************************
1707 * RtlGetProcessHeaps (NTDLL.@)
1709 * Get the Heaps belonging to the current process.
1712 * count [I] size of heaps
1713 * heaps [O] Destination array for heap HANDLE's
1716 * Success: The number of Heaps allocated by the process.
1719 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1721 ULONG total = 1; /* main heap */
1724 RtlEnterCriticalSection( &processHeap->critSection );
1725 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1728 *heaps++ = processHeap;
1729 LIST_FOR_EACH( ptr, &processHeap->entry )
1730 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1732 RtlLeaveCriticalSection( &processHeap->critSection );