4 * Copyright 1996 Alexandre Julliard
5 * Copyright 1998 Ulrich Weigand
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include "wine/port.h"
30 #ifdef HAVE_VALGRIND_MEMCHECK_H
31 #include <valgrind/memcheck.h>
34 #define NONAMELESSUNION
35 #define NONAMELESSSTRUCT
37 #define WIN32_NO_STATUS
41 #include "wine/list.h"
42 #include "wine/debug.h"
43 #include "wine/server.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(heap);
47 /* Note: the heap data structures are loosely based on what Pietrek describes in his
48 * book 'Windows 95 System Programming Secrets', with some adaptations for
49 * better compatibility with NT.
52 typedef struct tagARENA_INUSE
54 DWORD size; /* Block size; must be the first field */
55 DWORD magic : 24; /* Magic number */
56 DWORD unused_bytes : 8; /* Number of bytes in the block not used by user data (max value is HEAP_MIN_DATA_SIZE+HEAP_MIN_SHRINK_SIZE) */
59 typedef struct tagARENA_FREE
61 DWORD size; /* Block size; must be the first field */
62 DWORD magic; /* Magic number */
63 struct list entry; /* Entry in free list */
68 struct list entry; /* entry in heap large blocks list */
69 SIZE_T data_size; /* size of user data */
70 SIZE_T block_size; /* total size of virtual memory block */
71 DWORD pad[2]; /* padding to ensure 16-byte alignment of data */
72 DWORD size; /* fields for compatibility with normal arenas */
73 DWORD magic; /* these must remain at the end of the structure */
76 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
77 #define ARENA_FLAG_PREV_FREE 0x00000002
78 #define ARENA_SIZE_MASK (~3)
79 #define ARENA_LARGE_SIZE 0xfedcba90 /* magic value for 'size' field in large blocks */
81 /* Value for arena 'magic' field */
82 #define ARENA_INUSE_MAGIC 0x455355
83 #define ARENA_FREE_MAGIC 0x45455246
84 #define ARENA_LARGE_MAGIC 0x6752614c
86 #define ARENA_INUSE_FILLER 0x55
87 #define ARENA_TAIL_FILLER 0xab
88 #define ARENA_FREE_FILLER 0xfeeefeee
90 /* everything is aligned on 8 byte boundaries (16 for Win64) */
91 #define ALIGNMENT (2*sizeof(void*))
92 #define LARGE_ALIGNMENT 16 /* large blocks have stricter alignment */
93 #define ARENA_OFFSET (ALIGNMENT - sizeof(ARENA_INUSE))
95 C_ASSERT( sizeof(ARENA_LARGE) % LARGE_ALIGNMENT == 0 );
97 #define ROUND_SIZE(size) ((((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1)) + ARENA_OFFSET)
99 #define QUIET 1 /* Suppress messages */
100 #define NOISY 0 /* Report all errors */
102 /* minimum data size (without arenas) of an allocated block */
103 /* make sure that it's larger than a free list entry */
104 #define HEAP_MIN_DATA_SIZE ROUND_SIZE(2 * sizeof(struct list))
105 /* minimum size that must remain to shrink an allocated block */
106 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
107 /* minimum size to start allocating large blocks */
108 #define HEAP_MIN_LARGE_BLOCK_SIZE 0x7f000
110 /* Max size of the blocks on the free lists */
111 static const SIZE_T HEAP_freeListSizes[] =
113 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
115 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
125 typedef struct tagSUBHEAP
127 void *base; /* Base address of the sub-heap memory block */
128 SIZE_T size; /* Size of the whole sub-heap */
129 SIZE_T min_commit; /* Minimum committed size */
130 SIZE_T commitSize; /* Committed size of the sub-heap */
131 struct list entry; /* Entry in sub-heap list */
132 struct tagHEAP *heap; /* Main heap structure */
133 DWORD headerSize; /* Size of the heap header */
134 DWORD magic; /* Magic number */
137 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
139 typedef struct tagHEAP
142 DWORD flags; /* Heap flags */
143 DWORD force_flags; /* Forced heap flags for debugging */
144 SUBHEAP subheap; /* First sub-heap */
145 struct list entry; /* Entry in process heap list */
146 struct list subheap_list; /* Sub-heap list */
147 struct list large_list; /* Large blocks list */
148 SIZE_T grow_size; /* Size of next subheap for growing heap */
149 DWORD magic; /* Magic number */
150 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
151 FREE_LIST_ENTRY *freeList; /* Free lists */
154 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
156 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
157 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
159 /* some undocumented flags (names are made up) */
160 #define HEAP_PAGE_ALLOCS 0x01000000
161 #define HEAP_VALIDATE 0x10000000
162 #define HEAP_VALIDATE_ALL 0x20000000
163 #define HEAP_VALIDATE_PARAMS 0x40000000
165 static HEAP *processHeap; /* main process heap */
167 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
169 /* mark a block of memory as free for debugging purposes */
170 static inline void mark_block_free( void *ptr, SIZE_T size, DWORD flags )
172 if (flags & HEAP_FREE_CHECKING_ENABLED)
175 for (i = 0; i < size / sizeof(DWORD); i++) ((DWORD *)ptr)[i] = ARENA_FREE_FILLER;
177 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
178 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
179 #elif defined( VALGRIND_MAKE_NOACCESS)
180 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
184 /* mark a block of memory as initialized for debugging purposes */
185 static inline void mark_block_initialized( void *ptr, SIZE_T size )
187 #if defined(VALGRIND_MAKE_MEM_DEFINED)
188 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
189 #elif defined(VALGRIND_MAKE_READABLE)
190 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
194 /* mark a block of memory as uninitialized for debugging purposes */
195 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
197 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
198 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
199 #elif defined(VALGRIND_MAKE_WRITABLE)
200 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
204 /* mark a block of memory as a tail block */
205 static inline void mark_block_tail( void *ptr, SIZE_T size, DWORD flags )
207 mark_block_uninitialized( ptr, size );
208 if (flags & HEAP_TAIL_CHECKING_ENABLED)
210 memset( ptr, ARENA_TAIL_FILLER, size );
211 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
212 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
213 #elif defined( VALGRIND_MAKE_NOACCESS)
214 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
219 /* initialize contents of a newly created block of memory */
220 static inline void initialize_block( void *ptr, SIZE_T size, SIZE_T unused, DWORD flags )
222 if (flags & HEAP_ZERO_MEMORY)
224 mark_block_initialized( ptr, size );
225 memset( ptr, 0, size );
229 mark_block_uninitialized( ptr, size );
230 if (flags & HEAP_FREE_CHECKING_ENABLED)
232 memset( ptr, ARENA_INUSE_FILLER, size );
233 mark_block_uninitialized( ptr, size );
237 mark_block_tail( (char *)ptr + size, unused, flags );
240 /* notify that a new block of memory has been allocated for debugging purposes */
241 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
243 #ifdef VALGRIND_MALLOCLIKE_BLOCK
244 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
248 /* notify that a block of memory has been freed for debugging purposes */
249 static inline void notify_free( void const *ptr )
251 #ifdef VALGRIND_FREELIKE_BLOCK
252 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
256 static void subheap_notify_free_all(SUBHEAP const *subheap)
258 #ifdef VALGRIND_FREELIKE_BLOCK
259 char const *ptr = (char const *)subheap->base + subheap->headerSize;
261 if (!RUNNING_ON_VALGRIND) return;
263 while (ptr < (char const *)subheap->base + subheap->size)
265 if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
267 ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
268 if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
269 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
273 ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
274 if (pArena->magic!=ARENA_INUSE_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
275 notify_free(pArena + 1);
276 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
282 /* locate a free list entry of the appropriate size */
283 /* size is the size of the whole block including the arena header */
284 static inline unsigned int get_freelist_index( SIZE_T size )
288 size -= sizeof(ARENA_FREE);
289 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
293 /* get the memory protection type to use for a given heap */
294 static inline ULONG get_protection_type( DWORD flags )
296 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
299 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
301 0, 0, NULL, /* will be set later */
302 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
303 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
307 /***********************************************************************
310 static void HEAP_Dump( HEAP *heap )
316 DPRINTF( "Heap: %p\n", heap );
317 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
318 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
320 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
321 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
322 DPRINTF( "%p free %08lx prev=%p next=%p\n",
323 &heap->freeList[i].arena, HEAP_freeListSizes[i],
324 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
325 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
327 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
329 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
330 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
331 subheap, subheap->base, subheap->size, subheap->commitSize );
333 DPRINTF( "\n Block Arena Stat Size Id\n" );
334 ptr = (char *)subheap->base + subheap->headerSize;
335 while (ptr < (char *)subheap->base + subheap->size)
337 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
339 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
340 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
341 pArena, pArena->magic,
342 pArena->size & ARENA_SIZE_MASK,
343 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
344 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
345 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
346 arenaSize += sizeof(ARENA_FREE);
347 freeSize += pArena->size & ARENA_SIZE_MASK;
349 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
351 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
352 DPRINTF( "%p %08x Used %08x back=%p\n",
353 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
354 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
355 arenaSize += sizeof(ARENA_INUSE);
356 usedSize += pArena->size & ARENA_SIZE_MASK;
360 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
361 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
362 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
363 arenaSize += sizeof(ARENA_INUSE);
364 usedSize += pArena->size & ARENA_SIZE_MASK;
367 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
368 subheap->size, subheap->commitSize, freeSize, usedSize,
369 arenaSize, (arenaSize * 100) / subheap->size );
374 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
377 TRACE( "Dumping entry %p\n", entry );
378 TRACE( "lpData\t\t: %p\n", entry->lpData );
379 TRACE( "cbData\t\t: %08x\n", entry->cbData);
380 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
381 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
382 TRACE( "WFlags\t\t: ");
383 if (entry->wFlags & PROCESS_HEAP_REGION)
384 TRACE( "PROCESS_HEAP_REGION ");
385 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
386 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
387 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
388 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
389 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
390 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
391 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
392 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
393 rem_flags = entry->wFlags &
394 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
395 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
396 PROCESS_HEAP_ENTRY_DDESHARE);
398 TRACE( "Unknown %08x", rem_flags);
400 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
401 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
404 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
406 if (entry->wFlags & PROCESS_HEAP_REGION)
408 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
409 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
410 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
411 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
415 /***********************************************************************
418 * Pointer to the heap
421 static HEAP *HEAP_GetPtr(
422 HANDLE heap /* [in] Handle to the heap */
424 HEAP *heapPtr = heap;
425 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
427 ERR("Invalid heap %p!\n", heap );
430 if ((heapPtr->flags & HEAP_VALIDATE_ALL) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
434 HEAP_Dump( heapPtr );
443 /***********************************************************************
444 * HEAP_InsertFreeBlock
446 * Insert a free block into the free list.
448 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
450 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
453 /* insert at end of free list, i.e. before the next free list entry */
455 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
456 list_add_before( &pEntry->arena.entry, &pArena->entry );
460 /* insert at head of free list */
461 list_add_after( &pEntry->arena.entry, &pArena->entry );
463 pArena->size |= ARENA_FLAG_FREE;
467 /***********************************************************************
469 * Find the sub-heap containing a given address.
475 static SUBHEAP *HEAP_FindSubHeap(
476 const HEAP *heap, /* [in] Heap pointer */
477 LPCVOID ptr ) /* [in] Address */
480 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
481 if ((ptr >= sub->base) &&
482 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
488 /***********************************************************************
491 * Make sure the heap storage is committed for a given size in the specified arena.
493 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
495 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
496 SIZE_T size = (char *)ptr - (char *)subheap->base;
497 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
498 if (size > subheap->size) size = subheap->size;
499 if (size <= subheap->commitSize) return TRUE;
500 size -= subheap->commitSize;
501 ptr = (char *)subheap->base + subheap->commitSize;
502 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
503 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
505 WARN("Could not commit %08lx bytes at %p for heap %p\n",
506 size, ptr, subheap->heap );
509 subheap->commitSize += size;
514 /***********************************************************************
517 * If possible, decommit the heap storage from (including) 'ptr'.
519 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
522 SIZE_T decommit_size;
523 SIZE_T size = (char *)ptr - (char *)subheap->base;
525 /* round to next block and add one full block */
526 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
527 size = max( size, subheap->min_commit );
528 if (size >= subheap->commitSize) return TRUE;
529 decommit_size = subheap->commitSize - size;
530 addr = (char *)subheap->base + size;
532 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
534 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
535 decommit_size, (char *)subheap->base + size, subheap->heap );
538 subheap->commitSize -= decommit_size;
543 /***********************************************************************
544 * HEAP_CreateFreeBlock
546 * Create a free block at a specified address. 'size' is the size of the
547 * whole block, including the new arena.
549 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
554 DWORD flags = subheap->heap->flags;
556 /* Create a free arena */
557 mark_block_uninitialized( ptr, sizeof(ARENA_FREE) );
559 pFree->magic = ARENA_FREE_MAGIC;
561 /* If debugging, erase the freed block content */
563 pEnd = (char *)ptr + size;
564 if (pEnd > (char *)subheap->base + subheap->commitSize)
565 pEnd = (char *)subheap->base + subheap->commitSize;
566 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1), flags );
568 /* Check if next block is free also */
570 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
571 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
573 /* Remove the next arena from the free list */
574 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
575 list_remove( &pNext->entry );
576 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
577 mark_block_free( pNext, sizeof(ARENA_FREE), flags );
580 /* Set the next block PREV_FREE flag and pointer */
582 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
585 DWORD *pNext = (DWORD *)((char *)ptr + size);
586 *pNext |= ARENA_FLAG_PREV_FREE;
587 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
588 *((ARENA_FREE **)pNext - 1) = pFree;
591 /* Last, insert the new block into the free list */
593 pFree->size = size - sizeof(*pFree);
594 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
598 /***********************************************************************
599 * HEAP_MakeInUseBlockFree
601 * Turn an in-use block into a free block. Can also decommit the end of
602 * the heap, and possibly even free the sub-heap altogether.
604 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
607 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
609 /* Check if we can merge with previous block */
611 if (pArena->size & ARENA_FLAG_PREV_FREE)
613 pFree = *((ARENA_FREE **)pArena - 1);
614 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
615 /* Remove it from the free list */
616 list_remove( &pFree->entry );
618 else pFree = (ARENA_FREE *)pArena;
620 /* Create a free block */
622 HEAP_CreateFreeBlock( subheap, pFree, size );
623 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
624 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
625 return; /* Not the last block, so nothing more to do */
627 /* Free the whole sub-heap if it's empty and not the original one */
629 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
630 (subheap != &subheap->heap->subheap))
633 void *addr = subheap->base;
634 /* Remove the free block from the list */
635 list_remove( &pFree->entry );
636 /* Remove the subheap from the list */
637 list_remove( &subheap->entry );
638 /* Free the memory */
640 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
644 /* Decommit the end of the heap */
646 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
650 /***********************************************************************
653 * Shrink an in-use block.
655 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
657 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
659 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
660 (pArena->size & ARENA_SIZE_MASK) - size );
661 /* assign size plus previous arena flags */
662 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
666 /* Turn off PREV_FREE flag in next block */
667 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
668 if (pNext < (char *)subheap->base + subheap->size)
669 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
674 /***********************************************************************
675 * allocate_large_block
677 static void *allocate_large_block( HEAP *heap, DWORD flags, SIZE_T size )
680 SIZE_T block_size = sizeof(*arena) + ROUND_SIZE(size);
681 LPVOID address = NULL;
683 if (block_size < size) return NULL; /* overflow */
684 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 5,
685 &block_size, MEM_COMMIT, get_protection_type( flags ) ))
687 WARN("Could not allocate block for %08lx bytes\n", size );
691 arena->data_size = size;
692 arena->block_size = block_size;
693 arena->size = ARENA_LARGE_SIZE;
694 arena->magic = ARENA_LARGE_MAGIC;
695 list_add_tail( &heap->large_list, &arena->entry );
696 notify_alloc( arena + 1, size, flags & HEAP_ZERO_MEMORY );
701 /***********************************************************************
704 static void free_large_block( HEAP *heap, DWORD flags, void *ptr )
706 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
707 LPVOID address = arena;
710 list_remove( &arena->entry );
711 NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
715 /***********************************************************************
716 * realloc_large_block
718 static void *realloc_large_block( HEAP *heap, DWORD flags, void *ptr, SIZE_T size )
720 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
723 if (arena->block_size - sizeof(*arena) >= size)
725 /* FIXME: we could remap zero-pages instead */
726 if ((flags & HEAP_ZERO_MEMORY) && size > arena->data_size)
727 memset( (char *)ptr + arena->data_size, 0, size - arena->data_size );
728 arena->data_size = size;
731 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) return NULL;
732 if (!(new_ptr = allocate_large_block( heap, flags, size )))
734 WARN("Could not allocate block for %08lx bytes\n", size );
737 memcpy( new_ptr, ptr, arena->data_size );
738 free_large_block( heap, flags, ptr );
743 /***********************************************************************
746 static ARENA_LARGE *find_large_block( HEAP *heap, const void *ptr )
750 LIST_FOR_EACH_ENTRY( arena, &heap->large_list, ARENA_LARGE, entry )
751 if (ptr == arena + 1) return arena;
757 /***********************************************************************
758 * validate_large_arena
760 static BOOL validate_large_arena( HEAP *heap, const ARENA_LARGE *arena, BOOL quiet )
762 if ((ULONG_PTR)arena % getpagesize())
766 ERR( "Heap %p: invalid large arena pointer %p\n", heap, arena );
767 if (TRACE_ON(heap)) HEAP_Dump( heap );
769 else if (WARN_ON(heap))
771 WARN( "Heap %p: unaligned arena pointer %p\n", heap, arena );
772 if (TRACE_ON(heap)) HEAP_Dump( heap );
776 if (arena->size != ARENA_LARGE_SIZE || arena->magic != ARENA_LARGE_MAGIC)
780 ERR( "Heap %p: invalid large arena %p values %x/%x\n",
781 heap, arena, arena->size, arena->magic );
782 if (TRACE_ON(heap)) HEAP_Dump( heap );
784 else if (WARN_ON(heap))
786 WARN( "Heap %p: invalid large arena %p values %x/%x\n",
787 heap, arena, arena->size, arena->magic );
788 if (TRACE_ON(heap)) HEAP_Dump( heap );
796 /***********************************************************************
799 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, LPVOID address, DWORD flags,
800 SIZE_T commitSize, SIZE_T totalSize )
803 FREE_LIST_ENTRY *pEntry;
808 /* round-up sizes on a 64K boundary */
809 totalSize = (totalSize + 0xffff) & 0xffff0000;
810 commitSize = (commitSize + 0xffff) & 0xffff0000;
811 if (!commitSize) commitSize = 0x10000;
812 totalSize = min( totalSize, 0xffff0000 ); /* don't allow a heap larger than 4Gb */
813 if (totalSize < commitSize) totalSize = commitSize;
814 if (flags & HEAP_SHARED) commitSize = totalSize; /* always commit everything in a shared heap */
816 /* allocate the memory block */
817 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
818 MEM_RESERVE, get_protection_type( flags ) ))
820 WARN("Could not allocate %08lx bytes\n", totalSize );
823 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
824 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
826 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
833 /* If this is a secondary subheap, insert it into list */
836 subheap->base = address;
837 subheap->heap = heap;
838 subheap->size = totalSize;
839 subheap->min_commit = 0x10000;
840 subheap->commitSize = commitSize;
841 subheap->magic = SUBHEAP_MAGIC;
842 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
843 list_add_head( &heap->subheap_list, &subheap->entry );
847 /* If this is a primary subheap, initialize main heap */
851 heap->magic = HEAP_MAGIC;
852 heap->grow_size = max( HEAP_DEF_SIZE, totalSize );
853 list_init( &heap->subheap_list );
854 list_init( &heap->large_list );
856 subheap = &heap->subheap;
857 subheap->base = address;
858 subheap->heap = heap;
859 subheap->size = totalSize;
860 subheap->min_commit = commitSize;
861 subheap->commitSize = commitSize;
862 subheap->magic = SUBHEAP_MAGIC;
863 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
864 list_add_head( &heap->subheap_list, &subheap->entry );
866 /* Build the free lists */
868 heap->freeList = (FREE_LIST_ENTRY *)((char *)heap + subheap->headerSize);
869 subheap->headerSize += HEAP_NB_FREE_LISTS * sizeof(FREE_LIST_ENTRY);
870 list_init( &heap->freeList[0].arena.entry );
871 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
873 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
874 pEntry->arena.magic = ARENA_FREE_MAGIC;
875 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
878 /* Initialize critical section */
880 if (!processHeap) /* do it by hand to avoid memory allocations */
882 heap->critSection.DebugInfo = &process_heap_critsect_debug;
883 heap->critSection.LockCount = -1;
884 heap->critSection.RecursionCount = 0;
885 heap->critSection.OwningThread = 0;
886 heap->critSection.LockSemaphore = 0;
887 heap->critSection.SpinCount = 0;
888 process_heap_critsect_debug.CriticalSection = &heap->critSection;
892 RtlInitializeCriticalSection( &heap->critSection );
893 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
896 if (flags & HEAP_SHARED)
898 /* let's assume that only one thread at a time will try to do this */
899 HANDLE sem = heap->critSection.LockSemaphore;
900 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
902 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
903 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
904 heap->critSection.LockSemaphore = sem;
905 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
906 heap->critSection.DebugInfo = NULL;
910 /* Create the first free block */
912 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
913 subheap->size - subheap->headerSize );
919 /***********************************************************************
922 * Find a free block at least as large as the requested size, and make sure
923 * the requested size is committed.
925 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
926 SUBHEAP **ppSubHeap )
931 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
933 /* Find a suitable free list, and in it find a block large enough */
935 ptr = &pEntry->arena.entry;
936 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
938 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
939 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
940 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
941 if (arena_size >= size)
943 subheap = HEAP_FindSubHeap( heap, pArena );
944 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
945 *ppSubHeap = subheap;
950 /* If no block was found, attempt to grow the heap */
952 if (!(heap->flags & HEAP_GROWABLE))
954 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
957 /* make sure that we have a big enough size *committed* to fit another
958 * last free arena in !
959 * So just one heap struct, one first free arena which will eventually
960 * get used, and a second free arena that might get assigned all remaining
961 * free space in HEAP_ShrinkBlock() */
962 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
963 if (total_size < size) return NULL; /* overflow */
965 if ((subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
966 max( heap->grow_size, total_size ) )))
968 if (heap->grow_size < 128 * 1024 * 1024) heap->grow_size *= 2;
970 else while (!subheap) /* shrink the grow size again if we are running out of space */
972 if (heap->grow_size <= total_size || heap->grow_size <= 4 * 1024 * 1024) return NULL;
973 heap->grow_size /= 2;
974 subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
975 max( heap->grow_size, total_size ) );
978 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
979 subheap, subheap->size, heap );
981 *ppSubHeap = subheap;
982 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
986 /***********************************************************************
987 * HEAP_IsValidArenaPtr
989 * Check that the pointer is inside the range possible for arenas.
991 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
994 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
995 if (!subheap) return FALSE;
996 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
997 if (subheap != &heap->subheap) return FALSE;
998 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
999 if (ptr == &heap->freeList[i].arena) return TRUE;
1004 /***********************************************************************
1005 * HEAP_ValidateFreeArena
1007 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
1009 DWORD flags = subheap->heap->flags;
1011 ARENA_FREE *prev, *next;
1012 char *heapEnd = (char *)subheap->base + subheap->size;
1014 /* Check for unaligned pointers */
1015 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1017 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1021 /* Check magic number */
1022 if (pArena->magic != ARENA_FREE_MAGIC)
1024 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1027 /* Check size flags */
1028 if (!(pArena->size & ARENA_FLAG_FREE) ||
1029 (pArena->size & ARENA_FLAG_PREV_FREE))
1031 ERR("Heap %p: bad flags %08x for free arena %p\n",
1032 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1035 /* Check arena size */
1036 size = pArena->size & ARENA_SIZE_MASK;
1037 if ((char *)(pArena + 1) + size > heapEnd)
1039 ERR("Heap %p: bad size %08lx for free arena %p\n", subheap->heap, size, pArena );
1042 /* Check that next pointer is valid */
1043 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
1044 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
1046 ERR("Heap %p: bad next ptr %p for arena %p\n",
1047 subheap->heap, next, pArena );
1050 /* Check that next arena is free */
1051 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1053 ERR("Heap %p: next arena %p invalid for %p\n",
1054 subheap->heap, next, pArena );
1057 /* Check that prev pointer is valid */
1058 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1059 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1061 ERR("Heap %p: bad prev ptr %p for arena %p\n",
1062 subheap->heap, prev, pArena );
1065 /* Check that prev arena is free */
1066 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1068 /* this often means that the prev arena got overwritten
1069 * by a memory write before that prev arena */
1070 ERR("Heap %p: prev arena %p invalid for %p\n",
1071 subheap->heap, prev, pArena );
1074 /* Check that next block has PREV_FREE flag */
1075 if ((char *)(pArena + 1) + size < heapEnd)
1077 if (!(*(DWORD *)((char *)(pArena + 1) + size) & ARENA_FLAG_PREV_FREE))
1079 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1080 subheap->heap, pArena );
1083 /* Check next block back pointer */
1084 if (*((ARENA_FREE **)((char *)(pArena + 1) + size) - 1) != pArena)
1086 ERR("Heap %p: arena %p has wrong back ptr %p\n",
1087 subheap->heap, pArena,
1088 *((ARENA_FREE **)((char *)(pArena+1) + size) - 1));
1092 if (flags & HEAP_FREE_CHECKING_ENABLED)
1094 DWORD *ptr = (DWORD *)(pArena + 1);
1095 char *end = (char *)(pArena + 1) + size;
1097 if (end >= heapEnd) end = (char *)subheap->base + subheap->commitSize;
1098 while (ptr < (DWORD *)end - 1)
1100 if (*ptr != ARENA_FREE_FILLER)
1102 ERR("Heap %p: free block %p overwritten at %p by %08x\n",
1103 subheap->heap, (ARENA_INUSE *)pArena + 1, ptr, *ptr );
1113 /***********************************************************************
1114 * HEAP_ValidateInUseArena
1116 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1119 DWORD i, flags = subheap->heap->flags;
1120 const char *heapEnd = (const char *)subheap->base + subheap->size;
1122 /* Check for unaligned pointers */
1123 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1125 if ( quiet == NOISY )
1127 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1128 if ( TRACE_ON(heap) )
1129 HEAP_Dump( subheap->heap );
1131 else if ( WARN_ON(heap) )
1133 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1134 if ( TRACE_ON(heap) )
1135 HEAP_Dump( subheap->heap );
1140 /* Check magic number */
1141 if (pArena->magic != ARENA_INUSE_MAGIC)
1143 if (quiet == NOISY) {
1144 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1146 HEAP_Dump( subheap->heap );
1147 } else if (WARN_ON(heap)) {
1148 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1150 HEAP_Dump( subheap->heap );
1154 /* Check size flags */
1155 if (pArena->size & ARENA_FLAG_FREE)
1157 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1158 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1161 /* Check arena size */
1162 size = pArena->size & ARENA_SIZE_MASK;
1163 if ((const char *)(pArena + 1) + size > heapEnd ||
1164 (const char *)(pArena + 1) + size < (const char *)(pArena + 1))
1166 ERR("Heap %p: bad size %08lx for in-use arena %p\n", subheap->heap, size, pArena );
1169 /* Check next arena PREV_FREE flag */
1170 if (((const char *)(pArena + 1) + size < heapEnd) &&
1171 (*(const DWORD *)((const char *)(pArena + 1) + size) & ARENA_FLAG_PREV_FREE))
1173 ERR("Heap %p: in-use arena %p next block %p has PREV_FREE flag %x\n",
1174 subheap->heap, pArena, (const char *)(pArena + 1) + size,*(const DWORD *)((const char *)(pArena + 1) + size) );
1177 /* Check prev free arena */
1178 if (pArena->size & ARENA_FLAG_PREV_FREE)
1180 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1181 /* Check prev pointer */
1182 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1184 ERR("Heap %p: bad back ptr %p for arena %p\n",
1185 subheap->heap, pPrev, pArena );
1188 /* Check that prev arena is free */
1189 if (!(pPrev->size & ARENA_FLAG_FREE) ||
1190 (pPrev->magic != ARENA_FREE_MAGIC))
1192 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1193 subheap->heap, pPrev, pArena );
1196 /* Check that prev arena is really the previous block */
1197 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1199 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1200 subheap->heap, pPrev, pArena );
1204 /* Check unused size */
1205 if (pArena->unused_bytes > size)
1207 ERR("Heap %p: invalid unused size %08x/%08lx\n", subheap->heap, pArena->unused_bytes, size );
1210 /* Check unused bytes */
1211 if (flags & HEAP_TAIL_CHECKING_ENABLED)
1213 const unsigned char *data = (const unsigned char *)(pArena + 1) + size - pArena->unused_bytes;
1215 for (i = 0; i < pArena->unused_bytes; i++)
1217 if (data[i] == ARENA_TAIL_FILLER) continue;
1218 ERR("Heap %p: block %p tail overwritten at %p (byte %u/%u == 0x%02x)\n",
1219 subheap->heap, pArena + 1, data + i, i, pArena->unused_bytes, data[i] );
1227 /***********************************************************************
1228 * HEAP_IsRealArena [Internal]
1229 * Validates a block is a valid arena.
1235 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1236 DWORD flags, /* [in] Bit flags that control access during operation */
1237 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1238 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1239 * does not complain */
1243 const ARENA_LARGE *large_arena;
1245 flags &= HEAP_NO_SERIALIZE;
1246 flags |= heapPtr->flags;
1247 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1248 if (!(flags & HEAP_NO_SERIALIZE))
1249 RtlEnterCriticalSection( &heapPtr->critSection );
1251 if (block) /* only check this single memory block */
1253 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1255 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1256 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1258 if (!(large_arena = find_large_block( heapPtr, block )))
1261 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1262 else if (WARN_ON(heap))
1263 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1267 ret = validate_large_arena( heapPtr, large_arena, quiet );
1269 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1271 if (!(flags & HEAP_NO_SERIALIZE))
1272 RtlLeaveCriticalSection( &heapPtr->critSection );
1276 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1278 char *ptr = (char *)subheap->base + subheap->headerSize;
1279 while (ptr < (char *)subheap->base + subheap->size)
1281 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1283 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1287 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1291 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1295 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1301 LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1302 if (!(ret = validate_large_arena( heapPtr, large_arena, quiet ))) break;
1304 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1309 /***********************************************************************
1310 * heap_set_debug_flags
1312 void heap_set_debug_flags( HANDLE handle )
1314 HEAP *heap = HEAP_GetPtr( handle );
1315 ULONG global_flags = RtlGetNtGlobalFlags();
1318 if (TRACE_ON(heap)) global_flags |= FLG_HEAP_VALIDATE_ALL;
1319 if (WARN_ON(heap)) global_flags |= FLG_HEAP_VALIDATE_PARAMETERS;
1321 if (global_flags & FLG_HEAP_ENABLE_TAIL_CHECK) flags |= HEAP_TAIL_CHECKING_ENABLED;
1322 if (global_flags & FLG_HEAP_ENABLE_FREE_CHECK) flags |= HEAP_FREE_CHECKING_ENABLED;
1323 if (global_flags & FLG_HEAP_DISABLE_COALESCING) flags |= HEAP_DISABLE_COALESCE_ON_FREE;
1324 if (global_flags & FLG_HEAP_PAGE_ALLOCS) flags |= HEAP_PAGE_ALLOCS | HEAP_GROWABLE;
1326 if (global_flags & FLG_HEAP_VALIDATE_PARAMETERS)
1327 flags |= HEAP_VALIDATE | HEAP_VALIDATE_PARAMS |
1328 HEAP_TAIL_CHECKING_ENABLED | HEAP_FREE_CHECKING_ENABLED;
1329 if (global_flags & FLG_HEAP_VALIDATE_ALL)
1330 flags |= HEAP_VALIDATE | HEAP_VALIDATE_ALL |
1331 HEAP_TAIL_CHECKING_ENABLED | HEAP_FREE_CHECKING_ENABLED;
1333 heap->flags |= flags;
1334 heap->force_flags |= flags & ~(HEAP_VALIDATE | HEAP_DISABLE_COALESCE_ON_FREE);
1336 if (flags & (HEAP_FREE_CHECKING_ENABLED | HEAP_TAIL_CHECKING_ENABLED)) /* fix existing blocks */
1340 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
1342 char *ptr = (char *)subheap->base + subheap->headerSize;
1343 char *end = (char *)subheap->base + subheap->commitSize;
1346 ARENA_INUSE *arena = (ARENA_INUSE *)ptr;
1347 SIZE_T size = arena->size & ARENA_SIZE_MASK;
1348 if (arena->size & ARENA_FLAG_FREE)
1350 SIZE_T count = size;
1352 ptr += sizeof(ARENA_FREE) + size;
1353 if (ptr > end) count = end - (char *)((ARENA_FREE *)arena + 1);
1354 else count -= sizeof(DWORD);
1355 mark_block_free( (ARENA_FREE *)arena + 1, count, flags );
1359 mark_block_tail( (char *)(arena + 1) + size - arena->unused_bytes,
1360 arena->unused_bytes, flags );
1361 ptr += sizeof(ARENA_INUSE) + size;
1369 /***********************************************************************
1370 * RtlCreateHeap (NTDLL.@)
1372 * Create a new Heap.
1375 * flags [I] HEAP_ flags from "winnt.h"
1376 * addr [I] Desired base address
1377 * totalSize [I] Total size of the heap, or 0 for a growable heap
1378 * commitSize [I] Amount of heap space to commit
1379 * unknown [I] Not yet understood
1380 * definition [I] Heap definition
1383 * Success: A HANDLE to the newly created heap.
1384 * Failure: a NULL HANDLE.
1386 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1387 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1391 /* Allocate the heap block */
1395 totalSize = HEAP_DEF_SIZE;
1396 flags |= HEAP_GROWABLE;
1399 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1401 /* link it into the per-process heap list */
1404 HEAP *heapPtr = subheap->heap;
1405 RtlEnterCriticalSection( &processHeap->critSection );
1406 list_add_head( &processHeap->entry, &heapPtr->entry );
1407 RtlLeaveCriticalSection( &processHeap->critSection );
1411 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1412 list_init( &processHeap->entry );
1415 heap_set_debug_flags( subheap->heap );
1416 return subheap->heap;
1420 /***********************************************************************
1421 * RtlDestroyHeap (NTDLL.@)
1423 * Destroy a Heap created with RtlCreateHeap().
1426 * heap [I] Heap to destroy.
1429 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1430 * Failure: The Heap handle, if heap is the process heap.
1432 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1434 HEAP *heapPtr = HEAP_GetPtr( heap );
1435 SUBHEAP *subheap, *next;
1436 ARENA_LARGE *arena, *arena_next;
1440 TRACE("%p\n", heap );
1441 if (!heapPtr) return heap;
1443 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1445 /* remove it from the per-process list */
1446 RtlEnterCriticalSection( &processHeap->critSection );
1447 list_remove( &heapPtr->entry );
1448 RtlLeaveCriticalSection( &processHeap->critSection );
1450 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1451 RtlDeleteCriticalSection( &heapPtr->critSection );
1453 LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1455 list_remove( &arena->entry );
1458 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1460 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1462 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1463 subheap_notify_free_all(subheap);
1464 list_remove( &subheap->entry );
1466 addr = subheap->base;
1467 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1469 subheap_notify_free_all(&heapPtr->subheap);
1471 addr = heapPtr->subheap.base;
1472 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1477 /***********************************************************************
1478 * RtlAllocateHeap (NTDLL.@)
1480 * Allocate a memory block from a Heap.
1483 * heap [I] Heap to allocate block from
1484 * flags [I] HEAP_ flags from "winnt.h"
1485 * size [I] Size of the memory block to allocate
1488 * Success: A pointer to the newly allocated block
1492 * This call does not SetLastError().
1494 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1497 ARENA_INUSE *pInUse;
1499 HEAP *heapPtr = HEAP_GetPtr( heap );
1500 SIZE_T rounded_size;
1502 /* Validate the parameters */
1504 if (!heapPtr) return NULL;
1505 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1506 flags |= heapPtr->flags;
1507 rounded_size = ROUND_SIZE(size);
1508 if (rounded_size < size) /* overflow */
1510 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1513 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1515 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1517 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1519 void *ret = allocate_large_block( heap, flags, size );
1520 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1521 if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1522 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1526 /* Locate a suitable free block */
1528 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1530 TRACE("(%p,%08x,%08lx): returning NULL\n",
1531 heap, flags, size );
1532 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1533 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1537 /* Remove the arena from the free list */
1539 list_remove( &pArena->entry );
1541 /* Build the in-use arena */
1543 pInUse = (ARENA_INUSE *)pArena;
1545 /* in-use arena is smaller than free arena,
1546 * so we have to add the difference to the size */
1547 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1548 pInUse->magic = ARENA_INUSE_MAGIC;
1550 /* Shrink the block */
1552 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1553 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1555 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1556 initialize_block( pInUse + 1, size, pInUse->unused_bytes, flags );
1558 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1560 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1565 /***********************************************************************
1566 * RtlFreeHeap (NTDLL.@)
1568 * Free a memory block allocated with RtlAllocateHeap().
1571 * heap [I] Heap that block was allocated from
1572 * flags [I] HEAP_ flags from "winnt.h"
1573 * ptr [I] Block to free
1576 * Success: TRUE, if ptr is NULL or was freed successfully.
1579 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1581 ARENA_INUSE *pInUse;
1585 /* Validate the parameters */
1587 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1589 heapPtr = HEAP_GetPtr( heap );
1592 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1596 flags &= HEAP_NO_SERIALIZE;
1597 flags |= heapPtr->flags;
1598 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1600 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1603 /* Some sanity checks */
1604 pInUse = (ARENA_INUSE *)ptr - 1;
1605 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse )))
1607 if (!find_large_block( heapPtr, ptr )) goto error;
1608 free_large_block( heapPtr, flags, ptr );
1611 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1612 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1614 /* Turn the block into a free block */
1616 HEAP_MakeInUseBlockFree( subheap, pInUse );
1619 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1620 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1624 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1625 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1626 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1631 /***********************************************************************
1632 * RtlReAllocateHeap (NTDLL.@)
1634 * Change the size of a memory block allocated with RtlAllocateHeap().
1637 * heap [I] Heap that block was allocated from
1638 * flags [I] HEAP_ flags from "winnt.h"
1639 * ptr [I] Block to resize
1640 * size [I] Size of the memory block to allocate
1643 * Success: A pointer to the resized block (which may be different).
1646 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1648 ARENA_INUSE *pArena;
1651 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1654 if (!ptr) return NULL;
1655 if (!(heapPtr = HEAP_GetPtr( heap )))
1657 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1661 /* Validate the parameters */
1663 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1664 HEAP_REALLOC_IN_PLACE_ONLY;
1665 flags |= heapPtr->flags;
1666 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1668 rounded_size = ROUND_SIZE(size);
1669 if (rounded_size < size) goto oom; /* overflow */
1670 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1672 pArena = (ARENA_INUSE *)ptr - 1;
1673 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena )))
1675 if (!find_large_block( heapPtr, ptr )) goto error;
1676 if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1680 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1681 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1683 /* Check if we need to grow the block */
1685 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1686 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1687 if (rounded_size > oldBlockSize)
1689 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1691 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1693 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) goto oom;
1694 if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1695 memcpy( ret, pArena + 1, oldActualSize );
1696 notify_free( pArena + 1 );
1697 HEAP_MakeInUseBlockFree( subheap, pArena );
1700 if ((pNext < (char *)subheap->base + subheap->size) &&
1701 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1702 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1704 /* The next block is free and large enough */
1705 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1706 list_remove( &pFree->entry );
1707 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1708 if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1709 notify_free( pArena + 1 );
1710 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1711 notify_alloc( pArena + 1, size, FALSE );
1712 /* FIXME: this is wrong as we may lose old VBits settings */
1713 mark_block_initialized( pArena + 1, oldActualSize );
1715 else /* Do it the hard way */
1718 ARENA_INUSE *pInUse;
1719 SUBHEAP *newsubheap;
1721 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1722 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1725 /* Build the in-use arena */
1727 list_remove( &pNew->entry );
1728 pInUse = (ARENA_INUSE *)pNew;
1729 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1730 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1731 pInUse->magic = ARENA_INUSE_MAGIC;
1732 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1734 mark_block_initialized( pInUse + 1, oldActualSize );
1735 notify_alloc( pInUse + 1, size, FALSE );
1736 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1738 /* Free the previous block */
1740 notify_free( pArena + 1 );
1741 HEAP_MakeInUseBlockFree( subheap, pArena );
1742 subheap = newsubheap;
1748 /* Shrink the block */
1749 notify_free( pArena + 1 );
1750 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1751 notify_alloc( pArena + 1, size, FALSE );
1752 /* FIXME: this is wrong as we may lose old VBits settings */
1753 mark_block_initialized( pArena + 1, size );
1756 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1758 /* Clear the extra bytes if needed */
1760 if (size > oldActualSize)
1761 initialize_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize,
1762 pArena->unused_bytes, flags );
1764 mark_block_tail( (char *)(pArena + 1) + size, pArena->unused_bytes, flags );
1766 /* Return the new arena */
1770 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1771 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1775 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1776 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1777 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1778 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1782 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1783 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1784 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1789 /***********************************************************************
1790 * RtlCompactHeap (NTDLL.@)
1792 * Compact the free space in a Heap.
1795 * heap [I] Heap that block was allocated from
1796 * flags [I] HEAP_ flags from "winnt.h"
1799 * The number of bytes compacted.
1802 * This function is a harmless stub.
1804 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1806 static BOOL reported;
1807 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1812 /***********************************************************************
1813 * RtlLockHeap (NTDLL.@)
1818 * heap [I] Heap to lock
1821 * Success: TRUE. The Heap is locked.
1822 * Failure: FALSE, if heap is invalid.
1824 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1826 HEAP *heapPtr = HEAP_GetPtr( heap );
1827 if (!heapPtr) return FALSE;
1828 RtlEnterCriticalSection( &heapPtr->critSection );
1833 /***********************************************************************
1834 * RtlUnlockHeap (NTDLL.@)
1839 * heap [I] Heap to unlock
1842 * Success: TRUE. The Heap is unlocked.
1843 * Failure: FALSE, if heap is invalid.
1845 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1847 HEAP *heapPtr = HEAP_GetPtr( heap );
1848 if (!heapPtr) return FALSE;
1849 RtlLeaveCriticalSection( &heapPtr->critSection );
1854 /***********************************************************************
1855 * RtlSizeHeap (NTDLL.@)
1857 * Get the actual size of a memory block allocated from a Heap.
1860 * heap [I] Heap that block was allocated from
1861 * flags [I] HEAP_ flags from "winnt.h"
1862 * ptr [I] Block to get the size of
1865 * Success: The size of the block.
1866 * Failure: -1, heap or ptr are invalid.
1869 * The size may be bigger than what was passed to RtlAllocateHeap().
1871 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1874 HEAP *heapPtr = HEAP_GetPtr( heap );
1878 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1881 flags &= HEAP_NO_SERIALIZE;
1882 flags |= heapPtr->flags;
1883 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1884 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1886 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1891 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1892 if (pArena->size == ARENA_LARGE_SIZE)
1894 const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
1895 ret = large_arena->data_size;
1897 else ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1899 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1901 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1906 /***********************************************************************
1907 * RtlValidateHeap (NTDLL.@)
1909 * Determine if a block is a valid allocation from a heap.
1912 * heap [I] Heap that block was allocated from
1913 * flags [I] HEAP_ flags from "winnt.h"
1914 * ptr [I] Block to check
1917 * Success: TRUE. The block was allocated from heap.
1918 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1920 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1922 HEAP *heapPtr = HEAP_GetPtr( heap );
1923 if (!heapPtr) return FALSE;
1924 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1928 /***********************************************************************
1929 * RtlWalkHeap (NTDLL.@)
1932 * The PROCESS_HEAP_ENTRY flag values seem different between this
1933 * function and HeapWalk(). To be checked.
1935 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1937 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1938 HEAP *heapPtr = HEAP_GetPtr(heap);
1939 SUBHEAP *sub, *currentheap = NULL;
1942 int region_index = 0;
1944 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1946 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1948 /* FIXME: enumerate large blocks too */
1950 /* set ptr to the next arena to be examined */
1952 if (!entry->lpData) /* first call (init) ? */
1954 TRACE("begin walking of heap %p.\n", heap);
1955 currentheap = &heapPtr->subheap;
1956 ptr = (char*)currentheap->base + currentheap->headerSize;
1960 ptr = entry->lpData;
1961 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1963 if ((ptr >= (char *)sub->base) &&
1964 (ptr < (char *)sub->base + sub->size))
1971 if (currentheap == NULL)
1973 ERR("no matching subheap found, shouldn't happen !\n");
1974 ret = STATUS_NO_MORE_ENTRIES;
1978 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1980 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1981 ptr += pArena->size & ARENA_SIZE_MASK;
1983 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1985 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1986 ptr += pArena->size & ARENA_SIZE_MASK;
1989 ptr += entry->cbData; /* point to next arena */
1991 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1992 { /* proceed with next subheap */
1993 struct list *next = list_next( &heapPtr->subheap_list, ¤theap->entry );
1995 { /* successfully finished */
1996 TRACE("end reached.\n");
1997 ret = STATUS_NO_MORE_ENTRIES;
2000 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
2001 ptr = (char *)currentheap->base + currentheap->headerSize;
2006 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2008 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2010 /*TRACE("free, magic: %04x\n", pArena->magic);*/
2012 entry->lpData = pArena + 1;
2013 entry->cbData = pArena->size & ARENA_SIZE_MASK;
2014 entry->cbOverhead = sizeof(ARENA_FREE);
2015 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
2019 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2021 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
2023 entry->lpData = pArena + 1;
2024 entry->cbData = pArena->size & ARENA_SIZE_MASK;
2025 entry->cbOverhead = sizeof(ARENA_INUSE);
2026 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
2027 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
2028 and PROCESS_HEAP_ENTRY_DDESHARE yet */
2031 entry->iRegionIndex = region_index;
2033 /* first element of heap ? */
2034 if (ptr == (char *)currentheap->base + currentheap->headerSize)
2036 entry->wFlags |= PROCESS_HEAP_REGION;
2037 entry->u.Region.dwCommittedSize = currentheap->commitSize;
2038 entry->u.Region.dwUnCommittedSize =
2039 currentheap->size - currentheap->commitSize;
2040 entry->u.Region.lpFirstBlock = /* first valid block */
2041 (char *)currentheap->base + currentheap->headerSize;
2042 entry->u.Region.lpLastBlock = /* first invalid block */
2043 (char *)currentheap->base + currentheap->size;
2045 ret = STATUS_SUCCESS;
2046 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
2049 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
2054 /***********************************************************************
2055 * RtlGetProcessHeaps (NTDLL.@)
2057 * Get the Heaps belonging to the current process.
2060 * count [I] size of heaps
2061 * heaps [O] Destination array for heap HANDLE's
2064 * Success: The number of Heaps allocated by the process.
2067 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
2069 ULONG total = 1; /* main heap */
2072 RtlEnterCriticalSection( &processHeap->critSection );
2073 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
2076 *heaps++ = processHeap;
2077 LIST_FOR_EACH( ptr, &processHeap->entry )
2078 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
2080 RtlLeaveCriticalSection( &processHeap->critSection );
2084 /***********************************************************************
2085 * RtlQueryHeapInformation (NTDLL.@)
2087 NTSTATUS WINAPI RtlQueryHeapInformation( HANDLE heap, HEAP_INFORMATION_CLASS info_class,
2088 PVOID info, SIZE_T size_in, PSIZE_T size_out)
2092 case HeapCompatibilityInformation:
2093 if (size_out) *size_out = sizeof(ULONG);
2095 if (size_in < sizeof(ULONG))
2096 return STATUS_BUFFER_TOO_SMALL;
2098 *(ULONG *)info = 0; /* standard heap */
2099 return STATUS_SUCCESS;
2102 FIXME("Unknown heap information class %u\n", info_class);
2103 return STATUS_INVALID_INFO_CLASS;