4 * Copyright 1996 Alexandre Julliard
5 * Copyright 1998 Ulrich Weigand
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
29 #ifdef HAVE_VALGRIND_MEMCHECK_H
30 #include <valgrind/memcheck.h>
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
36 #define WIN32_NO_STATUS
40 #include "wine/list.h"
41 #include "wine/debug.h"
42 #include "wine/server.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(heap);
46 /* Note: the heap data structures are loosely based on what Pietrek describes in his
47 * book 'Windows 95 System Programming Secrets', with some adaptations for
48 * better compatibility with NT.
51 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
52 * that there is no unaligned accesses to structure fields.
55 typedef struct tagARENA_INUSE
57 DWORD size; /* Block size; must be the first field */
58 DWORD magic : 24; /* Magic number */
59 DWORD unused_bytes : 8; /* Number of bytes in the block not used by user data (max value is HEAP_MIN_DATA_SIZE+HEAP_MIN_SHRINK_SIZE) */
62 typedef struct tagARENA_FREE
64 DWORD size; /* Block size; must be the first field */
65 DWORD magic; /* Magic number */
66 struct list entry; /* Entry in free list */
69 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
70 #define ARENA_FLAG_PREV_FREE 0x00000002
71 #define ARENA_SIZE_MASK (~3)
72 #define ARENA_INUSE_MAGIC 0x455355 /* Value for arena 'magic' field */
73 #define ARENA_FREE_MAGIC 0x45455246 /* Value for arena 'magic' field */
75 #define ARENA_INUSE_FILLER 0x55
76 #define ARENA_FREE_FILLER 0xaa
78 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
79 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
81 #define QUIET 1 /* Suppress messages */
82 #define NOISY 0 /* Report all errors */
84 /* minimum data size (without arenas) of an allocated block */
85 /* make sure that it's larger than a free list entry */
86 #define HEAP_MIN_DATA_SIZE (2 * sizeof(struct list))
87 /* minimum size that must remain to shrink an allocated block */
88 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
90 /* Max size of the blocks on the free lists */
91 static const SIZE_T HEAP_freeListSizes[] =
93 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
95 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
104 typedef struct tagSUBHEAP
106 void *base; /* Base address of the sub-heap memory block */
107 SIZE_T size; /* Size of the whole sub-heap */
108 SIZE_T commitSize; /* Committed size of the sub-heap */
109 struct list entry; /* Entry in sub-heap list */
110 struct tagHEAP *heap; /* Main heap structure */
111 DWORD headerSize; /* Size of the heap header */
112 DWORD magic; /* Magic number */
115 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
117 typedef struct tagHEAP
120 DWORD flags; /* Heap flags */
121 DWORD force_flags; /* Forced heap flags for debugging */
122 SUBHEAP subheap; /* First sub-heap */
123 struct list entry; /* Entry in process heap list */
124 struct list subheap_list; /* Sub-heap list */
125 DWORD magic; /* Magic number */
126 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
127 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
130 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
132 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
133 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
135 static HEAP *processHeap; /* main process heap */
137 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
139 /* mark a block of memory as free for debugging purposes */
140 static inline void mark_block_free( void *ptr, SIZE_T size )
142 if (TRACE_ON(heap) || WARN_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
143 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
144 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
145 #elif defined( VALGRIND_MAKE_NOACCESS)
146 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
150 /* mark a block of memory as initialized for debugging purposes */
151 static inline void mark_block_initialized( void *ptr, SIZE_T size )
153 #if defined(VALGRIND_MAKE_MEM_DEFINED)
154 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
155 #elif defined(VALGRIND_MAKE_READABLE)
156 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
160 /* mark a block of memory as uninitialized for debugging purposes */
161 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
163 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
164 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
165 #elif defined(VALGRIND_MAKE_WRITABLE)
166 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
168 if (TRACE_ON(heap) || WARN_ON(heap))
170 memset( ptr, ARENA_INUSE_FILLER, size );
171 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
172 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
173 #elif defined(VALGRIND_MAKE_WRITABLE)
174 /* make it uninitialized to valgrind again */
175 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
180 /* clear contents of a block of memory */
181 static inline void clear_block( void *ptr, SIZE_T size )
183 mark_block_initialized( ptr, size );
184 memset( ptr, 0, size );
187 /* notify that a new block of memory has been allocated for debugging purposes */
188 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
190 #ifdef VALGRIND_MALLOCLIKE_BLOCK
191 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
195 /* notify that a block of memory has been freed for debugging purposes */
196 static inline void notify_free( void const *ptr )
198 #ifdef VALGRIND_FREELIKE_BLOCK
199 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
203 static void subheap_notify_free_all(SUBHEAP const *subheap)
205 #ifdef VALGRIND_FREELIKE_BLOCK
206 char const *ptr = (char const *)subheap->base + subheap->headerSize;
208 if (!RUNNING_ON_VALGRIND) return;
210 while (ptr < (char const *)subheap->base + subheap->size)
212 if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
214 ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
215 if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
216 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
220 ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
221 if (pArena->magic!=ARENA_INUSE_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
222 notify_free(pArena + 1);
223 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
229 /* locate a free list entry of the appropriate size */
230 /* size is the size of the whole block including the arena header */
231 static inline unsigned int get_freelist_index( SIZE_T size )
235 size -= sizeof(ARENA_FREE);
236 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
240 /* get the memory protection type to use for a given heap */
241 static inline ULONG get_protection_type( DWORD flags )
243 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
246 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
248 0, 0, NULL, /* will be set later */
249 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
250 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
254 /***********************************************************************
257 static void HEAP_Dump( HEAP *heap )
263 DPRINTF( "Heap: %p\n", heap );
264 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
265 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
267 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
268 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
269 DPRINTF( "%p free %08lx prev=%p next=%p\n",
270 &heap->freeList[i].arena, HEAP_freeListSizes[i],
271 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
272 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
274 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
276 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
277 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
278 subheap, subheap->base, subheap->size, subheap->commitSize );
280 DPRINTF( "\n Block Arena Stat Size Id\n" );
281 ptr = (char *)subheap->base + subheap->headerSize;
282 while (ptr < (char *)subheap->base + subheap->size)
284 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
286 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
287 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
288 pArena, pArena->magic,
289 pArena->size & ARENA_SIZE_MASK,
290 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
291 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
292 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
293 arenaSize += sizeof(ARENA_FREE);
294 freeSize += pArena->size & ARENA_SIZE_MASK;
296 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
298 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
299 DPRINTF( "%p %08x Used %08x back=%p\n",
300 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
301 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
302 arenaSize += sizeof(ARENA_INUSE);
303 usedSize += pArena->size & ARENA_SIZE_MASK;
307 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
308 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
309 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
310 arenaSize += sizeof(ARENA_INUSE);
311 usedSize += pArena->size & ARENA_SIZE_MASK;
314 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
315 subheap->size, subheap->commitSize, freeSize, usedSize,
316 arenaSize, (arenaSize * 100) / subheap->size );
321 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
324 TRACE( "Dumping entry %p\n", entry );
325 TRACE( "lpData\t\t: %p\n", entry->lpData );
326 TRACE( "cbData\t\t: %08x\n", entry->cbData);
327 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
328 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
329 TRACE( "WFlags\t\t: ");
330 if (entry->wFlags & PROCESS_HEAP_REGION)
331 TRACE( "PROCESS_HEAP_REGION ");
332 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
333 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
334 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
335 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
336 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
337 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
338 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
339 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
340 rem_flags = entry->wFlags &
341 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
342 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
343 PROCESS_HEAP_ENTRY_DDESHARE);
345 TRACE( "Unknown %08x", rem_flags);
347 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
348 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
351 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
353 if (entry->wFlags & PROCESS_HEAP_REGION)
355 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
356 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
357 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
358 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
362 /***********************************************************************
365 * Pointer to the heap
368 static HEAP *HEAP_GetPtr(
369 HANDLE heap /* [in] Handle to the heap */
371 HEAP *heapPtr = (HEAP *)heap;
372 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
374 ERR("Invalid heap %p!\n", heap );
377 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
379 HEAP_Dump( heapPtr );
387 /***********************************************************************
388 * HEAP_InsertFreeBlock
390 * Insert a free block into the free list.
392 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
394 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
397 /* insert at end of free list, i.e. before the next free list entry */
399 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
400 list_add_before( &pEntry->arena.entry, &pArena->entry );
404 /* insert at head of free list */
405 list_add_after( &pEntry->arena.entry, &pArena->entry );
407 pArena->size |= ARENA_FLAG_FREE;
411 /***********************************************************************
413 * Find the sub-heap containing a given address.
419 static SUBHEAP *HEAP_FindSubHeap(
420 const HEAP *heap, /* [in] Heap pointer */
421 LPCVOID ptr ) /* [in] Address */
424 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
425 if (((const char *)ptr >= (const char *)sub->base) &&
426 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
432 /***********************************************************************
435 * Make sure the heap storage is committed for a given size in the specified arena.
437 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
439 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
440 SIZE_T size = (char *)ptr - (char *)subheap->base;
441 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
442 if (size > subheap->size) size = subheap->size;
443 if (size <= subheap->commitSize) return TRUE;
444 size -= subheap->commitSize;
445 ptr = (char *)subheap->base + subheap->commitSize;
446 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
447 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
449 WARN("Could not commit %08lx bytes at %p for heap %p\n",
450 size, ptr, subheap->heap );
453 subheap->commitSize += size;
458 /***********************************************************************
461 * If possible, decommit the heap storage from (including) 'ptr'.
463 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
466 SIZE_T decommit_size;
467 SIZE_T size = (char *)ptr - (char *)subheap->base;
469 /* round to next block and add one full block */
470 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
471 if (size >= subheap->commitSize) return TRUE;
472 decommit_size = subheap->commitSize - size;
473 addr = (char *)subheap->base + size;
475 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
477 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
478 decommit_size, (char *)subheap->base + size, subheap->heap );
481 subheap->commitSize -= decommit_size;
486 /***********************************************************************
487 * HEAP_CreateFreeBlock
489 * Create a free block at a specified address. 'size' is the size of the
490 * whole block, including the new arena.
492 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
498 /* Create a free arena */
499 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
500 pFree = (ARENA_FREE *)ptr;
501 pFree->magic = ARENA_FREE_MAGIC;
503 /* If debugging, erase the freed block content */
505 pEnd = (char *)ptr + size;
506 if (pEnd > (char *)subheap->base + subheap->commitSize)
507 pEnd = (char *)subheap->base + subheap->commitSize;
508 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
510 /* Check if next block is free also */
512 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
513 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
515 /* Remove the next arena from the free list */
516 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
517 list_remove( &pNext->entry );
518 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
519 mark_block_free( pNext, sizeof(ARENA_FREE) );
522 /* Set the next block PREV_FREE flag and pointer */
524 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
527 DWORD *pNext = (DWORD *)((char *)ptr + size);
528 *pNext |= ARENA_FLAG_PREV_FREE;
529 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
530 *((ARENA_FREE **)pNext - 1) = pFree;
533 /* Last, insert the new block into the free list */
535 pFree->size = size - sizeof(*pFree);
536 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
540 /***********************************************************************
541 * HEAP_MakeInUseBlockFree
543 * Turn an in-use block into a free block. Can also decommit the end of
544 * the heap, and possibly even free the sub-heap altogether.
546 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
549 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
551 /* Check if we can merge with previous block */
553 if (pArena->size & ARENA_FLAG_PREV_FREE)
555 pFree = *((ARENA_FREE **)pArena - 1);
556 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
557 /* Remove it from the free list */
558 list_remove( &pFree->entry );
560 else pFree = (ARENA_FREE *)pArena;
562 /* Create a free block */
564 HEAP_CreateFreeBlock( subheap, pFree, size );
565 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
566 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
567 return; /* Not the last block, so nothing more to do */
569 /* Free the whole sub-heap if it's empty and not the original one */
571 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
572 (subheap != &subheap->heap->subheap))
575 void *addr = subheap->base;
576 /* Remove the free block from the list */
577 list_remove( &pFree->entry );
578 /* Remove the subheap from the list */
579 list_remove( &subheap->entry );
580 /* Free the memory */
582 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
586 /* Decommit the end of the heap */
588 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
592 /***********************************************************************
595 * Shrink an in-use block.
597 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
599 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
601 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
602 (pArena->size & ARENA_SIZE_MASK) - size );
603 /* assign size plus previous arena flags */
604 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
608 /* Turn off PREV_FREE flag in next block */
609 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
610 if (pNext < (char *)subheap->base + subheap->size)
611 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
615 /***********************************************************************
618 static SUBHEAP *HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
619 SIZE_T commitSize, SIZE_T totalSize )
622 FREE_LIST_ENTRY *pEntry;
627 if (flags & HEAP_SHARED)
628 commitSize = totalSize; /* always commit everything in a shared heap */
629 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
630 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
632 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
638 /* If this is a secondary subheap, insert it into list */
640 subheap = (SUBHEAP *)address;
641 subheap->base = address;
642 subheap->heap = heap;
643 subheap->size = totalSize;
644 subheap->commitSize = commitSize;
645 subheap->magic = SUBHEAP_MAGIC;
646 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
647 list_add_head( &heap->subheap_list, &subheap->entry );
651 /* If this is a primary subheap, initialize main heap */
653 heap = (HEAP *)address;
655 heap->magic = HEAP_MAGIC;
656 list_init( &heap->subheap_list );
658 subheap = &heap->subheap;
659 subheap->base = address;
660 subheap->heap = heap;
661 subheap->size = totalSize;
662 subheap->commitSize = commitSize;
663 subheap->magic = SUBHEAP_MAGIC;
664 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
665 list_add_head( &heap->subheap_list, &subheap->entry );
667 /* Build the free lists */
669 list_init( &heap->freeList[0].arena.entry );
670 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
672 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
673 pEntry->arena.magic = ARENA_FREE_MAGIC;
674 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
677 /* Initialize critical section */
679 if (!processHeap) /* do it by hand to avoid memory allocations */
681 heap->critSection.DebugInfo = &process_heap_critsect_debug;
682 heap->critSection.LockCount = -1;
683 heap->critSection.RecursionCount = 0;
684 heap->critSection.OwningThread = 0;
685 heap->critSection.LockSemaphore = 0;
686 heap->critSection.SpinCount = 0;
687 process_heap_critsect_debug.CriticalSection = &heap->critSection;
691 RtlInitializeCriticalSection( &heap->critSection );
692 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
695 if (flags & HEAP_SHARED)
697 /* let's assume that only one thread at a time will try to do this */
698 HANDLE sem = heap->critSection.LockSemaphore;
699 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
701 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
702 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
703 heap->critSection.LockSemaphore = sem;
704 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
705 heap->critSection.DebugInfo = NULL;
709 /* Create the first free block */
711 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
712 subheap->size - subheap->headerSize );
717 /***********************************************************************
720 * Create a sub-heap of the given size.
721 * If heap == NULL, creates a main heap.
723 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
724 SIZE_T commitSize, SIZE_T totalSize )
726 LPVOID address = base;
729 /* round-up sizes on a 64K boundary */
730 totalSize = (totalSize + 0xffff) & 0xffff0000;
731 commitSize = (commitSize + 0xffff) & 0xffff0000;
732 if (!commitSize) commitSize = 0x10000;
733 if (totalSize < commitSize) totalSize = commitSize;
737 /* allocate the memory block */
738 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
739 MEM_RESERVE, get_protection_type( flags ) ))
741 WARN("Could not allocate %08lx bytes\n", totalSize );
746 /* Initialize subheap */
748 if (!(ret = HEAP_InitSubHeap( heap, address, flags, commitSize, totalSize )))
751 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
757 /***********************************************************************
760 * Find a free block at least as large as the requested size, and make sure
761 * the requested size is committed.
763 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
764 SUBHEAP **ppSubHeap )
769 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
771 /* Find a suitable free list, and in it find a block large enough */
773 ptr = &pEntry->arena.entry;
774 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
776 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
777 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
778 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
779 if (arena_size >= size)
781 subheap = HEAP_FindSubHeap( heap, pArena );
782 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
783 *ppSubHeap = subheap;
788 /* If no block was found, attempt to grow the heap */
790 if (!(heap->flags & HEAP_GROWABLE))
792 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
795 /* make sure that we have a big enough size *committed* to fit another
796 * last free arena in !
797 * So just one heap struct, one first free arena which will eventually
798 * get used, and a second free arena that might get assigned all remaining
799 * free space in HEAP_ShrinkBlock() */
800 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
801 if (total_size < size) return NULL; /* overflow */
803 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
804 max( HEAP_DEF_SIZE, total_size ) )))
807 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
808 subheap, total_size, heap );
810 *ppSubHeap = subheap;
811 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
815 /***********************************************************************
816 * HEAP_IsValidArenaPtr
818 * Check that the pointer is inside the range possible for arenas.
820 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
823 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
824 if (!subheap) return FALSE;
825 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
826 if (subheap != &heap->subheap) return FALSE;
827 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
828 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
833 /***********************************************************************
834 * HEAP_ValidateFreeArena
836 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
838 ARENA_FREE *prev, *next;
839 char *heapEnd = (char *)subheap->base + subheap->size;
841 /* Check for unaligned pointers */
842 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
844 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
848 /* Check magic number */
849 if (pArena->magic != ARENA_FREE_MAGIC)
851 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
854 /* Check size flags */
855 if (!(pArena->size & ARENA_FLAG_FREE) ||
856 (pArena->size & ARENA_FLAG_PREV_FREE))
858 ERR("Heap %p: bad flags %08x for free arena %p\n",
859 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
862 /* Check arena size */
863 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
865 ERR("Heap %p: bad size %08x for free arena %p\n",
866 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
869 /* Check that next pointer is valid */
870 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
871 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
873 ERR("Heap %p: bad next ptr %p for arena %p\n",
874 subheap->heap, next, pArena );
877 /* Check that next arena is free */
878 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
880 ERR("Heap %p: next arena %p invalid for %p\n",
881 subheap->heap, next, pArena );
884 /* Check that prev pointer is valid */
885 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
886 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
888 ERR("Heap %p: bad prev ptr %p for arena %p\n",
889 subheap->heap, prev, pArena );
892 /* Check that prev arena is free */
893 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
895 /* this often means that the prev arena got overwritten
896 * by a memory write before that prev arena */
897 ERR("Heap %p: prev arena %p invalid for %p\n",
898 subheap->heap, prev, pArena );
901 /* Check that next block has PREV_FREE flag */
902 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
904 if (!(*(DWORD *)((char *)(pArena + 1) +
905 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
907 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
908 subheap->heap, pArena );
911 /* Check next block back pointer */
912 if (*((ARENA_FREE **)((char *)(pArena + 1) +
913 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
915 ERR("Heap %p: arena %p has wrong back ptr %p\n",
916 subheap->heap, pArena,
917 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
925 /***********************************************************************
926 * HEAP_ValidateInUseArena
928 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
930 const char *heapEnd = (const char *)subheap->base + subheap->size;
932 /* Check for unaligned pointers */
933 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
935 if ( quiet == NOISY )
937 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
938 if ( TRACE_ON(heap) )
939 HEAP_Dump( subheap->heap );
941 else if ( WARN_ON(heap) )
943 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
944 if ( TRACE_ON(heap) )
945 HEAP_Dump( subheap->heap );
950 /* Check magic number */
951 if (pArena->magic != ARENA_INUSE_MAGIC)
953 if (quiet == NOISY) {
954 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
956 HEAP_Dump( subheap->heap );
957 } else if (WARN_ON(heap)) {
958 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
960 HEAP_Dump( subheap->heap );
964 /* Check size flags */
965 if (pArena->size & ARENA_FLAG_FREE)
967 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
968 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
971 /* Check arena size */
972 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
974 ERR("Heap %p: bad size %08x for in-use arena %p\n",
975 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
978 /* Check next arena PREV_FREE flag */
979 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
980 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
982 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
983 subheap->heap, pArena );
986 /* Check prev free arena */
987 if (pArena->size & ARENA_FLAG_PREV_FREE)
989 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
990 /* Check prev pointer */
991 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
993 ERR("Heap %p: bad back ptr %p for arena %p\n",
994 subheap->heap, pPrev, pArena );
997 /* Check that prev arena is free */
998 if (!(pPrev->size & ARENA_FLAG_FREE) ||
999 (pPrev->magic != ARENA_FREE_MAGIC))
1001 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1002 subheap->heap, pPrev, pArena );
1005 /* Check that prev arena is really the previous block */
1006 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1008 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1009 subheap->heap, pPrev, pArena );
1017 /***********************************************************************
1018 * HEAP_IsRealArena [Internal]
1019 * Validates a block is a valid arena.
1025 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1026 DWORD flags, /* [in] Bit flags that control access during operation */
1027 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1028 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1029 * does not complain */
1034 flags &= HEAP_NO_SERIALIZE;
1035 flags |= heapPtr->flags;
1036 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1037 if (!(flags & HEAP_NO_SERIALIZE))
1038 RtlEnterCriticalSection( &heapPtr->critSection );
1040 if (block) /* only check this single memory block */
1042 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1044 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1045 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1048 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1049 else if (WARN_ON(heap))
1050 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1053 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1055 if (!(flags & HEAP_NO_SERIALIZE))
1056 RtlLeaveCriticalSection( &heapPtr->critSection );
1060 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1062 char *ptr = (char *)subheap->base + subheap->headerSize;
1063 while (ptr < (char *)subheap->base + subheap->size)
1065 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1067 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1071 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1075 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1079 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1085 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1090 /***********************************************************************
1091 * RtlCreateHeap (NTDLL.@)
1093 * Create a new Heap.
1096 * flags [I] HEAP_ flags from "winnt.h"
1097 * addr [I] Desired base address
1098 * totalSize [I] Total size of the heap, or 0 for a growable heap
1099 * commitSize [I] Amount of heap space to commit
1100 * unknown [I] Not yet understood
1101 * definition [I] Heap definition
1104 * Success: A HANDLE to the newly created heap.
1105 * Failure: a NULL HANDLE.
1107 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1108 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1112 /* Allocate the heap block */
1116 totalSize = HEAP_DEF_SIZE;
1117 flags |= HEAP_GROWABLE;
1120 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1122 /* link it into the per-process heap list */
1125 HEAP *heapPtr = subheap->heap;
1126 RtlEnterCriticalSection( &processHeap->critSection );
1127 list_add_head( &processHeap->entry, &heapPtr->entry );
1128 RtlLeaveCriticalSection( &processHeap->critSection );
1132 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1133 list_init( &processHeap->entry );
1134 /* make sure structure alignment is correct */
1135 assert( (ULONG_PTR)processHeap->freeList % ALIGNMENT == 0 );
1138 return (HANDLE)subheap->heap;
1142 /***********************************************************************
1143 * RtlDestroyHeap (NTDLL.@)
1145 * Destroy a Heap created with RtlCreateHeap().
1148 * heap [I] Heap to destroy.
1151 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1152 * Failure: The Heap handle, if heap is the process heap.
1154 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1156 HEAP *heapPtr = HEAP_GetPtr( heap );
1157 SUBHEAP *subheap, *next;
1161 TRACE("%p\n", heap );
1162 if (!heapPtr) return heap;
1164 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1166 /* remove it from the per-process list */
1167 RtlEnterCriticalSection( &processHeap->critSection );
1168 list_remove( &heapPtr->entry );
1169 RtlLeaveCriticalSection( &processHeap->critSection );
1171 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1172 RtlDeleteCriticalSection( &heapPtr->critSection );
1174 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1176 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1177 subheap_notify_free_all(subheap);
1178 list_remove( &subheap->entry );
1180 addr = subheap->base;
1181 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1183 subheap_notify_free_all(&heapPtr->subheap);
1185 addr = heapPtr->subheap.base;
1186 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1191 /***********************************************************************
1192 * RtlAllocateHeap (NTDLL.@)
1194 * Allocate a memory block from a Heap.
1197 * heap [I] Heap to allocate block from
1198 * flags [I] HEAP_ flags from "winnt.h"
1199 * size [I] Size of the memory block to allocate
1202 * Success: A pointer to the newly allocated block
1206 * This call does not SetLastError().
1208 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1211 ARENA_INUSE *pInUse;
1213 HEAP *heapPtr = HEAP_GetPtr( heap );
1214 SIZE_T rounded_size;
1216 /* Validate the parameters */
1218 if (!heapPtr) return NULL;
1219 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1220 flags |= heapPtr->flags;
1221 rounded_size = ROUND_SIZE(size);
1222 if (rounded_size < size) /* overflow */
1224 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1227 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1229 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1230 /* Locate a suitable free block */
1232 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1234 TRACE("(%p,%08x,%08lx): returning NULL\n",
1235 heap, flags, size );
1236 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1237 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1241 /* Remove the arena from the free list */
1243 list_remove( &pArena->entry );
1245 /* Build the in-use arena */
1247 pInUse = (ARENA_INUSE *)pArena;
1249 /* in-use arena is smaller than free arena,
1250 * so we have to add the difference to the size */
1251 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1252 pInUse->magic = ARENA_INUSE_MAGIC;
1254 /* Shrink the block */
1256 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1257 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1259 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1261 if (flags & HEAP_ZERO_MEMORY)
1263 clear_block( pInUse + 1, size );
1264 mark_block_uninitialized( (char *)(pInUse + 1) + size, pInUse->unused_bytes );
1267 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1269 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1271 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1272 return (LPVOID)(pInUse + 1);
1276 /***********************************************************************
1277 * RtlFreeHeap (NTDLL.@)
1279 * Free a memory block allocated with RtlAllocateHeap().
1282 * heap [I] Heap that block was allocated from
1283 * flags [I] HEAP_ flags from "winnt.h"
1284 * ptr [I] Block to free
1287 * Success: TRUE, if ptr is NULL or was freed successfully.
1290 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1292 ARENA_INUSE *pInUse;
1296 /* Validate the parameters */
1298 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1300 heapPtr = HEAP_GetPtr( heap );
1303 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1307 flags &= HEAP_NO_SERIALIZE;
1308 flags |= heapPtr->flags;
1309 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1311 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1314 /* Some sanity checks */
1315 pInUse = (ARENA_INUSE *)ptr - 1;
1316 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse ))) goto error;
1317 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1318 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1320 /* Turn the block into a free block */
1322 HEAP_MakeInUseBlockFree( subheap, pInUse );
1324 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1326 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1330 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1331 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1332 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1337 /***********************************************************************
1338 * RtlReAllocateHeap (NTDLL.@)
1340 * Change the size of a memory block allocated with RtlAllocateHeap().
1343 * heap [I] Heap that block was allocated from
1344 * flags [I] HEAP_ flags from "winnt.h"
1345 * ptr [I] Block to resize
1346 * size [I] Size of the memory block to allocate
1349 * Success: A pointer to the resized block (which may be different).
1352 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1354 ARENA_INUSE *pArena;
1357 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1359 if (!ptr) return NULL;
1360 if (!(heapPtr = HEAP_GetPtr( heap )))
1362 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1366 /* Validate the parameters */
1368 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1369 HEAP_REALLOC_IN_PLACE_ONLY;
1370 flags |= heapPtr->flags;
1371 rounded_size = ROUND_SIZE(size);
1372 if (rounded_size < size) /* overflow */
1374 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1375 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1378 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1380 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1382 pArena = (ARENA_INUSE *)ptr - 1;
1383 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena ))) goto error;
1384 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1385 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1387 /* Check if we need to grow the block */
1389 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1390 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1391 if (rounded_size > oldBlockSize)
1393 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1394 if ((pNext < (char *)subheap->base + subheap->size) &&
1395 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1396 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1398 /* The next block is free and large enough */
1399 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1400 list_remove( &pFree->entry );
1401 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1402 if (!HEAP_Commit( subheap, pArena, rounded_size ))
1404 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1405 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1406 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1409 notify_free( pArena + 1 );
1410 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1411 notify_alloc( pArena + 1, size, FALSE );
1412 /* FIXME: this is wrong as we may lose old VBits settings */
1413 mark_block_initialized( pArena + 1, oldActualSize );
1415 else /* Do it the hard way */
1418 ARENA_INUSE *pInUse;
1419 SUBHEAP *newsubheap;
1421 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1422 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1424 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1425 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1426 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1430 /* Build the in-use arena */
1432 list_remove( &pNew->entry );
1433 pInUse = (ARENA_INUSE *)pNew;
1434 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1435 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1436 pInUse->magic = ARENA_INUSE_MAGIC;
1437 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1439 mark_block_initialized( pInUse + 1, oldActualSize );
1440 notify_alloc( pInUse + 1, size, FALSE );
1441 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1443 /* Free the previous block */
1445 notify_free( pArena + 1 );
1446 HEAP_MakeInUseBlockFree( subheap, pArena );
1447 subheap = newsubheap;
1453 /* Shrink the block */
1454 notify_free( pArena + 1 );
1455 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1456 notify_alloc( pArena + 1, size, FALSE );
1457 /* FIXME: this is wrong as we may lose old VBits settings */
1458 mark_block_initialized( pArena + 1, size );
1461 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1463 /* Clear the extra bytes if needed */
1465 if (size > oldActualSize)
1467 if (flags & HEAP_ZERO_MEMORY)
1469 clear_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize );
1470 mark_block_uninitialized( (char *)(pArena + 1) + size, pArena->unused_bytes );
1473 mark_block_uninitialized( (char *)(pArena + 1) + oldActualSize,
1474 (pArena->size & ARENA_SIZE_MASK) - oldActualSize );
1477 /* Return the new arena */
1479 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1481 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1482 return (LPVOID)(pArena + 1);
1485 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1486 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1487 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1492 /***********************************************************************
1493 * RtlCompactHeap (NTDLL.@)
1495 * Compact the free space in a Heap.
1498 * heap [I] Heap that block was allocated from
1499 * flags [I] HEAP_ flags from "winnt.h"
1502 * The number of bytes compacted.
1505 * This function is a harmless stub.
1507 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1509 static BOOL reported;
1510 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1515 /***********************************************************************
1516 * RtlLockHeap (NTDLL.@)
1521 * heap [I] Heap to lock
1524 * Success: TRUE. The Heap is locked.
1525 * Failure: FALSE, if heap is invalid.
1527 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1529 HEAP *heapPtr = HEAP_GetPtr( heap );
1530 if (!heapPtr) return FALSE;
1531 RtlEnterCriticalSection( &heapPtr->critSection );
1536 /***********************************************************************
1537 * RtlUnlockHeap (NTDLL.@)
1542 * heap [I] Heap to unlock
1545 * Success: TRUE. The Heap is unlocked.
1546 * Failure: FALSE, if heap is invalid.
1548 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1550 HEAP *heapPtr = HEAP_GetPtr( heap );
1551 if (!heapPtr) return FALSE;
1552 RtlLeaveCriticalSection( &heapPtr->critSection );
1557 /***********************************************************************
1558 * RtlSizeHeap (NTDLL.@)
1560 * Get the actual size of a memory block allocated from a Heap.
1563 * heap [I] Heap that block was allocated from
1564 * flags [I] HEAP_ flags from "winnt.h"
1565 * ptr [I] Block to get the size of
1568 * Success: The size of the block.
1569 * Failure: -1, heap or ptr are invalid.
1572 * The size may be bigger than what was passed to RtlAllocateHeap().
1574 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1577 HEAP *heapPtr = HEAP_GetPtr( heap );
1581 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1584 flags &= HEAP_NO_SERIALIZE;
1585 flags |= heapPtr->flags;
1586 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1587 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1589 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1594 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1595 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1597 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1599 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1604 /***********************************************************************
1605 * RtlValidateHeap (NTDLL.@)
1607 * Determine if a block is a valid allocation from a heap.
1610 * heap [I] Heap that block was allocated from
1611 * flags [I] HEAP_ flags from "winnt.h"
1612 * ptr [I] Block to check
1615 * Success: TRUE. The block was allocated from heap.
1616 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1618 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1620 HEAP *heapPtr = HEAP_GetPtr( heap );
1621 if (!heapPtr) return FALSE;
1622 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1626 /***********************************************************************
1627 * RtlWalkHeap (NTDLL.@)
1630 * The PROCESS_HEAP_ENTRY flag values seem different between this
1631 * function and HeapWalk(). To be checked.
1633 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1635 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1636 HEAP *heapPtr = HEAP_GetPtr(heap);
1637 SUBHEAP *sub, *currentheap = NULL;
1640 int region_index = 0;
1642 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1644 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1646 /* set ptr to the next arena to be examined */
1648 if (!entry->lpData) /* first call (init) ? */
1650 TRACE("begin walking of heap %p.\n", heap);
1651 currentheap = &heapPtr->subheap;
1652 ptr = (char*)currentheap->base + currentheap->headerSize;
1656 ptr = entry->lpData;
1657 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1659 if ((ptr >= (char *)sub->base) &&
1660 (ptr < (char *)sub->base + sub->size))
1667 if (currentheap == NULL)
1669 ERR("no matching subheap found, shouldn't happen !\n");
1670 ret = STATUS_NO_MORE_ENTRIES;
1674 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1676 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1677 ptr += pArena->size & ARENA_SIZE_MASK;
1679 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1681 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1682 ptr += pArena->size & ARENA_SIZE_MASK;
1685 ptr += entry->cbData; /* point to next arena */
1687 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1688 { /* proceed with next subheap */
1689 struct list *next = list_next( &heapPtr->subheap_list, ¤theap->entry );
1691 { /* successfully finished */
1692 TRACE("end reached.\n");
1693 ret = STATUS_NO_MORE_ENTRIES;
1696 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1697 ptr = (char *)currentheap->base + currentheap->headerSize;
1702 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1704 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1706 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1708 entry->lpData = pArena + 1;
1709 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1710 entry->cbOverhead = sizeof(ARENA_FREE);
1711 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1715 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1717 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1719 entry->lpData = pArena + 1;
1720 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1721 entry->cbOverhead = sizeof(ARENA_INUSE);
1722 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1723 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1724 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1727 entry->iRegionIndex = region_index;
1729 /* first element of heap ? */
1730 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1732 entry->wFlags |= PROCESS_HEAP_REGION;
1733 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1734 entry->u.Region.dwUnCommittedSize =
1735 currentheap->size - currentheap->commitSize;
1736 entry->u.Region.lpFirstBlock = /* first valid block */
1737 (char *)currentheap->base + currentheap->headerSize;
1738 entry->u.Region.lpLastBlock = /* first invalid block */
1739 (char *)currentheap->base + currentheap->size;
1741 ret = STATUS_SUCCESS;
1742 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1745 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1750 /***********************************************************************
1751 * RtlGetProcessHeaps (NTDLL.@)
1753 * Get the Heaps belonging to the current process.
1756 * count [I] size of heaps
1757 * heaps [O] Destination array for heap HANDLE's
1760 * Success: The number of Heaps allocated by the process.
1763 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1765 ULONG total = 1; /* main heap */
1768 RtlEnterCriticalSection( &processHeap->critSection );
1769 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1772 *heaps++ = processHeap;
1773 LIST_FOR_EACH( ptr, &processHeap->entry )
1774 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1776 RtlLeaveCriticalSection( &processHeap->critSection );