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
39 #include "wine/debug.h"
41 #include "wine/server_protocol.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(heap);
45 /* Note: the heap data structures are based on what Pietrek describes in his
46 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
47 * the same, but could be easily adapted if it turns out some programs
51 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
52 * that there is no unaligned accesses to structure fields.
55 typedef struct tagARENA_INUSE
57 DWORD size; /* Block size; must be the first field */
58 DWORD magic : 27; /* Magic number */
59 DWORD unused_bytes : 5; /* Number of bytes in the block not used by user data (max value is HEAP_MIN_BLOCK_SIZE+ALIGNMENT) */
62 typedef struct tagARENA_FREE
64 DWORD size; /* Block size; must be the first field */
65 DWORD magic; /* Magic number */
66 struct tagARENA_FREE *next; /* Next free arena */
67 struct tagARENA_FREE *prev; /* Prev free arena */
70 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
71 #define ARENA_FLAG_PREV_FREE 0x00000002
72 #define ARENA_SIZE_MASK (~3)
73 #define ARENA_INUSE_MAGIC 0x4455355 /* Value for arena 'magic' field */
74 #define ARENA_FREE_MAGIC 0x45455246 /* Value for arena 'magic' field */
76 #define ARENA_INUSE_FILLER 0x55
77 #define ARENA_FREE_FILLER 0xaa
79 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
80 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
82 #define QUIET 1 /* Suppress messages */
83 #define NOISY 0 /* Report all errors */
85 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
87 /* Max size of the blocks on the free lists */
88 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
90 0x20, 0x80, 0x200, ~0UL
101 typedef struct tagSUBHEAP
103 DWORD size; /* Size of the whole sub-heap */
104 DWORD commitSize; /* Committed size of the sub-heap */
105 DWORD headerSize; /* Size of the heap header */
106 struct tagSUBHEAP *next; /* Next sub-heap */
107 struct tagHEAP *heap; /* Main heap structure */
108 DWORD magic; /* Magic number */
111 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
113 typedef struct tagHEAP
115 SUBHEAP subheap; /* First sub-heap */
116 struct tagHEAP *next; /* Next heap for this process */
117 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
118 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
119 DWORD flags; /* Heap flags */
120 DWORD magic; /* Magic number */
123 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
125 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
126 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
127 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
129 static HANDLE processHeap; /* main process heap */
131 static HEAP *firstHeap; /* head of secondary heaps list */
133 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
135 /* mark a block of memory as free for debugging purposes */
136 static inline void mark_block_free( void *ptr, SIZE_T size )
138 if (TRACE_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
139 #ifdef VALGRIND_MAKE_NOACCESS
140 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
144 /* mark a block of memory as initialized for debugging purposes */
145 static inline void mark_block_initialized( void *ptr, SIZE_T size )
147 #ifdef VALGRIND_MAKE_READABLE
148 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
152 /* mark a block of memory as uninitialized for debugging purposes */
153 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
155 #ifdef VALGRIND_MAKE_WRITABLE
156 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
160 memset( ptr, ARENA_INUSE_FILLER, size );
161 #ifdef VALGRIND_MAKE_WRITABLE
162 /* make it uninitialized to valgrind again */
163 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
168 /* clear contents of a block of memory */
169 static inline void clear_block( void *ptr, SIZE_T size )
171 mark_block_initialized( ptr, size );
172 memset( ptr, 0, size );
175 /***********************************************************************
178 static void HEAP_Dump( HEAP *heap )
184 DPRINTF( "Heap: %08lx\n", (DWORD)heap );
185 DPRINTF( "Next: %08lx Sub-heaps: %08lx",
186 (DWORD)heap->next, (DWORD)&heap->subheap );
187 subheap = &heap->subheap;
188 while (subheap->next)
190 DPRINTF( " -> %08lx", (DWORD)subheap->next );
191 subheap = subheap->next;
194 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
195 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
196 DPRINTF( "%08lx free %08lx prev=%08lx next=%08lx\n",
197 (DWORD)&heap->freeList[i].arena, heap->freeList[i].size,
198 (DWORD)heap->freeList[i].arena.prev,
199 (DWORD)heap->freeList[i].arena.next );
201 subheap = &heap->subheap;
204 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
205 DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
206 (DWORD)subheap, subheap->size, subheap->commitSize );
208 DPRINTF( "\n Block Stat Size Id\n" );
209 ptr = (char*)subheap + subheap->headerSize;
210 while (ptr < (char *)subheap + subheap->size)
212 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
214 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
215 DPRINTF( "%08lx free %08lx prev=%08lx next=%08lx\n",
216 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
217 (DWORD)pArena->prev, (DWORD)pArena->next);
218 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
219 arenaSize += sizeof(ARENA_FREE);
220 freeSize += pArena->size & ARENA_SIZE_MASK;
222 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
224 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
225 DPRINTF( "%08lx Used %08lx back=%08lx\n",
226 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK, *((DWORD *)pArena - 1) );
227 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
228 arenaSize += sizeof(ARENA_INUSE);
229 usedSize += pArena->size & ARENA_SIZE_MASK;
233 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
234 DPRINTF( "%08lx used %08lx\n",
235 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK );
236 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
237 arenaSize += sizeof(ARENA_INUSE);
238 usedSize += pArena->size & ARENA_SIZE_MASK;
241 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
242 subheap->size, subheap->commitSize, freeSize, usedSize,
243 arenaSize, (arenaSize * 100) / subheap->size );
244 subheap = subheap->next;
249 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
252 TRACE( "Dumping entry %p\n", entry );
253 TRACE( "lpData\t\t: %p\n", entry->lpData );
254 TRACE( "cbData\t\t: %08lx\n", entry->cbData);
255 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
256 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
257 TRACE( "WFlags\t\t: ");
258 if (entry->wFlags & PROCESS_HEAP_REGION)
259 TRACE( "PROCESS_HEAP_REGION ");
260 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
261 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
262 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
263 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
264 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
265 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
266 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
267 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
268 rem_flags = entry->wFlags &
269 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
270 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
271 PROCESS_HEAP_ENTRY_DDESHARE);
273 TRACE( "Unknown %08x", rem_flags);
275 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
276 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
279 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
281 if (entry->wFlags & PROCESS_HEAP_REGION)
283 TRACE( "Region.dwCommittedSize\t:%08lx\n",entry->u.Region.dwCommittedSize);
284 TRACE( "Region.dwUnCommittedSize\t:%08lx\n",entry->u.Region.dwUnCommittedSize);
285 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
286 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
290 /***********************************************************************
293 * Pointer to the heap
296 static HEAP *HEAP_GetPtr(
297 HANDLE heap /* [in] Handle to the heap */
299 HEAP *heapPtr = (HEAP *)heap;
300 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
302 ERR("Invalid heap %p!\n", heap );
305 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
307 HEAP_Dump( heapPtr );
315 /***********************************************************************
316 * HEAP_InsertFreeBlock
318 * Insert a free block into the free list.
320 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
322 FREE_LIST_ENTRY *pEntry = heap->freeList;
323 while (pEntry->size < pArena->size) pEntry++;
326 /* insert at end of free list, i.e. before the next free list entry */
328 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
329 pArena->prev = pEntry->arena.prev;
330 pArena->prev->next = pArena;
331 pArena->next = &pEntry->arena;
332 pEntry->arena.prev = pArena;
336 /* insert at head of free list */
337 pArena->next = pEntry->arena.next;
338 pArena->next->prev = pArena;
339 pArena->prev = &pEntry->arena;
340 pEntry->arena.next = pArena;
342 pArena->size |= ARENA_FLAG_FREE;
346 /***********************************************************************
348 * Find the sub-heap containing a given address.
354 static SUBHEAP *HEAP_FindSubHeap(
355 const HEAP *heap, /* [in] Heap pointer */
356 LPCVOID ptr /* [in] Address */
358 const SUBHEAP *sub = &heap->subheap;
361 if (((const char *)ptr >= (const char *)sub) &&
362 ((const char *)ptr < (const char *)sub + sub->size)) return (SUBHEAP*)sub;
369 /***********************************************************************
372 * Make sure the heap storage is committed up to (not including) ptr.
374 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
376 SIZE_T size = (SIZE_T)((char *)ptr - (char *)subheap);
377 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
378 if (size > subheap->size) size = subheap->size;
379 if (size <= subheap->commitSize) return TRUE;
380 size -= subheap->commitSize;
381 ptr = (char *)subheap + subheap->commitSize;
382 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
383 &size, MEM_COMMIT, PAGE_READWRITE ))
385 WARN("Could not commit %08lx bytes at %p for heap %p\n",
386 size, ptr, subheap->heap );
389 subheap->commitSize += size;
394 /***********************************************************************
397 * If possible, decommit the heap storage from (including) 'ptr'.
399 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
402 SIZE_T decommit_size;
403 SIZE_T size = (SIZE_T)((char *)ptr - (char *)subheap);
405 /* round to next block and add one full block */
406 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
407 if (size >= subheap->commitSize) return TRUE;
408 decommit_size = subheap->commitSize - size;
409 addr = (char *)subheap + size;
411 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
413 WARN("Could not decommit %08lx bytes at %08lx for heap %p\n",
414 decommit_size, (DWORD)((char *)subheap + size), subheap->heap );
417 subheap->commitSize -= decommit_size;
422 /***********************************************************************
423 * HEAP_CreateFreeBlock
425 * Create a free block at a specified address. 'size' is the size of the
426 * whole block, including the new arena.
428 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
434 /* Create a free arena */
435 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
436 pFree = (ARENA_FREE *)ptr;
437 pFree->magic = ARENA_FREE_MAGIC;
439 /* If debugging, erase the freed block content */
441 pEnd = (char *)ptr + size;
442 if (pEnd > (char *)subheap + subheap->commitSize) pEnd = (char *)subheap + subheap->commitSize;
443 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
445 /* Check if next block is free also */
447 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
448 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
450 /* Remove the next arena from the free list */
451 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
452 pNext->next->prev = pNext->prev;
453 pNext->prev->next = pNext->next;
454 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
455 mark_block_free( pNext, sizeof(ARENA_FREE) );
458 /* Set the next block PREV_FREE flag and pointer */
460 last = ((char *)ptr + size >= (char *)subheap + subheap->size);
463 DWORD *pNext = (DWORD *)((char *)ptr + size);
464 *pNext |= ARENA_FLAG_PREV_FREE;
465 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
466 *(ARENA_FREE **)(pNext - 1) = pFree;
469 /* Last, insert the new block into the free list */
471 pFree->size = size - sizeof(*pFree);
472 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
476 /***********************************************************************
477 * HEAP_MakeInUseBlockFree
479 * Turn an in-use block into a free block. Can also decommit the end of
480 * the heap, and possibly even free the sub-heap altogether.
482 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
485 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
487 /* Check if we can merge with previous block */
489 if (pArena->size & ARENA_FLAG_PREV_FREE)
491 pFree = *((ARENA_FREE **)pArena - 1);
492 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
493 /* Remove it from the free list */
494 pFree->next->prev = pFree->prev;
495 pFree->prev->next = pFree->next;
497 else pFree = (ARENA_FREE *)pArena;
499 /* Create a free block */
501 HEAP_CreateFreeBlock( subheap, pFree, size );
502 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
503 if ((char *)pFree + size < (char *)subheap + subheap->size)
504 return; /* Not the last block, so nothing more to do */
506 /* Free the whole sub-heap if it's empty and not the original one */
508 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
509 (subheap != &subheap->heap->subheap))
512 SUBHEAP *pPrev = &subheap->heap->subheap;
513 /* Remove the free block from the list */
514 pFree->next->prev = pFree->prev;
515 pFree->prev->next = pFree->next;
516 /* Remove the subheap from the list */
517 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
518 if (pPrev) pPrev->next = subheap->next;
519 /* Free the memory */
521 NtFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap, &size, MEM_RELEASE );
525 /* Decommit the end of the heap */
527 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
531 /***********************************************************************
534 * Shrink an in-use block.
536 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
538 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
540 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
541 (pArena->size & ARENA_SIZE_MASK) - size );
542 /* assign size plus previous arena flags */
543 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
547 /* Turn off PREV_FREE flag in next block */
548 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
549 if (pNext < (char *)subheap + subheap->size)
550 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
554 /***********************************************************************
557 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
558 SIZE_T commitSize, SIZE_T totalSize )
561 FREE_LIST_ENTRY *pEntry;
566 if (flags & HEAP_SHARED)
567 commitSize = totalSize; /* always commit everything in a shared heap */
568 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
569 &commitSize, MEM_COMMIT, PAGE_READWRITE ))
571 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
575 /* Fill the sub-heap structure */
577 subheap = (SUBHEAP *)address;
578 subheap->heap = heap;
579 subheap->size = totalSize;
580 subheap->commitSize = commitSize;
581 subheap->magic = SUBHEAP_MAGIC;
583 if ( subheap != (SUBHEAP *)heap )
585 /* If this is a secondary subheap, insert it into list */
587 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
588 subheap->next = heap->subheap.next;
589 heap->subheap.next = subheap;
593 /* If this is a primary subheap, initialize main heap */
595 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
596 subheap->next = NULL;
599 heap->magic = HEAP_MAGIC;
601 /* Build the free lists */
603 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
605 pEntry->size = HEAP_freeListSizes[i];
606 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
607 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
608 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
609 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
610 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
611 pEntry->arena.magic = ARENA_FREE_MAGIC;
614 /* Initialize critical section */
616 RtlInitializeCriticalSection( &heap->critSection );
617 if (flags & HEAP_SHARED)
619 /* let's assume that only one thread at a time will try to do this */
620 HANDLE sem = heap->critSection.LockSemaphore;
621 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
623 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
624 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
625 heap->critSection.LockSemaphore = sem;
629 /* Create the first free block */
631 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
632 subheap->size - subheap->headerSize );
637 /***********************************************************************
640 * Create a sub-heap of the given size.
641 * If heap == NULL, creates a main heap.
643 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
644 SIZE_T commitSize, SIZE_T totalSize )
646 LPVOID address = base;
648 /* round-up sizes on a 64K boundary */
649 totalSize = (totalSize + 0xffff) & 0xffff0000;
650 commitSize = (commitSize + 0xffff) & 0xffff0000;
651 if (!commitSize) commitSize = 0x10000;
652 if (totalSize < commitSize) totalSize = commitSize;
656 /* allocate the memory block */
657 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
658 MEM_RESERVE, PAGE_READWRITE ))
660 WARN("Could not allocate %08lx bytes\n", totalSize );
665 /* Initialize subheap */
667 if (!HEAP_InitSubHeap( heap ? heap : (HEAP *)address,
668 address, flags, commitSize, totalSize ))
671 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
675 return (SUBHEAP *)address;
679 /***********************************************************************
682 * Find a free block at least as large as the requested size, and make sure
683 * the requested size is committed.
685 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
686 SUBHEAP **ppSubHeap )
690 FREE_LIST_ENTRY *pEntry = heap->freeList;
692 /* Find a suitable free list, and in it find a block large enough */
694 while (pEntry->size < size) pEntry++;
695 pArena = pEntry->arena.next;
696 while (pArena != &heap->freeList[0].arena)
698 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
699 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
700 if (arena_size >= size)
702 subheap = HEAP_FindSubHeap( heap, pArena );
703 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
704 + size + HEAP_MIN_BLOCK_SIZE))
706 *ppSubHeap = subheap;
709 pArena = pArena->next;
712 /* If no block was found, attempt to grow the heap */
714 if (!(heap->flags & HEAP_GROWABLE))
716 WARN("Not enough space in heap %08lx for %08lx bytes\n",
720 /* make sure that we have a big enough size *committed* to fit another
721 * last free arena in !
722 * So just one heap struct, one first free arena which will eventually
723 * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
724 * might get assigned all remaining free space in HEAP_ShrinkBlock() */
725 size += ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
726 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, size,
727 max( HEAP_DEF_SIZE, size ) )))
730 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
731 (DWORD)subheap, size, (DWORD)heap );
733 *ppSubHeap = subheap;
734 return (ARENA_FREE *)(subheap + 1);
738 /***********************************************************************
739 * HEAP_IsValidArenaPtr
741 * Check that the pointer is inside the range possible for arenas.
743 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const void *ptr )
746 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
747 if (!subheap) return FALSE;
748 if ((const char *)ptr >= (const char *)subheap + subheap->headerSize) return TRUE;
749 if (subheap != &heap->subheap) return FALSE;
750 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
751 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
756 /***********************************************************************
757 * HEAP_ValidateFreeArena
759 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
761 char *heapEnd = (char *)subheap + subheap->size;
763 /* Check for unaligned pointers */
764 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
766 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
767 (DWORD)subheap->heap, (DWORD)pArena );
771 /* Check magic number */
772 if (pArena->magic != ARENA_FREE_MAGIC)
774 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
775 (DWORD)subheap->heap, (DWORD)pArena );
778 /* Check size flags */
779 if (!(pArena->size & ARENA_FLAG_FREE) ||
780 (pArena->size & ARENA_FLAG_PREV_FREE))
782 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
783 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
786 /* Check arena size */
787 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
789 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
790 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
793 /* Check that next pointer is valid */
794 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
796 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
797 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
800 /* Check that next arena is free */
801 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
802 (pArena->next->magic != ARENA_FREE_MAGIC))
804 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
805 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
808 /* Check that prev pointer is valid */
809 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
811 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
812 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
815 /* Check that prev arena is free */
816 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
817 (pArena->prev->magic != ARENA_FREE_MAGIC))
819 /* this often means that the prev arena got overwritten
820 * by a memory write before that prev arena */
821 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
822 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
825 /* Check that next block has PREV_FREE flag */
826 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
828 if (!(*(DWORD *)((char *)(pArena + 1) +
829 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
831 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
832 (DWORD)subheap->heap, (DWORD)pArena );
835 /* Check next block back pointer */
836 if (*((ARENA_FREE **)((char *)(pArena + 1) +
837 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
839 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
840 (DWORD)subheap->heap, (DWORD)pArena,
841 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
849 /***********************************************************************
850 * HEAP_ValidateInUseArena
852 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
854 const char *heapEnd = (const char *)subheap + subheap->size;
856 /* Check for unaligned pointers */
857 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
859 if ( quiet == NOISY )
861 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
862 (DWORD)subheap->heap, (DWORD)pArena );
863 if ( TRACE_ON(heap) )
864 HEAP_Dump( subheap->heap );
866 else if ( WARN_ON(heap) )
868 WARN( "Heap %08lx: unaligned arena pointer %08lx\n",
869 (DWORD)subheap->heap, (DWORD)pArena );
870 if ( TRACE_ON(heap) )
871 HEAP_Dump( subheap->heap );
876 /* Check magic number */
877 if (pArena->magic != ARENA_INUSE_MAGIC)
879 if (quiet == NOISY) {
880 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
881 (DWORD)subheap->heap, (DWORD)pArena );
883 HEAP_Dump( subheap->heap );
884 } else if (WARN_ON(heap)) {
885 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
886 (DWORD)subheap->heap, (DWORD)pArena );
888 HEAP_Dump( subheap->heap );
892 /* Check size flags */
893 if (pArena->size & ARENA_FLAG_FREE)
895 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
896 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
899 /* Check arena size */
900 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
902 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
903 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
906 /* Check next arena PREV_FREE flag */
907 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
908 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
910 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
911 (DWORD)subheap->heap, (DWORD)pArena );
914 /* Check prev free arena */
915 if (pArena->size & ARENA_FLAG_PREV_FREE)
917 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
918 /* Check prev pointer */
919 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
921 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
922 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
925 /* Check that prev arena is free */
926 if (!(pPrev->size & ARENA_FLAG_FREE) ||
927 (pPrev->magic != ARENA_FREE_MAGIC))
929 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
930 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
933 /* Check that prev arena is really the previous block */
934 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
936 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
937 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
945 /***********************************************************************
946 * HEAP_IsRealArena [Internal]
947 * Validates a block is a valid arena.
953 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
954 DWORD flags, /* [in] Bit flags that control access during operation */
955 LPCVOID block, /* [in] Optional pointer to memory block to validate */
956 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
957 * does not complain */
962 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
964 ERR("Invalid heap %p!\n", heapPtr );
968 flags &= HEAP_NO_SERIALIZE;
969 flags |= heapPtr->flags;
970 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
971 if (!(flags & HEAP_NO_SERIALIZE))
972 RtlEnterCriticalSection( &heapPtr->critSection );
976 /* Only check this single memory block */
978 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
979 ((const char *)block < (char *)subheap + subheap->headerSize
980 + sizeof(ARENA_INUSE)))
983 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
984 else if (WARN_ON(heap))
985 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
988 ret = HEAP_ValidateInUseArena( subheap, (const ARENA_INUSE *)block - 1, quiet );
990 if (!(flags & HEAP_NO_SERIALIZE))
991 RtlLeaveCriticalSection( &heapPtr->critSection );
995 subheap = &heapPtr->subheap;
996 while (subheap && ret)
998 char *ptr = (char *)subheap + subheap->headerSize;
999 while (ptr < (char *)subheap + subheap->size)
1001 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1003 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1007 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1011 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1015 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1018 subheap = subheap->next;
1021 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1026 /***********************************************************************
1027 * RtlCreateHeap (NTDLL.@)
1029 * Create a new Heap.
1032 * flags [I] HEAP_ flags from "winnt.h"
1033 * addr [I] Desired base address
1034 * totalSize [I] Total size of the heap, or 0 for a growable heap
1035 * commitSize [I] Amount of heap space to commit
1036 * unknown [I] Not yet understood
1037 * definition [I] Heap definition
1040 * Success: A HANDLE to the newly created heap.
1041 * Failure: a NULL HANDLE.
1043 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1044 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1048 /* Allocate the heap block */
1052 totalSize = HEAP_DEF_SIZE;
1053 flags |= HEAP_GROWABLE;
1056 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1058 /* link it into the per-process heap list */
1061 HEAP *heapPtr = subheap->heap;
1062 RtlLockHeap( processHeap );
1063 heapPtr->next = firstHeap;
1064 firstHeap = heapPtr;
1065 RtlUnlockHeap( processHeap );
1067 else processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1069 return (HANDLE)subheap;
1073 /***********************************************************************
1074 * RtlDestroyHeap (NTDLL.@)
1076 * Destroy a Heap created with RtlCreateHeap().
1079 * heap [I] Heap to destroy.
1082 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1083 * Failure: The Heap handle, if heap is the process heap.
1085 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1087 HEAP *heapPtr = HEAP_GetPtr( heap );
1090 TRACE("%p\n", heap );
1091 if (!heapPtr) return heap;
1093 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1094 else /* remove it from the per-process list */
1097 RtlLockHeap( processHeap );
1099 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1100 if (*pptr) *pptr = (*pptr)->next;
1101 RtlUnlockHeap( processHeap );
1104 RtlDeleteCriticalSection( &heapPtr->critSection );
1105 subheap = &heapPtr->subheap;
1108 SUBHEAP *next = subheap->next;
1110 void *addr = subheap;
1111 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1118 /***********************************************************************
1119 * RtlAllocateHeap (NTDLL.@)
1121 * Allocate a memory block from a Heap.
1124 * heap [I] Heap to allocate block from
1125 * flags [I] HEAP_ flags from "winnt.h"
1126 * size [I] Size of the memory block to allocate
1129 * Success: A pointer to the newly allocated block
1133 * This call does not SetLastError().
1135 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1138 ARENA_INUSE *pInUse;
1140 HEAP *heapPtr = HEAP_GetPtr( heap );
1141 SIZE_T rounded_size;
1143 /* Validate the parameters */
1145 if (!heapPtr) return NULL;
1146 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1147 flags |= heapPtr->flags;
1148 rounded_size = ROUND_SIZE(size);
1149 if (rounded_size < HEAP_MIN_BLOCK_SIZE) rounded_size = HEAP_MIN_BLOCK_SIZE;
1151 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1152 /* Locate a suitable free block */
1154 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1156 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1157 heap, flags, size );
1158 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1159 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1163 /* Remove the arena from the free list */
1165 pArena->next->prev = pArena->prev;
1166 pArena->prev->next = pArena->next;
1168 /* Build the in-use arena */
1170 pInUse = (ARENA_INUSE *)pArena;
1172 /* in-use arena is smaller than free arena,
1173 * so we have to add the difference to the size */
1174 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1175 pInUse->magic = ARENA_INUSE_MAGIC;
1177 /* Shrink the block */
1179 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1180 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1182 if (flags & HEAP_ZERO_MEMORY)
1183 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1185 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1187 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1189 TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1190 heap, flags, size, (DWORD)(pInUse + 1) );
1191 return (LPVOID)(pInUse + 1);
1195 /***********************************************************************
1196 * RtlFreeHeap (NTDLL.@)
1198 * Free a memory block allocated with RtlAllocateHeap().
1201 * heap [I] Heap that block was allocated from
1202 * flags [I] HEAP_ flags from "winnt.h"
1203 * ptr [I] Block to free
1206 * Success: TRUE, if ptr is NULL or was freed successfully.
1209 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1211 ARENA_INUSE *pInUse;
1215 /* Validate the parameters */
1217 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1219 heapPtr = HEAP_GetPtr( heap );
1222 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1226 flags &= HEAP_NO_SERIALIZE;
1227 flags |= heapPtr->flags;
1228 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1229 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1231 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1232 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1233 TRACE("(%p,%08lx,%08lx): returning FALSE\n",
1234 heap, flags, (DWORD)ptr );
1238 /* Turn the block into a free block */
1240 pInUse = (ARENA_INUSE *)ptr - 1;
1241 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1242 HEAP_MakeInUseBlockFree( subheap, pInUse );
1244 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1246 TRACE("(%p,%08lx,%08lx): returning TRUE\n",
1247 heap, flags, (DWORD)ptr );
1252 /***********************************************************************
1253 * RtlReAllocateHeap (NTDLL.@)
1255 * Change the size of a memory block allocated with RtlAllocateHeap().
1258 * heap [I] Heap that block was allocated from
1259 * flags [I] HEAP_ flags from "winnt.h"
1260 * ptr [I] Block to resize
1261 * size [I] Size of the memory block to allocate
1264 * Success: A pointer to the resized block (which may be different).
1267 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1269 ARENA_INUSE *pArena;
1272 SIZE_T oldSize, rounded_size;
1274 if (!ptr) return NULL;
1275 if (!(heapPtr = HEAP_GetPtr( heap )))
1277 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1281 /* Validate the parameters */
1283 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1284 HEAP_REALLOC_IN_PLACE_ONLY;
1285 flags |= heapPtr->flags;
1286 rounded_size = ROUND_SIZE(size);
1287 if (rounded_size < HEAP_MIN_BLOCK_SIZE) rounded_size = HEAP_MIN_BLOCK_SIZE;
1289 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1290 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1292 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1293 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1294 TRACE("(%p,%08lx,%08lx,%08lx): returning NULL\n",
1295 heap, flags, (DWORD)ptr, size );
1299 /* Check if we need to grow the block */
1301 pArena = (ARENA_INUSE *)ptr - 1;
1302 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1303 oldSize = (pArena->size & ARENA_SIZE_MASK);
1304 if (rounded_size > oldSize)
1306 char *pNext = (char *)(pArena + 1) + oldSize;
1307 if ((pNext < (char *)subheap + subheap->size) &&
1308 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1309 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1311 /* The next block is free and large enough */
1312 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1313 pFree->next->prev = pFree->prev;
1314 pFree->prev->next = pFree->next;
1315 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1316 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1317 + rounded_size + HEAP_MIN_BLOCK_SIZE))
1319 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1320 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1321 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1324 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1326 else /* Do it the hard way */
1329 ARENA_INUSE *pInUse;
1330 SUBHEAP *newsubheap;
1332 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1333 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1335 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1336 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1337 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1341 /* Build the in-use arena */
1343 pNew->next->prev = pNew->prev;
1344 pNew->prev->next = pNew->next;
1345 pInUse = (ARENA_INUSE *)pNew;
1346 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1347 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1348 pInUse->magic = ARENA_INUSE_MAGIC;
1349 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1350 mark_block_initialized( pInUse + 1, oldSize );
1351 memcpy( pInUse + 1, pArena + 1, oldSize );
1353 /* Free the previous block */
1355 HEAP_MakeInUseBlockFree( subheap, pArena );
1356 subheap = newsubheap;
1360 else HEAP_ShrinkBlock( subheap, pArena, rounded_size ); /* Shrink the block */
1362 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1364 /* Clear the extra bytes if needed */
1366 if (rounded_size > oldSize)
1368 if (flags & HEAP_ZERO_MEMORY)
1369 clear_block( (char *)(pArena + 1) + oldSize,
1370 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1372 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1373 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1376 /* Return the new arena */
1378 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1380 TRACE("(%p,%08lx,%08lx,%08lx): returning %08lx\n",
1381 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1382 return (LPVOID)(pArena + 1);
1386 /***********************************************************************
1387 * RtlCompactHeap (NTDLL.@)
1389 * Compact the free space in a Heap.
1392 * heap [I] Heap that block was allocated from
1393 * flags [I] HEAP_ flags from "winnt.h"
1396 * The number of bytes compacted.
1399 * This function is a harmless stub.
1401 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1408 /***********************************************************************
1409 * RtlLockHeap (NTDLL.@)
1414 * heap [I] Heap to lock
1417 * Success: TRUE. The Heap is locked.
1418 * Failure: FALSE, if heap is invalid.
1420 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1422 HEAP *heapPtr = HEAP_GetPtr( heap );
1423 if (!heapPtr) return FALSE;
1424 RtlEnterCriticalSection( &heapPtr->critSection );
1429 /***********************************************************************
1430 * RtlUnlockHeap (NTDLL.@)
1435 * heap [I] Heap to unlock
1438 * Success: TRUE. The Heap is unlocked.
1439 * Failure: FALSE, if heap is invalid.
1441 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1443 HEAP *heapPtr = HEAP_GetPtr( heap );
1444 if (!heapPtr) return FALSE;
1445 RtlLeaveCriticalSection( &heapPtr->critSection );
1450 /***********************************************************************
1451 * RtlSizeHeap (NTDLL.@)
1453 * Get the actual size of a memory block allocated from a Heap.
1456 * heap [I] Heap that block was allocated from
1457 * flags [I] HEAP_ flags from "winnt.h"
1458 * ptr [I] Block to get the size of
1461 * Success: The size of the block.
1462 * Failure: -1, heap or ptr are invalid.
1465 * The size may be bigger than what was passed to RtlAllocateHeap().
1467 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1470 HEAP *heapPtr = HEAP_GetPtr( heap );
1474 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1477 flags &= HEAP_NO_SERIALIZE;
1478 flags |= heapPtr->flags;
1479 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1480 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1482 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1487 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1488 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1490 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1492 TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1493 heap, flags, (DWORD)ptr, ret );
1498 /***********************************************************************
1499 * RtlValidateHeap (NTDLL.@)
1501 * Determine if a block is a valid allocation from a heap.
1504 * heap [I] Heap that block was allocated from
1505 * flags [I] HEAP_ flags from "winnt.h"
1506 * ptr [I] Block to check
1509 * Success: TRUE. The block was allocated from heap.
1510 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1512 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1514 HEAP *heapPtr = HEAP_GetPtr( heap );
1515 if (!heapPtr) return FALSE;
1516 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1520 /***********************************************************************
1521 * RtlWalkHeap (NTDLL.@)
1524 * The PROCESS_HEAP_ENTRY flag values seem different between this
1525 * function and HeapWalk(). To be checked.
1527 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1529 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1530 HEAP *heapPtr = HEAP_GetPtr(heap);
1531 SUBHEAP *sub, *currentheap = NULL;
1534 int region_index = 0;
1536 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1538 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1540 /* set ptr to the next arena to be examined */
1542 if (!entry->lpData) /* first call (init) ? */
1544 TRACE("begin walking of heap %p.\n", heap);
1545 currentheap = &heapPtr->subheap;
1546 ptr = (char*)currentheap + currentheap->headerSize;
1550 ptr = entry->lpData;
1551 sub = &heapPtr->subheap;
1554 if (((char *)ptr >= (char *)sub) &&
1555 ((char *)ptr < (char *)sub + sub->size))
1563 if (currentheap == NULL)
1565 ERR("no matching subheap found, shouldn't happen !\n");
1566 ret = STATUS_NO_MORE_ENTRIES;
1570 ptr += entry->cbData; /* point to next arena */
1571 if (ptr > (char *)currentheap + currentheap->size - 1)
1572 { /* proceed with next subheap */
1573 if (!(currentheap = currentheap->next))
1574 { /* successfully finished */
1575 TRACE("end reached.\n");
1576 ret = STATUS_NO_MORE_ENTRIES;
1579 ptr = (char*)currentheap + currentheap->headerSize;
1584 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1586 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1588 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1590 entry->lpData = pArena + 1;
1591 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1592 entry->cbOverhead = sizeof(ARENA_FREE);
1593 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1597 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1599 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1601 entry->lpData = pArena + 1;
1602 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1603 entry->cbOverhead = sizeof(ARENA_INUSE);
1604 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1605 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1606 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1609 entry->iRegionIndex = region_index;
1611 /* first element of heap ? */
1612 if (ptr == (char *)(currentheap + currentheap->headerSize))
1614 entry->wFlags |= PROCESS_HEAP_REGION;
1615 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1616 entry->u.Region.dwUnCommittedSize =
1617 currentheap->size - currentheap->commitSize;
1618 entry->u.Region.lpFirstBlock = /* first valid block */
1619 currentheap + currentheap->headerSize;
1620 entry->u.Region.lpLastBlock = /* first invalid block */
1621 currentheap + currentheap->size;
1623 ret = STATUS_SUCCESS;
1624 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1627 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1632 /***********************************************************************
1633 * RtlGetProcessHeaps (NTDLL.@)
1635 * Get the Heaps belonging to the current process.
1638 * count [I] size of heaps
1639 * heaps [O] Destination array for heap HANDLE's
1642 * Success: The number of Heaps allocated by the process.
1645 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1650 if (!processHeap) return 0; /* should never happen */
1651 total = 1; /* main heap */
1652 RtlLockHeap( processHeap );
1653 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1656 *heaps++ = (HANDLE)processHeap;
1657 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1659 RtlUnlockHeap( processHeap );