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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 #ifdef HAVE_VALGRIND_MEMCHECK_H
30 #include <valgrind/memcheck.h>
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
43 #include "wine/debug.h"
45 #include "wine/server_protocol.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(heap);
49 /* Note: the heap data structures are based on what Pietrek describes in his
50 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
51 * the same, but could be easily adapted if it turns out some programs
55 typedef struct tagARENA_INUSE
57 DWORD size; /* Block size; must be the first field */
58 DWORD magic; /* Magic number */
61 typedef struct tagARENA_FREE
63 DWORD size; /* Block size; must be the first field */
64 DWORD magic; /* Magic number */
65 struct tagARENA_FREE *next; /* Next free arena */
66 struct tagARENA_FREE *prev; /* Prev free arena */
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 0x44455355 /* 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 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
86 /* Max size of the blocks on the free lists */
87 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
89 0x20, 0x80, 0x200, ~0UL
100 typedef struct tagSUBHEAP
102 DWORD size; /* Size of the whole sub-heap */
103 DWORD commitSize; /* Committed size of the sub-heap */
104 DWORD headerSize; /* Size of the heap header */
105 struct tagSUBHEAP *next; /* Next sub-heap */
106 struct tagHEAP *heap; /* Main heap structure */
107 DWORD magic; /* Magic number */
110 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
112 typedef struct tagHEAP
114 SUBHEAP subheap; /* First sub-heap */
115 struct tagHEAP *next; /* Next heap for this process */
116 CRITICAL_SECTION critSection; /* Critical section for serialization */
117 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
118 DWORD flags; /* Heap flags */
119 DWORD magic; /* Magic number */
122 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
124 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
125 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
126 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
128 static HANDLE processHeap; /* main process heap */
130 static HEAP *firstHeap; /* head of secondary heaps list */
132 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
134 /* mark a block of memory as free for debugging purposes */
135 static inline void mark_block_free( void *ptr, size_t size )
137 if (TRACE_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
138 #ifdef VALGRIND_MAKE_NOACCESS
139 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
143 /* mark a block of memory as initialized for debugging purposes */
144 static inline void mark_block_initialized( void *ptr, size_t size )
146 #ifdef VALGRIND_MAKE_READABLE
147 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
151 /* mark a block of memory as uninitialized for debugging purposes */
152 static inline void mark_block_uninitialized( void *ptr, size_t size )
154 #ifdef VALGRIND_MAKE_WRITABLE
155 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
159 memset( ptr, ARENA_INUSE_FILLER, size );
160 #ifdef VALGRIND_MAKE_WRITABLE
161 /* make it uninitialized to valgrind again */
162 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
167 /* clear contents of a block of memory */
168 static inline void clear_block( void *ptr, size_t size )
170 mark_block_initialized( ptr, size );
171 memset( ptr, 0, size );
174 /***********************************************************************
177 void HEAP_Dump( HEAP *heap )
183 DPRINTF( "Heap: %08lx\n", (DWORD)heap );
184 DPRINTF( "Next: %08lx Sub-heaps: %08lx",
185 (DWORD)heap->next, (DWORD)&heap->subheap );
186 subheap = &heap->subheap;
187 while (subheap->next)
189 DPRINTF( " -> %08lx", (DWORD)subheap->next );
190 subheap = subheap->next;
193 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
194 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
195 DPRINTF( "%08lx free %08lx prev=%08lx next=%08lx\n",
196 (DWORD)&heap->freeList[i].arena, heap->freeList[i].size,
197 (DWORD)heap->freeList[i].arena.prev,
198 (DWORD)heap->freeList[i].arena.next );
200 subheap = &heap->subheap;
203 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
204 DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
205 (DWORD)subheap, subheap->size, subheap->commitSize );
207 DPRINTF( "\n Block Stat Size Id\n" );
208 ptr = (char*)subheap + subheap->headerSize;
209 while (ptr < (char *)subheap + subheap->size)
211 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
213 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
214 DPRINTF( "%08lx free %08lx prev=%08lx next=%08lx\n",
215 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
216 (DWORD)pArena->prev, (DWORD)pArena->next);
217 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
218 arenaSize += sizeof(ARENA_FREE);
219 freeSize += pArena->size & ARENA_SIZE_MASK;
221 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
223 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
224 DPRINTF( "%08lx Used %08lx back=%08lx\n",
225 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK, *((DWORD *)pArena - 1) );
226 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
227 arenaSize += sizeof(ARENA_INUSE);
228 usedSize += pArena->size & ARENA_SIZE_MASK;
232 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
233 DPRINTF( "%08lx used %08lx\n",
234 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK );
235 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
236 arenaSize += sizeof(ARENA_INUSE);
237 usedSize += pArena->size & ARENA_SIZE_MASK;
240 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
241 subheap->size, subheap->commitSize, freeSize, usedSize,
242 arenaSize, (arenaSize * 100) / subheap->size );
243 subheap = subheap->next;
248 void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
251 TRACE( "Dumping entry %p\n", entry );
252 TRACE( "lpData\t\t: %p\n", entry->lpData );
253 TRACE( "cbData\t\t: %08lx\n", entry->cbData);
254 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
255 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
256 TRACE( "WFlags\t\t: ");
257 if (entry->wFlags & PROCESS_HEAP_REGION)
258 TRACE( "PROCESS_HEAP_REGION ");
259 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
260 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
261 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
262 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
263 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
264 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
265 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
266 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
267 rem_flags = entry->wFlags &
268 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
269 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
270 PROCESS_HEAP_ENTRY_DDESHARE);
272 TRACE( "Unknown %08x", rem_flags);
274 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
275 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
278 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
280 if (entry->wFlags & PROCESS_HEAP_REGION)
282 TRACE( "Region.dwCommittedSize\t:%08lx\n",entry->u.Region.dwCommittedSize);
283 TRACE( "Region.dwUnCommittedSize\t:%08lx\n",entry->u.Region.dwUnCommittedSize);
284 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
285 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
289 /***********************************************************************
292 * Pointer to the heap
295 static HEAP *HEAP_GetPtr(
296 HANDLE heap /* [in] Handle to the heap */
298 HEAP *heapPtr = (HEAP *)heap;
299 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
301 ERR("Invalid heap %p!\n", heap );
304 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
306 HEAP_Dump( heapPtr );
314 /***********************************************************************
315 * HEAP_InsertFreeBlock
317 * Insert a free block into the free list.
319 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
321 FREE_LIST_ENTRY *pEntry = heap->freeList;
322 while (pEntry->size < pArena->size) pEntry++;
325 /* insert at end of free list, i.e. before the next free list entry */
327 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
328 pArena->prev = pEntry->arena.prev;
329 pArena->prev->next = pArena;
330 pArena->next = &pEntry->arena;
331 pEntry->arena.prev = pArena;
335 /* insert at head of free list */
336 pArena->next = pEntry->arena.next;
337 pArena->next->prev = pArena;
338 pArena->prev = &pEntry->arena;
339 pEntry->arena.next = pArena;
341 pArena->size |= ARENA_FLAG_FREE;
345 /***********************************************************************
347 * Find the sub-heap containing a given address.
353 static SUBHEAP *HEAP_FindSubHeap(
354 const HEAP *heap, /* [in] Heap pointer */
355 LPCVOID ptr /* [in] Address */
357 const SUBHEAP *sub = &heap->subheap;
360 if (((const char *)ptr >= (const char *)sub) &&
361 ((const char *)ptr < (const char *)sub + sub->size)) return (SUBHEAP*)sub;
368 /***********************************************************************
371 * Make sure the heap storage is committed up to (not including) ptr.
373 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
375 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
376 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
377 if (size > subheap->size) size = subheap->size;
378 if (size <= subheap->commitSize) return TRUE;
379 size -= subheap->commitSize;
380 ptr = (char *)subheap + subheap->commitSize;
381 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
382 &size, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
384 WARN("Could not commit %08lx bytes at %p for heap %p\n",
385 size, ptr, subheap->heap );
388 subheap->commitSize += size;
393 /***********************************************************************
396 * If possible, decommit the heap storage from (including) 'ptr'.
398 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
403 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
404 /* round to next block and add one full block */
405 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
406 if (size >= subheap->commitSize) return TRUE;
407 decommit_size = subheap->commitSize - size;
408 addr = (char *)subheap + size;
410 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
412 WARN("Could not decommit %08lx bytes at %08lx for heap %p\n",
413 decommit_size, (DWORD)((char *)subheap + size), subheap->heap );
416 subheap->commitSize -= decommit_size;
421 /***********************************************************************
422 * HEAP_CreateFreeBlock
424 * Create a free block at a specified address. 'size' is the size of the
425 * whole block, including the new arena.
427 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
433 /* Create a free arena */
434 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
435 pFree = (ARENA_FREE *)ptr;
436 pFree->magic = ARENA_FREE_MAGIC;
438 /* If debugging, erase the freed block content */
440 pEnd = (char *)ptr + size;
441 if (pEnd > (char *)subheap + subheap->commitSize) pEnd = (char *)subheap + subheap->commitSize;
442 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
444 /* Check if next block is free also */
446 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
447 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
449 /* Remove the next arena from the free list */
450 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
451 pNext->next->prev = pNext->prev;
452 pNext->prev->next = pNext->next;
453 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
454 mark_block_free( pNext, sizeof(ARENA_FREE) );
457 /* Set the next block PREV_FREE flag and pointer */
459 last = ((char *)ptr + size >= (char *)subheap + subheap->size);
462 DWORD *pNext = (DWORD *)((char *)ptr + size);
463 *pNext |= ARENA_FLAG_PREV_FREE;
464 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
465 *(ARENA_FREE **)(pNext - 1) = pFree;
468 /* Last, insert the new block into the free list */
470 pFree->size = size - sizeof(*pFree);
471 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
475 /***********************************************************************
476 * HEAP_MakeInUseBlockFree
478 * Turn an in-use block into a free block. Can also decommit the end of
479 * the heap, and possibly even free the sub-heap altogether.
481 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
484 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
486 /* Check if we can merge with previous block */
488 if (pArena->size & ARENA_FLAG_PREV_FREE)
490 pFree = *((ARENA_FREE **)pArena - 1);
491 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
492 /* Remove it from the free list */
493 pFree->next->prev = pFree->prev;
494 pFree->prev->next = pFree->next;
496 else pFree = (ARENA_FREE *)pArena;
498 /* Create a free block */
500 HEAP_CreateFreeBlock( subheap, pFree, size );
501 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
502 if ((char *)pFree + size < (char *)subheap + subheap->size)
503 return; /* Not the last block, so nothing more to do */
505 /* Free the whole sub-heap if it's empty and not the original one */
507 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
508 (subheap != &subheap->heap->subheap))
511 SUBHEAP *pPrev = &subheap->heap->subheap;
512 /* Remove the free block from the list */
513 pFree->next->prev = pFree->prev;
514 pFree->prev->next = pFree->next;
515 /* Remove the subheap from the list */
516 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
517 if (pPrev) pPrev->next = subheap->next;
518 /* Free the memory */
520 NtFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap, &size, MEM_RELEASE );
524 /* Decommit the end of the heap */
526 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
530 /***********************************************************************
533 * Shrink an in-use block.
535 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
537 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
539 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
540 (pArena->size & ARENA_SIZE_MASK) - size );
541 /* assign size plus previous arena flags */
542 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
546 /* Turn off PREV_FREE flag in next block */
547 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
548 if (pNext < (char *)subheap + subheap->size)
549 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
553 /***********************************************************************
556 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
557 DWORD commitSize, DWORD totalSize )
560 FREE_LIST_ENTRY *pEntry;
565 if (flags & HEAP_SHARED)
566 commitSize = totalSize; /* always commit everything in a shared heap */
567 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
568 &commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
570 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
574 /* Fill the sub-heap structure */
576 subheap = (SUBHEAP *)address;
577 subheap->heap = heap;
578 subheap->size = totalSize;
579 subheap->commitSize = commitSize;
580 subheap->magic = SUBHEAP_MAGIC;
582 if ( subheap != (SUBHEAP *)heap )
584 /* If this is a secondary subheap, insert it into list */
586 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
587 subheap->next = heap->subheap.next;
588 heap->subheap.next = subheap;
592 /* If this is a primary subheap, initialize main heap */
594 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
595 subheap->next = NULL;
598 heap->magic = HEAP_MAGIC;
600 /* Build the free lists */
602 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
604 pEntry->size = HEAP_freeListSizes[i];
605 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
606 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
607 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
608 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
609 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
610 pEntry->arena.magic = ARENA_FREE_MAGIC;
613 /* Initialize critical section */
615 RtlInitializeCriticalSection( &heap->critSection );
616 if (flags & HEAP_SHARED)
618 /* let's assume that only one thread at a time will try to do this */
619 HANDLE sem = heap->critSection.LockSemaphore;
620 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
622 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
623 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
624 heap->critSection.LockSemaphore = sem;
628 /* Create the first free block */
630 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
631 subheap->size - subheap->headerSize );
636 /***********************************************************************
639 * Create a sub-heap of the given size.
640 * If heap == NULL, creates a main heap.
642 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
643 DWORD commitSize, DWORD totalSize )
645 LPVOID address = base;
647 /* round-up sizes on a 64K boundary */
648 totalSize = (totalSize + 0xffff) & 0xffff0000;
649 commitSize = (commitSize + 0xffff) & 0xffff0000;
650 if (!commitSize) commitSize = 0x10000;
651 if (totalSize < commitSize) totalSize = commitSize;
655 /* allocate the memory block */
656 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
657 MEM_RESERVE, PAGE_EXECUTE_READWRITE ))
659 WARN("Could not allocate %08lx bytes\n", totalSize );
664 /* Initialize subheap */
666 if (!HEAP_InitSubHeap( heap ? heap : (HEAP *)address,
667 address, flags, commitSize, totalSize ))
670 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
674 return (SUBHEAP *)address;
678 /***********************************************************************
681 * Find a free block at least as large as the requested size, and make sure
682 * the requested size is committed.
684 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
685 SUBHEAP **ppSubHeap )
689 FREE_LIST_ENTRY *pEntry = heap->freeList;
691 /* Find a suitable free list, and in it find a block large enough */
693 while (pEntry->size < size) pEntry++;
694 pArena = pEntry->arena.next;
695 while (pArena != &heap->freeList[0].arena)
697 DWORD arena_size = (pArena->size & ARENA_SIZE_MASK) +
698 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
699 if (arena_size >= size)
701 subheap = HEAP_FindSubHeap( heap, pArena );
702 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
703 + size + HEAP_MIN_BLOCK_SIZE))
705 *ppSubHeap = subheap;
708 pArena = pArena->next;
711 /* If no block was found, attempt to grow the heap */
713 if (!(heap->flags & HEAP_GROWABLE))
715 WARN("Not enough space in heap %08lx for %08lx bytes\n",
719 /* make sure that we have a big enough size *committed* to fit another
720 * last free arena in !
721 * So just one heap struct, one first free arena which will eventually
722 * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
723 * might get assigned all remaining free space in HEAP_ShrinkBlock() */
724 size += ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
725 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, size,
726 max( HEAP_DEF_SIZE, size ) )))
729 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
730 (DWORD)subheap, size, (DWORD)heap );
732 *ppSubHeap = subheap;
733 return (ARENA_FREE *)(subheap + 1);
737 /***********************************************************************
738 * HEAP_IsValidArenaPtr
740 * Check that the pointer is inside the range possible for arenas.
742 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const void *ptr )
745 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
746 if (!subheap) return FALSE;
747 if ((const char *)ptr >= (const char *)subheap + subheap->headerSize) return TRUE;
748 if (subheap != &heap->subheap) return FALSE;
749 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
750 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
755 /***********************************************************************
756 * HEAP_ValidateFreeArena
758 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
760 char *heapEnd = (char *)subheap + subheap->size;
762 /* Check for unaligned pointers */
763 if ( (long)pArena % ALIGNMENT != 0 )
765 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
766 (DWORD)subheap->heap, (DWORD)pArena );
770 /* Check magic number */
771 if (pArena->magic != ARENA_FREE_MAGIC)
773 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
774 (DWORD)subheap->heap, (DWORD)pArena );
777 /* Check size flags */
778 if (!(pArena->size & ARENA_FLAG_FREE) ||
779 (pArena->size & ARENA_FLAG_PREV_FREE))
781 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
782 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
784 /* Check arena size */
785 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
787 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
788 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
791 /* Check that next pointer is valid */
792 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
794 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
795 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
798 /* Check that next arena is free */
799 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
800 (pArena->next->magic != ARENA_FREE_MAGIC))
802 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
803 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
806 /* Check that prev pointer is valid */
807 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
809 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
810 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
813 /* Check that prev arena is free */
814 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
815 (pArena->prev->magic != ARENA_FREE_MAGIC))
817 /* this often means that the prev arena got overwritten
818 * by a memory write before that prev arena */
819 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
820 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
823 /* Check that next block has PREV_FREE flag */
824 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
826 if (!(*(DWORD *)((char *)(pArena + 1) +
827 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
829 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
830 (DWORD)subheap->heap, (DWORD)pArena );
833 /* Check next block back pointer */
834 if (*((ARENA_FREE **)((char *)(pArena + 1) +
835 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
837 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
838 (DWORD)subheap->heap, (DWORD)pArena,
839 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
847 /***********************************************************************
848 * HEAP_ValidateInUseArena
850 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
852 const char *heapEnd = (const char *)subheap + subheap->size;
854 /* Check for unaligned pointers */
855 if ( (long)pArena % ALIGNMENT != 0 )
857 if ( quiet == NOISY )
859 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
860 (DWORD)subheap->heap, (DWORD)pArena );
861 if ( TRACE_ON(heap) )
862 HEAP_Dump( subheap->heap );
864 else if ( WARN_ON(heap) )
866 WARN( "Heap %08lx: unaligned arena pointer %08lx\n",
867 (DWORD)subheap->heap, (DWORD)pArena );
868 if ( TRACE_ON(heap) )
869 HEAP_Dump( subheap->heap );
874 /* Check magic number */
875 if (pArena->magic != ARENA_INUSE_MAGIC)
877 if (quiet == NOISY) {
878 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
879 (DWORD)subheap->heap, (DWORD)pArena );
881 HEAP_Dump( subheap->heap );
882 } else if (WARN_ON(heap)) {
883 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
884 (DWORD)subheap->heap, (DWORD)pArena );
886 HEAP_Dump( subheap->heap );
890 /* Check size flags */
891 if (pArena->size & ARENA_FLAG_FREE)
893 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
894 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
897 /* Check arena size */
898 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
900 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
901 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
904 /* Check next arena PREV_FREE flag */
905 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
906 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
908 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
909 (DWORD)subheap->heap, (DWORD)pArena );
912 /* Check prev free arena */
913 if (pArena->size & ARENA_FLAG_PREV_FREE)
915 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
916 /* Check prev pointer */
917 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
919 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
920 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
923 /* Check that prev arena is free */
924 if (!(pPrev->size & ARENA_FLAG_FREE) ||
925 (pPrev->magic != ARENA_FREE_MAGIC))
927 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
928 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
931 /* Check that prev arena is really the previous block */
932 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
934 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
935 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
943 /***********************************************************************
944 * HEAP_IsRealArena [Internal]
945 * Validates a block is a valid arena.
951 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
952 DWORD flags, /* [in] Bit flags that control access during operation */
953 LPCVOID block, /* [in] Optional pointer to memory block to validate */
954 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
955 * does not complain */
960 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
962 ERR("Invalid heap %p!\n", heapPtr );
966 flags &= HEAP_NO_SERIALIZE;
967 flags |= heapPtr->flags;
968 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
969 if (!(flags & HEAP_NO_SERIALIZE))
970 RtlEnterCriticalSection( &heapPtr->critSection );
974 /* Only check this single memory block */
976 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
977 ((const char *)block < (char *)subheap + subheap->headerSize
978 + sizeof(ARENA_INUSE)))
981 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
982 else if (WARN_ON(heap))
983 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
986 ret = HEAP_ValidateInUseArena( subheap, (const ARENA_INUSE *)block - 1, quiet );
988 if (!(flags & HEAP_NO_SERIALIZE))
989 RtlLeaveCriticalSection( &heapPtr->critSection );
993 subheap = &heapPtr->subheap;
994 while (subheap && ret)
996 char *ptr = (char *)subheap + subheap->headerSize;
997 while (ptr < (char *)subheap + subheap->size)
999 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1001 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1005 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1009 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1013 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1016 subheap = subheap->next;
1019 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1024 /***********************************************************************
1025 * RtlCreateHeap (NTDLL.@)
1027 * Create a new Heap.
1030 * flags [I] HEAP_ flags from "winnt.h"
1031 * addr [I] Desired base address
1032 * totalSize [I] Total size of the heap, or 0 for a growable heap
1033 * commitSize [I] Amount of heap space to commit
1034 * unknown [I] Not yet understood
1035 * definition [I] Heap definition
1038 * Success: A HANDLE to the newly created heap.
1039 * Failure: a NULL HANDLE.
1041 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, ULONG totalSize, ULONG commitSize,
1042 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1046 /* Allocate the heap block */
1050 totalSize = HEAP_DEF_SIZE;
1051 flags |= HEAP_GROWABLE;
1054 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1056 /* link it into the per-process heap list */
1059 HEAP *heapPtr = subheap->heap;
1060 RtlLockHeap( processHeap );
1061 heapPtr->next = firstHeap;
1062 firstHeap = heapPtr;
1063 RtlUnlockHeap( processHeap );
1065 else processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1067 return (HANDLE)subheap;
1071 /***********************************************************************
1072 * RtlDestroyHeap (NTDLL.@)
1074 * Destroy a Heap created with RtlCreateHeap().
1077 * heap [I] Heap to destroy.
1080 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1081 * Failure: The Heap handle, if heap is the process heap.
1083 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1085 HEAP *heapPtr = HEAP_GetPtr( heap );
1088 TRACE("%p\n", heap );
1089 if (!heapPtr) return heap;
1091 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1092 else /* remove it from the per-process list */
1095 RtlLockHeap( processHeap );
1097 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1098 if (*pptr) *pptr = (*pptr)->next;
1099 RtlUnlockHeap( processHeap );
1102 RtlDeleteCriticalSection( &heapPtr->critSection );
1103 subheap = &heapPtr->subheap;
1106 SUBHEAP *next = subheap->next;
1108 void *addr = subheap;
1109 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1116 /***********************************************************************
1117 * RtlAllocateHeap (NTDLL.@)
1119 * Allocate a memory block from a Heap.
1122 * heap [I] Heap to allocate block from
1123 * flags [I] HEAP_ flags from "winnt.h"
1124 * size [I] Size of the memory block to allocate
1127 * Success: A pointer to the newly allocated block
1131 * This call does not SetLastError().
1133 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, ULONG size )
1136 ARENA_INUSE *pInUse;
1138 HEAP *heapPtr = HEAP_GetPtr( heap );
1140 /* Validate the parameters */
1142 if (!heapPtr) return NULL;
1143 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1144 flags |= heapPtr->flags;
1145 size = ROUND_SIZE(size);
1146 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1148 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1149 /* Locate a suitable free block */
1151 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1153 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1154 heap, flags, size );
1155 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1156 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1160 /* Remove the arena from the free list */
1162 pArena->next->prev = pArena->prev;
1163 pArena->prev->next = pArena->next;
1165 /* Build the in-use arena */
1167 pInUse = (ARENA_INUSE *)pArena;
1169 /* in-use arena is smaller than free arena,
1170 * so we have to add the difference to the size */
1171 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1172 pInUse->magic = ARENA_INUSE_MAGIC;
1174 /* Shrink the block */
1176 HEAP_ShrinkBlock( subheap, pInUse, size );
1178 if (flags & HEAP_ZERO_MEMORY)
1179 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1181 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1183 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1185 TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1186 heap, flags, size, (DWORD)(pInUse + 1) );
1187 return (LPVOID)(pInUse + 1);
1191 /***********************************************************************
1192 * RtlFreeHeap (NTDLL.@)
1194 * Free a memory block allocated with RtlAllocateHeap().
1197 * heap [I] Heap that block was allocated from
1198 * flags [I] HEAP_ flags from "winnt.h"
1199 * ptr [I] Block to free
1202 * Success: TRUE, if ptr is NULL or was freed successfully.
1205 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1207 ARENA_INUSE *pInUse;
1211 /* Validate the parameters */
1213 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1215 heapPtr = HEAP_GetPtr( heap );
1218 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1222 flags &= HEAP_NO_SERIALIZE;
1223 flags |= heapPtr->flags;
1224 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1225 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1227 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1228 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1229 TRACE("(%p,%08lx,%08lx): returning FALSE\n",
1230 heap, flags, (DWORD)ptr );
1234 /* Turn the block into a free block */
1236 pInUse = (ARENA_INUSE *)ptr - 1;
1237 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1238 HEAP_MakeInUseBlockFree( subheap, pInUse );
1240 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1242 TRACE("(%p,%08lx,%08lx): returning TRUE\n",
1243 heap, flags, (DWORD)ptr );
1248 /***********************************************************************
1249 * RtlReAllocateHeap (NTDLL.@)
1251 * Change the size of a memory block allocated with RtlAllocateHeap().
1254 * heap [I] Heap that block was allocated from
1255 * flags [I] HEAP_ flags from "winnt.h"
1256 * ptr [I] Block to resize
1257 * size [I] Size of the memory block to allocate
1260 * Success: A pointer to the resized block (which may be different).
1263 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, ULONG size )
1265 ARENA_INUSE *pArena;
1270 if (!ptr) return NULL;
1271 if (!(heapPtr = HEAP_GetPtr( heap )))
1273 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1277 /* Validate the parameters */
1279 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1280 HEAP_REALLOC_IN_PLACE_ONLY;
1281 flags |= heapPtr->flags;
1282 size = ROUND_SIZE(size);
1283 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1285 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1286 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1288 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1289 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1290 TRACE("(%p,%08lx,%08lx,%08lx): returning NULL\n",
1291 heap, flags, (DWORD)ptr, size );
1295 /* Check if we need to grow the block */
1297 pArena = (ARENA_INUSE *)ptr - 1;
1298 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1299 oldSize = (pArena->size & ARENA_SIZE_MASK);
1302 char *pNext = (char *)(pArena + 1) + oldSize;
1303 if ((pNext < (char *)subheap + subheap->size) &&
1304 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1305 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1307 /* The next block is free and large enough */
1308 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1309 pFree->next->prev = pFree->prev;
1310 pFree->prev->next = pFree->next;
1311 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1312 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1313 + size + HEAP_MIN_BLOCK_SIZE))
1315 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1316 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1317 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1320 HEAP_ShrinkBlock( subheap, pArena, size );
1322 else /* Do it the hard way */
1325 ARENA_INUSE *pInUse;
1326 SUBHEAP *newsubheap;
1328 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1329 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1331 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1332 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1333 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1337 /* Build the in-use arena */
1339 pNew->next->prev = pNew->prev;
1340 pNew->prev->next = pNew->next;
1341 pInUse = (ARENA_INUSE *)pNew;
1342 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1343 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1344 pInUse->magic = ARENA_INUSE_MAGIC;
1345 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1346 mark_block_initialized( pInUse + 1, oldSize );
1347 memcpy( pInUse + 1, pArena + 1, oldSize );
1349 /* Free the previous block */
1351 HEAP_MakeInUseBlockFree( subheap, pArena );
1352 subheap = newsubheap;
1356 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1358 /* Clear the extra bytes if needed */
1362 if (flags & HEAP_ZERO_MEMORY)
1363 clear_block( (char *)(pArena + 1) + oldSize,
1364 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1366 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1367 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1370 /* Return the new arena */
1372 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1374 TRACE("(%p,%08lx,%08lx,%08lx): returning %08lx\n",
1375 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1376 return (LPVOID)(pArena + 1);
1380 /***********************************************************************
1381 * RtlCompactHeap (NTDLL.@)
1383 * Compact the free space in a Heap.
1386 * heap [I] Heap that block was allocated from
1387 * flags [I] HEAP_ flags from "winnt.h"
1390 * The number of bytes compacted.
1393 * This function is a harmless stub.
1395 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1402 /***********************************************************************
1403 * RtlLockHeap (NTDLL.@)
1408 * heap [I] Heap to lock
1411 * Success: TRUE. The Heap is locked.
1412 * Failure: FALSE, if heap is invalid.
1414 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1416 HEAP *heapPtr = HEAP_GetPtr( heap );
1417 if (!heapPtr) return FALSE;
1418 RtlEnterCriticalSection( &heapPtr->critSection );
1423 /***********************************************************************
1424 * RtlUnlockHeap (NTDLL.@)
1429 * heap [I] Heap to unlock
1432 * Success: TRUE. The Heap is unlocked.
1433 * Failure: FALSE, if heap is invalid.
1435 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1437 HEAP *heapPtr = HEAP_GetPtr( heap );
1438 if (!heapPtr) return FALSE;
1439 RtlLeaveCriticalSection( &heapPtr->critSection );
1444 /***********************************************************************
1445 * RtlSizeHeap (NTDLL.@)
1447 * Get the actual size of a memory block allocated from a Heap.
1450 * heap [I] Heap that block was allocated from
1451 * flags [I] HEAP_ flags from "winnt.h"
1452 * ptr [I] Block to get the size of
1455 * Success: The size of the block.
1456 * Failure: -1, heap or ptr are invalid.
1459 * The size may be bigger than what was passed to RtlAllocateHeap().
1461 ULONG WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1464 HEAP *heapPtr = HEAP_GetPtr( heap );
1468 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1471 flags &= HEAP_NO_SERIALIZE;
1472 flags |= heapPtr->flags;
1473 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1474 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1476 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1481 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1482 ret = pArena->size & ARENA_SIZE_MASK;
1484 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1486 TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1487 heap, flags, (DWORD)ptr, ret );
1492 /***********************************************************************
1493 * RtlValidateHeap (NTDLL.@)
1495 * Determine if a block is a valid allocation from a heap.
1498 * heap [I] Heap that block was allocated from
1499 * flags [I] HEAP_ flags from "winnt.h"
1500 * ptr [I] Block to check
1503 * Success: TRUE. The block was allocated from heap.
1504 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1506 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1508 HEAP *heapPtr = HEAP_GetPtr( heap );
1509 if (!heapPtr) return FALSE;
1510 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1514 /***********************************************************************
1515 * RtlWalkHeap (NTDLL.@)
1518 * The PROCESS_HEAP_ENTRY flag values seem different between this
1519 * function and HeapWalk(). To be checked.
1521 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1523 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1524 HEAP *heapPtr = HEAP_GetPtr(heap);
1525 SUBHEAP *sub, *currentheap = NULL;
1528 int region_index = 0;
1530 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1532 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1534 /* set ptr to the next arena to be examined */
1536 if (!entry->lpData) /* first call (init) ? */
1538 TRACE("begin walking of heap %p.\n", heap);
1539 currentheap = &heapPtr->subheap;
1540 ptr = (char*)currentheap + currentheap->headerSize;
1544 ptr = entry->lpData;
1545 sub = &heapPtr->subheap;
1548 if (((char *)ptr >= (char *)sub) &&
1549 ((char *)ptr < (char *)sub + sub->size))
1557 if (currentheap == NULL)
1559 ERR("no matching subheap found, shouldn't happen !\n");
1560 ret = STATUS_NO_MORE_ENTRIES;
1564 ptr += entry->cbData; /* point to next arena */
1565 if (ptr > (char *)currentheap + currentheap->size - 1)
1566 { /* proceed with next subheap */
1567 if (!(currentheap = currentheap->next))
1568 { /* successfully finished */
1569 TRACE("end reached.\n");
1570 ret = STATUS_NO_MORE_ENTRIES;
1573 ptr = (char*)currentheap + currentheap->headerSize;
1578 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1580 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1582 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1584 entry->lpData = pArena + 1;
1585 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1586 entry->cbOverhead = sizeof(ARENA_FREE);
1587 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1591 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1593 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1595 entry->lpData = pArena + 1;
1596 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1597 entry->cbOverhead = sizeof(ARENA_INUSE);
1598 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1599 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1600 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1603 entry->iRegionIndex = region_index;
1605 /* first element of heap ? */
1606 if (ptr == (char *)(currentheap + currentheap->headerSize))
1608 entry->wFlags |= PROCESS_HEAP_REGION;
1609 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1610 entry->u.Region.dwUnCommittedSize =
1611 currentheap->size - currentheap->commitSize;
1612 entry->u.Region.lpFirstBlock = /* first valid block */
1613 currentheap + currentheap->headerSize;
1614 entry->u.Region.lpLastBlock = /* first invalid block */
1615 currentheap + currentheap->size;
1617 ret = STATUS_SUCCESS;
1618 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1621 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1626 /***********************************************************************
1627 * RtlGetProcessHeaps (NTDLL.@)
1629 * Get the Heaps belonging to the current process.
1632 * count [I] size of heaps
1633 * heaps [O] Destination array for heap HANDLE's
1636 * Success: The number of Heaps allocated by the process.
1639 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1644 if (!processHeap) return 0; /* should never happen */
1645 total = 1; /* main heap */
1646 RtlLockHeap( processHeap );
1647 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1650 *heaps++ = (HANDLE)processHeap;
1651 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1653 RtlUnlockHeap( processHeap );