4 * Copyright 1996 Alexandre Julliard
5 * Copyright 1998 Ulrich Weigand
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
29 #ifdef HAVE_VALGRIND_MEMCHECK_H
30 #include <valgrind/memcheck.h>
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
36 #define WIN32_NO_STATUS
41 #include "wine/list.h"
42 #include "wine/debug.h"
43 #include "wine/server.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(heap);
47 /* Note: the heap data structures are based on what Pietrek describes in his
48 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
49 * the same, but could be easily adapted if it turns out some programs
53 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
54 * that there is no unaligned accesses to structure fields.
57 typedef struct tagARENA_INUSE
59 DWORD size; /* Block size; must be the first field */
60 DWORD magic : 24; /* Magic number */
61 DWORD unused_bytes : 8; /* Number of bytes in the block not used by user data (max value is HEAP_MIN_DATA_SIZE+HEAP_MIN_SHRINK_SIZE) */
64 typedef struct tagARENA_FREE
66 DWORD size; /* Block size; must be the first field */
67 DWORD magic; /* Magic number */
68 struct list entry; /* Entry in free list */
71 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
72 #define ARENA_FLAG_PREV_FREE 0x00000002
73 #define ARENA_SIZE_MASK (~3)
74 #define ARENA_INUSE_MAGIC 0x455355 /* Value for arena 'magic' field */
75 #define ARENA_FREE_MAGIC 0x45455246 /* Value for arena 'magic' field */
77 #define ARENA_INUSE_FILLER 0x55
78 #define ARENA_FREE_FILLER 0xaa
80 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
81 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
83 #define QUIET 1 /* Suppress messages */
84 #define NOISY 0 /* Report all errors */
86 /* minimum data size (without arenas) of an allocated block */
87 /* make sure that it's larger than a free list entry */
88 #define HEAP_MIN_DATA_SIZE (2 * sizeof(struct list))
89 /* minimum size that must remain to shrink an allocated block */
90 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
92 /* Max size of the blocks on the free lists */
93 static const DWORD HEAP_freeListSizes[] =
95 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
97 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
106 typedef struct tagSUBHEAP
108 DWORD size; /* Size of the whole sub-heap */
109 DWORD commitSize; /* Committed size of the sub-heap */
110 DWORD headerSize; /* Size of the heap header */
111 struct tagSUBHEAP *next; /* Next sub-heap */
112 struct tagHEAP *heap; /* Main heap structure */
113 DWORD magic; /* Magic number */
116 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
118 typedef struct tagHEAP
120 SUBHEAP subheap; /* First sub-heap */
121 struct list entry; /* Entry in process heap list */
122 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
123 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
124 DWORD flags; /* Heap flags */
125 DWORD magic; /* Magic number */
128 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
130 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
131 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
133 static HEAP *processHeap; /* main process heap */
135 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
137 /* mark a block of memory as free for debugging purposes */
138 static inline void mark_block_free( void *ptr, SIZE_T size )
140 if (TRACE_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
141 #ifdef VALGRIND_MAKE_NOACCESS
142 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
146 /* mark a block of memory as initialized for debugging purposes */
147 static inline void mark_block_initialized( void *ptr, SIZE_T size )
149 #ifdef VALGRIND_MAKE_READABLE
150 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
154 /* mark a block of memory as uninitialized for debugging purposes */
155 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
157 #ifdef VALGRIND_MAKE_WRITABLE
158 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
162 memset( ptr, ARENA_INUSE_FILLER, size );
163 #ifdef VALGRIND_MAKE_WRITABLE
164 /* make it uninitialized to valgrind again */
165 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
170 /* clear contents of a block of memory */
171 static inline void clear_block( void *ptr, SIZE_T size )
173 mark_block_initialized( ptr, size );
174 memset( ptr, 0, size );
177 /* notify that a new block of memory has been allocated for debugging purposes */
178 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
180 #ifdef VALGRIND_MALLOCLIKE_BLOCK
181 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
185 /* notify that a block of memory has been freed for debugging purposes */
186 static inline void notify_free( void *ptr )
188 #ifdef VALGRIND_FREELIKE_BLOCK
189 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
193 /* locate a free list entry of the appropriate size */
194 /* size is the size of the whole block including the arena header */
195 static inline unsigned int get_freelist_index( SIZE_T size )
199 size -= sizeof(ARENA_FREE);
200 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
204 /* get the memory protection type to use for a given heap */
205 static inline ULONG get_protection_type( DWORD flags )
207 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
210 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
212 0, 0, NULL, /* will be set later */
213 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
214 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
218 /***********************************************************************
221 static void HEAP_Dump( HEAP *heap )
227 DPRINTF( "Heap: %p\n", heap );
228 DPRINTF( "Next: %p Sub-heaps: %p",
229 LIST_ENTRY( heap->entry.next, HEAP, entry ), &heap->subheap );
230 subheap = &heap->subheap;
231 while (subheap->next)
233 DPRINTF( " -> %p", subheap->next );
234 subheap = subheap->next;
237 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
238 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
239 DPRINTF( "%p free %08x prev=%p next=%p\n",
240 &heap->freeList[i].arena, HEAP_freeListSizes[i],
241 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
242 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
244 subheap = &heap->subheap;
247 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
248 DPRINTF( "\n\nSub-heap %p: size=%08x committed=%08x\n",
249 subheap, subheap->size, subheap->commitSize );
251 DPRINTF( "\n Block Stat Size Id\n" );
252 ptr = (char*)subheap + subheap->headerSize;
253 while (ptr < (char *)subheap + subheap->size)
255 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
257 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
258 DPRINTF( "%p free %08x prev=%p next=%p\n",
259 pArena, pArena->size & ARENA_SIZE_MASK,
260 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
261 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
262 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
263 arenaSize += sizeof(ARENA_FREE);
264 freeSize += pArena->size & ARENA_SIZE_MASK;
266 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
268 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
269 DPRINTF( "%p Used %08x back=%p\n",
270 pArena, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
271 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
272 arenaSize += sizeof(ARENA_INUSE);
273 usedSize += pArena->size & ARENA_SIZE_MASK;
277 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
278 DPRINTF( "%p used %08x\n", pArena, pArena->size & ARENA_SIZE_MASK );
279 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
280 arenaSize += sizeof(ARENA_INUSE);
281 usedSize += pArena->size & ARENA_SIZE_MASK;
284 DPRINTF( "\nTotal: Size=%08x Committed=%08x Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
285 subheap->size, subheap->commitSize, freeSize, usedSize,
286 arenaSize, (arenaSize * 100) / subheap->size );
287 subheap = subheap->next;
292 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
295 TRACE( "Dumping entry %p\n", entry );
296 TRACE( "lpData\t\t: %p\n", entry->lpData );
297 TRACE( "cbData\t\t: %08x\n", entry->cbData);
298 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
299 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
300 TRACE( "WFlags\t\t: ");
301 if (entry->wFlags & PROCESS_HEAP_REGION)
302 TRACE( "PROCESS_HEAP_REGION ");
303 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
304 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
305 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
306 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
307 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
308 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
309 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
310 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
311 rem_flags = entry->wFlags &
312 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
313 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
314 PROCESS_HEAP_ENTRY_DDESHARE);
316 TRACE( "Unknown %08x", rem_flags);
318 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
319 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
322 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
324 if (entry->wFlags & PROCESS_HEAP_REGION)
326 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
327 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
328 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
329 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
333 /***********************************************************************
336 * Pointer to the heap
339 static HEAP *HEAP_GetPtr(
340 HANDLE heap /* [in] Handle to the heap */
342 HEAP *heapPtr = (HEAP *)heap;
343 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
345 ERR("Invalid heap %p!\n", heap );
348 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
350 HEAP_Dump( heapPtr );
358 /***********************************************************************
359 * HEAP_InsertFreeBlock
361 * Insert a free block into the free list.
363 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
365 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
368 /* insert at end of free list, i.e. before the next free list entry */
370 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
371 list_add_before( &pEntry->arena.entry, &pArena->entry );
375 /* insert at head of free list */
376 list_add_after( &pEntry->arena.entry, &pArena->entry );
378 pArena->size |= ARENA_FLAG_FREE;
382 /***********************************************************************
384 * Find the sub-heap containing a given address.
390 static SUBHEAP *HEAP_FindSubHeap(
391 const HEAP *heap, /* [in] Heap pointer */
392 LPCVOID ptr /* [in] Address */
394 const SUBHEAP *sub = &heap->subheap;
397 if (((const char *)ptr >= (const char *)sub) &&
398 ((const char *)ptr < (const char *)sub + sub->size)) return (SUBHEAP*)sub;
405 /***********************************************************************
408 * Make sure the heap storage is committed for a given size in the specified arena.
410 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
412 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
413 SIZE_T size = (char *)ptr - (char *)subheap;
414 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
415 if (size > subheap->size) size = subheap->size;
416 if (size <= subheap->commitSize) return TRUE;
417 size -= subheap->commitSize;
418 ptr = (char *)subheap + subheap->commitSize;
419 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
420 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
422 WARN("Could not commit %08lx bytes at %p for heap %p\n",
423 size, ptr, subheap->heap );
426 subheap->commitSize += size;
431 /***********************************************************************
434 * If possible, decommit the heap storage from (including) 'ptr'.
436 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
439 SIZE_T decommit_size;
440 SIZE_T size = (char *)ptr - (char *)subheap;
442 /* round to next block and add one full block */
443 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
444 if (size >= subheap->commitSize) return TRUE;
445 decommit_size = subheap->commitSize - size;
446 addr = (char *)subheap + size;
448 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
450 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
451 decommit_size, (char *)subheap + size, subheap->heap );
454 subheap->commitSize -= decommit_size;
459 /***********************************************************************
460 * HEAP_CreateFreeBlock
462 * Create a free block at a specified address. 'size' is the size of the
463 * whole block, including the new arena.
465 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
471 /* Create a free arena */
472 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
473 pFree = (ARENA_FREE *)ptr;
474 pFree->magic = ARENA_FREE_MAGIC;
476 /* If debugging, erase the freed block content */
478 pEnd = (char *)ptr + size;
479 if (pEnd > (char *)subheap + subheap->commitSize) pEnd = (char *)subheap + subheap->commitSize;
480 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
482 /* Check if next block is free also */
484 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
485 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
487 /* Remove the next arena from the free list */
488 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
489 list_remove( &pNext->entry );
490 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
491 mark_block_free( pNext, sizeof(ARENA_FREE) );
494 /* Set the next block PREV_FREE flag and pointer */
496 last = ((char *)ptr + size >= (char *)subheap + subheap->size);
499 DWORD *pNext = (DWORD *)((char *)ptr + size);
500 *pNext |= ARENA_FLAG_PREV_FREE;
501 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
502 *((ARENA_FREE **)pNext - 1) = pFree;
505 /* Last, insert the new block into the free list */
507 pFree->size = size - sizeof(*pFree);
508 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
512 /***********************************************************************
513 * HEAP_MakeInUseBlockFree
515 * Turn an in-use block into a free block. Can also decommit the end of
516 * the heap, and possibly even free the sub-heap altogether.
518 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
521 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
523 /* Check if we can merge with previous block */
525 if (pArena->size & ARENA_FLAG_PREV_FREE)
527 pFree = *((ARENA_FREE **)pArena - 1);
528 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
529 /* Remove it from the free list */
530 list_remove( &pFree->entry );
532 else pFree = (ARENA_FREE *)pArena;
534 /* Create a free block */
536 HEAP_CreateFreeBlock( subheap, pFree, size );
537 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
538 if ((char *)pFree + size < (char *)subheap + subheap->size)
539 return; /* Not the last block, so nothing more to do */
541 /* Free the whole sub-heap if it's empty and not the original one */
543 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
544 (subheap != &subheap->heap->subheap))
547 SUBHEAP *pPrev = &subheap->heap->subheap;
548 /* Remove the free block from the list */
549 list_remove( &pFree->entry );
550 /* Remove the subheap from the list */
551 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
552 if (pPrev) pPrev->next = subheap->next;
553 /* Free the memory */
555 NtFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap, &size, MEM_RELEASE );
559 /* Decommit the end of the heap */
561 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
565 /***********************************************************************
568 * Shrink an in-use block.
570 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
572 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
574 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
575 (pArena->size & ARENA_SIZE_MASK) - size );
576 /* assign size plus previous arena flags */
577 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
581 /* Turn off PREV_FREE flag in next block */
582 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
583 if (pNext < (char *)subheap + subheap->size)
584 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
588 /***********************************************************************
591 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
592 SIZE_T commitSize, SIZE_T totalSize )
595 FREE_LIST_ENTRY *pEntry;
600 if (flags & HEAP_SHARED)
601 commitSize = totalSize; /* always commit everything in a shared heap */
602 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
603 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
605 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
609 /* Fill the sub-heap structure */
611 subheap = (SUBHEAP *)address;
612 subheap->heap = heap;
613 subheap->size = totalSize;
614 subheap->commitSize = commitSize;
615 subheap->magic = SUBHEAP_MAGIC;
617 if ( subheap != (SUBHEAP *)heap )
619 /* If this is a secondary subheap, insert it into list */
621 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
622 subheap->next = heap->subheap.next;
623 heap->subheap.next = subheap;
627 /* If this is a primary subheap, initialize main heap */
629 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
630 subheap->next = NULL;
632 heap->magic = HEAP_MAGIC;
634 /* Build the free lists */
636 list_init( &heap->freeList[0].arena.entry );
637 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
639 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
640 pEntry->arena.magic = ARENA_FREE_MAGIC;
641 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
644 /* Initialize critical section */
646 if (!processHeap) /* do it by hand to avoid memory allocations */
648 heap->critSection.DebugInfo = &process_heap_critsect_debug;
649 heap->critSection.LockCount = -1;
650 heap->critSection.RecursionCount = 0;
651 heap->critSection.OwningThread = 0;
652 heap->critSection.LockSemaphore = 0;
653 heap->critSection.SpinCount = 0;
654 process_heap_critsect_debug.CriticalSection = &heap->critSection;
656 else RtlInitializeCriticalSection( &heap->critSection );
658 if (flags & HEAP_SHARED)
660 /* let's assume that only one thread at a time will try to do this */
661 HANDLE sem = heap->critSection.LockSemaphore;
662 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
664 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
665 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
666 heap->critSection.LockSemaphore = sem;
667 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
668 heap->critSection.DebugInfo = NULL;
672 /* Create the first free block */
674 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
675 subheap->size - subheap->headerSize );
680 /***********************************************************************
683 * Create a sub-heap of the given size.
684 * If heap == NULL, creates a main heap.
686 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
687 SIZE_T commitSize, SIZE_T totalSize )
689 LPVOID address = base;
691 /* round-up sizes on a 64K boundary */
692 totalSize = (totalSize + 0xffff) & 0xffff0000;
693 commitSize = (commitSize + 0xffff) & 0xffff0000;
694 if (!commitSize) commitSize = 0x10000;
695 if (totalSize < commitSize) totalSize = commitSize;
699 /* allocate the memory block */
700 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
701 MEM_RESERVE, get_protection_type( flags ) ))
703 WARN("Could not allocate %08lx bytes\n", totalSize );
708 /* Initialize subheap */
710 if (!HEAP_InitSubHeap( heap ? heap : (HEAP *)address,
711 address, flags, commitSize, totalSize ))
714 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
718 return (SUBHEAP *)address;
722 /***********************************************************************
725 * Find a free block at least as large as the requested size, and make sure
726 * the requested size is committed.
728 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
729 SUBHEAP **ppSubHeap )
733 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
735 /* Find a suitable free list, and in it find a block large enough */
737 ptr = &pEntry->arena.entry;
738 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
740 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
741 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
742 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
743 if (arena_size >= size)
745 subheap = HEAP_FindSubHeap( heap, pArena );
746 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
747 *ppSubHeap = subheap;
752 /* If no block was found, attempt to grow the heap */
754 if (!(heap->flags & HEAP_GROWABLE))
756 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
759 /* make sure that we have a big enough size *committed* to fit another
760 * last free arena in !
761 * So just one heap struct, one first free arena which will eventually
762 * get used, and a second free arena that might get assigned all remaining
763 * free space in HEAP_ShrinkBlock() */
764 size += ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
765 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, size,
766 max( HEAP_DEF_SIZE, size ) )))
769 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
770 subheap, size, heap );
772 *ppSubHeap = subheap;
773 return (ARENA_FREE *)(subheap + 1);
777 /***********************************************************************
778 * HEAP_IsValidArenaPtr
780 * Check that the pointer is inside the range possible for arenas.
782 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const void *ptr )
785 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
786 if (!subheap) return FALSE;
787 if ((const char *)ptr >= (const char *)subheap + subheap->headerSize) return TRUE;
788 if (subheap != &heap->subheap) return FALSE;
789 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
790 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
795 /***********************************************************************
796 * HEAP_ValidateFreeArena
798 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
800 ARENA_FREE *prev, *next;
801 char *heapEnd = (char *)subheap + subheap->size;
803 /* Check for unaligned pointers */
804 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
806 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
810 /* Check magic number */
811 if (pArena->magic != ARENA_FREE_MAGIC)
813 ERR("Heap %p: invalid free arena magic for %p\n", subheap->heap, pArena );
816 /* Check size flags */
817 if (!(pArena->size & ARENA_FLAG_FREE) ||
818 (pArena->size & ARENA_FLAG_PREV_FREE))
820 ERR("Heap %p: bad flags %08x for free arena %p\n",
821 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
824 /* Check arena size */
825 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
827 ERR("Heap %p: bad size %08x for free arena %p\n",
828 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
831 /* Check that next pointer is valid */
832 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
833 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
835 ERR("Heap %p: bad next ptr %p for arena %p\n",
836 subheap->heap, next, pArena );
839 /* Check that next arena is free */
840 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
842 ERR("Heap %p: next arena %p invalid for %p\n",
843 subheap->heap, next, pArena );
846 /* Check that prev pointer is valid */
847 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
848 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
850 ERR("Heap %p: bad prev ptr %p for arena %p\n",
851 subheap->heap, prev, pArena );
854 /* Check that prev arena is free */
855 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
857 /* this often means that the prev arena got overwritten
858 * by a memory write before that prev arena */
859 ERR("Heap %p: prev arena %p invalid for %p\n",
860 subheap->heap, prev, pArena );
863 /* Check that next block has PREV_FREE flag */
864 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
866 if (!(*(DWORD *)((char *)(pArena + 1) +
867 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
869 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
870 subheap->heap, pArena );
873 /* Check next block back pointer */
874 if (*((ARENA_FREE **)((char *)(pArena + 1) +
875 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
877 ERR("Heap %p: arena %p has wrong back ptr %p\n",
878 subheap->heap, pArena,
879 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
887 /***********************************************************************
888 * HEAP_ValidateInUseArena
890 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
892 const char *heapEnd = (const char *)subheap + subheap->size;
894 /* Check for unaligned pointers */
895 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
897 if ( quiet == NOISY )
899 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
900 if ( TRACE_ON(heap) )
901 HEAP_Dump( subheap->heap );
903 else if ( WARN_ON(heap) )
905 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
906 if ( TRACE_ON(heap) )
907 HEAP_Dump( subheap->heap );
912 /* Check magic number */
913 if (pArena->magic != ARENA_INUSE_MAGIC)
915 if (quiet == NOISY) {
916 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
918 HEAP_Dump( subheap->heap );
919 } else if (WARN_ON(heap)) {
920 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
922 HEAP_Dump( subheap->heap );
926 /* Check size flags */
927 if (pArena->size & ARENA_FLAG_FREE)
929 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
930 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
933 /* Check arena size */
934 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
936 ERR("Heap %p: bad size %08x for in-use arena %p\n",
937 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
940 /* Check next arena PREV_FREE flag */
941 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
942 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
944 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
945 subheap->heap, pArena );
948 /* Check prev free arena */
949 if (pArena->size & ARENA_FLAG_PREV_FREE)
951 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
952 /* Check prev pointer */
953 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
955 ERR("Heap %p: bad back ptr %p for arena %p\n",
956 subheap->heap, pPrev, pArena );
959 /* Check that prev arena is free */
960 if (!(pPrev->size & ARENA_FLAG_FREE) ||
961 (pPrev->magic != ARENA_FREE_MAGIC))
963 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
964 subheap->heap, pPrev, pArena );
967 /* Check that prev arena is really the previous block */
968 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
970 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
971 subheap->heap, pPrev, pArena );
979 /***********************************************************************
980 * HEAP_IsRealArena [Internal]
981 * Validates a block is a valid arena.
987 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
988 DWORD flags, /* [in] Bit flags that control access during operation */
989 LPCVOID block, /* [in] Optional pointer to memory block to validate */
990 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
991 * does not complain */
996 flags &= HEAP_NO_SERIALIZE;
997 flags |= heapPtr->flags;
998 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
999 if (!(flags & HEAP_NO_SERIALIZE))
1000 RtlEnterCriticalSection( &heapPtr->critSection );
1004 /* Only check this single memory block */
1006 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
1007 ((const char *)block < (char *)subheap + subheap->headerSize
1008 + sizeof(ARENA_INUSE)))
1011 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1012 else if (WARN_ON(heap))
1013 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1016 ret = HEAP_ValidateInUseArena( subheap, (const ARENA_INUSE *)block - 1, quiet );
1018 if (!(flags & HEAP_NO_SERIALIZE))
1019 RtlLeaveCriticalSection( &heapPtr->critSection );
1023 subheap = &heapPtr->subheap;
1024 while (subheap && ret)
1026 char *ptr = (char *)subheap + subheap->headerSize;
1027 while (ptr < (char *)subheap + subheap->size)
1029 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1031 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1035 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1039 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1043 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1046 subheap = subheap->next;
1049 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1054 /***********************************************************************
1055 * RtlCreateHeap (NTDLL.@)
1057 * Create a new Heap.
1060 * flags [I] HEAP_ flags from "winnt.h"
1061 * addr [I] Desired base address
1062 * totalSize [I] Total size of the heap, or 0 for a growable heap
1063 * commitSize [I] Amount of heap space to commit
1064 * unknown [I] Not yet understood
1065 * definition [I] Heap definition
1068 * Success: A HANDLE to the newly created heap.
1069 * Failure: a NULL HANDLE.
1071 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1072 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1076 /* Allocate the heap block */
1080 totalSize = HEAP_DEF_SIZE;
1081 flags |= HEAP_GROWABLE;
1084 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1086 /* link it into the per-process heap list */
1089 HEAP *heapPtr = subheap->heap;
1090 RtlEnterCriticalSection( &processHeap->critSection );
1091 list_add_head( &processHeap->entry, &heapPtr->entry );
1092 RtlLeaveCriticalSection( &processHeap->critSection );
1096 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1097 list_init( &processHeap->entry );
1100 return (HANDLE)subheap;
1104 /***********************************************************************
1105 * RtlDestroyHeap (NTDLL.@)
1107 * Destroy a Heap created with RtlCreateHeap().
1110 * heap [I] Heap to destroy.
1113 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1114 * Failure: The Heap handle, if heap is the process heap.
1116 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1118 HEAP *heapPtr = HEAP_GetPtr( heap );
1121 TRACE("%p\n", heap );
1122 if (!heapPtr) return heap;
1124 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1126 /* remove it from the per-process list */
1127 RtlEnterCriticalSection( &processHeap->critSection );
1128 list_remove( &heapPtr->entry );
1129 RtlLeaveCriticalSection( &processHeap->critSection );
1131 RtlDeleteCriticalSection( &heapPtr->critSection );
1132 subheap = &heapPtr->subheap;
1135 SUBHEAP *next = subheap->next;
1137 void *addr = subheap;
1138 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1145 /***********************************************************************
1146 * RtlAllocateHeap (NTDLL.@)
1148 * Allocate a memory block from a Heap.
1151 * heap [I] Heap to allocate block from
1152 * flags [I] HEAP_ flags from "winnt.h"
1153 * size [I] Size of the memory block to allocate
1156 * Success: A pointer to the newly allocated block
1160 * This call does not SetLastError().
1162 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1165 ARENA_INUSE *pInUse;
1167 HEAP *heapPtr = HEAP_GetPtr( heap );
1168 SIZE_T rounded_size;
1170 /* Validate the parameters */
1172 if (!heapPtr) return NULL;
1173 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1174 flags |= heapPtr->flags;
1175 rounded_size = ROUND_SIZE(size);
1176 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1178 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1179 /* Locate a suitable free block */
1181 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1183 TRACE("(%p,%08x,%08lx): returning NULL\n",
1184 heap, flags, size );
1185 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1186 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1190 /* Remove the arena from the free list */
1192 list_remove( &pArena->entry );
1194 /* Build the in-use arena */
1196 pInUse = (ARENA_INUSE *)pArena;
1198 /* in-use arena is smaller than free arena,
1199 * so we have to add the difference to the size */
1200 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1201 pInUse->magic = ARENA_INUSE_MAGIC;
1203 /* Shrink the block */
1205 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1206 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1208 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1210 if (flags & HEAP_ZERO_MEMORY)
1211 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1213 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1215 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1217 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1218 return (LPVOID)(pInUse + 1);
1222 /***********************************************************************
1223 * RtlFreeHeap (NTDLL.@)
1225 * Free a memory block allocated with RtlAllocateHeap().
1228 * heap [I] Heap that block was allocated from
1229 * flags [I] HEAP_ flags from "winnt.h"
1230 * ptr [I] Block to free
1233 * Success: TRUE, if ptr is NULL or was freed successfully.
1236 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1238 ARENA_INUSE *pInUse;
1242 /* Validate the parameters */
1244 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1246 heapPtr = HEAP_GetPtr( heap );
1249 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1253 flags &= HEAP_NO_SERIALIZE;
1254 flags |= heapPtr->flags;
1255 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1257 /* Some sanity checks */
1259 pInUse = (ARENA_INUSE *)ptr - 1;
1260 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse ))) goto error;
1261 if ((char *)pInUse < (char *)subheap + subheap->headerSize) goto error;
1262 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1264 /* Turn the block into a free block */
1268 HEAP_MakeInUseBlockFree( subheap, pInUse );
1270 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1272 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1276 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1277 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1278 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1283 /***********************************************************************
1284 * RtlReAllocateHeap (NTDLL.@)
1286 * Change the size of a memory block allocated with RtlAllocateHeap().
1289 * heap [I] Heap that block was allocated from
1290 * flags [I] HEAP_ flags from "winnt.h"
1291 * ptr [I] Block to resize
1292 * size [I] Size of the memory block to allocate
1295 * Success: A pointer to the resized block (which may be different).
1298 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1300 ARENA_INUSE *pArena;
1303 SIZE_T oldSize, rounded_size;
1305 if (!ptr) return NULL;
1306 if (!(heapPtr = HEAP_GetPtr( heap )))
1308 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1312 /* Validate the parameters */
1314 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1315 HEAP_REALLOC_IN_PLACE_ONLY;
1316 flags |= heapPtr->flags;
1317 rounded_size = ROUND_SIZE(size);
1318 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1320 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1322 pArena = (ARENA_INUSE *)ptr - 1;
1323 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena ))) goto error;
1324 if ((char *)pArena < (char *)subheap + subheap->headerSize) goto error;
1325 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1327 /* Check if we need to grow the block */
1329 oldSize = (pArena->size & ARENA_SIZE_MASK);
1330 if (rounded_size > oldSize)
1332 char *pNext = (char *)(pArena + 1) + oldSize;
1333 if ((pNext < (char *)subheap + subheap->size) &&
1334 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1335 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1337 /* The next block is free and large enough */
1338 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1339 list_remove( &pFree->entry );
1340 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1341 if (!HEAP_Commit( subheap, pArena, rounded_size ))
1343 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1344 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1345 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1348 notify_free( pArena + 1 );
1349 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1350 notify_alloc( pArena + 1, size, FALSE );
1351 /* FIXME: this is wrong as we may lose old VBits settings */
1352 mark_block_initialized( pArena + 1, oldSize );
1354 else /* Do it the hard way */
1357 ARENA_INUSE *pInUse;
1358 SUBHEAP *newsubheap;
1360 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1361 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1363 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1364 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1365 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1369 /* Build the in-use arena */
1371 list_remove( &pNew->entry );
1372 pInUse = (ARENA_INUSE *)pNew;
1373 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1374 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1375 pInUse->magic = ARENA_INUSE_MAGIC;
1376 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1377 mark_block_initialized( pInUse + 1, oldSize );
1378 notify_alloc( pInUse + 1, size, FALSE );
1379 memcpy( pInUse + 1, pArena + 1, oldSize );
1381 /* Free the previous block */
1383 notify_free( pArena + 1 );
1384 HEAP_MakeInUseBlockFree( subheap, pArena );
1385 subheap = newsubheap;
1391 /* Shrink the block */
1392 notify_free( pArena + 1 );
1393 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1394 notify_alloc( pArena + 1, size, FALSE );
1395 /* FIXME: this is wrong as we may lose old VBits settings */
1396 mark_block_initialized( pArena + 1, size );
1399 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1401 /* Clear the extra bytes if needed */
1403 if (rounded_size > oldSize)
1405 if (flags & HEAP_ZERO_MEMORY)
1406 clear_block( (char *)(pArena + 1) + oldSize,
1407 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1409 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1410 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1413 /* Return the new arena */
1415 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1417 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1418 return (LPVOID)(pArena + 1);
1421 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1422 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1423 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1428 /***********************************************************************
1429 * RtlCompactHeap (NTDLL.@)
1431 * Compact the free space in a Heap.
1434 * heap [I] Heap that block was allocated from
1435 * flags [I] HEAP_ flags from "winnt.h"
1438 * The number of bytes compacted.
1441 * This function is a harmless stub.
1443 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1450 /***********************************************************************
1451 * RtlLockHeap (NTDLL.@)
1456 * heap [I] Heap to lock
1459 * Success: TRUE. The Heap is locked.
1460 * Failure: FALSE, if heap is invalid.
1462 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1464 HEAP *heapPtr = HEAP_GetPtr( heap );
1465 if (!heapPtr) return FALSE;
1466 RtlEnterCriticalSection( &heapPtr->critSection );
1471 /***********************************************************************
1472 * RtlUnlockHeap (NTDLL.@)
1477 * heap [I] Heap to unlock
1480 * Success: TRUE. The Heap is unlocked.
1481 * Failure: FALSE, if heap is invalid.
1483 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1485 HEAP *heapPtr = HEAP_GetPtr( heap );
1486 if (!heapPtr) return FALSE;
1487 RtlLeaveCriticalSection( &heapPtr->critSection );
1492 /***********************************************************************
1493 * RtlSizeHeap (NTDLL.@)
1495 * Get the actual size of a memory block allocated 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 get the size of
1503 * Success: The size of the block.
1504 * Failure: -1, heap or ptr are invalid.
1507 * The size may be bigger than what was passed to RtlAllocateHeap().
1509 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1512 HEAP *heapPtr = HEAP_GetPtr( heap );
1516 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1519 flags &= HEAP_NO_SERIALIZE;
1520 flags |= heapPtr->flags;
1521 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1522 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1524 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1529 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1530 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1532 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1534 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1539 /***********************************************************************
1540 * RtlValidateHeap (NTDLL.@)
1542 * Determine if a block is a valid allocation from a heap.
1545 * heap [I] Heap that block was allocated from
1546 * flags [I] HEAP_ flags from "winnt.h"
1547 * ptr [I] Block to check
1550 * Success: TRUE. The block was allocated from heap.
1551 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1553 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1555 HEAP *heapPtr = HEAP_GetPtr( heap );
1556 if (!heapPtr) return FALSE;
1557 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1561 /***********************************************************************
1562 * RtlWalkHeap (NTDLL.@)
1565 * The PROCESS_HEAP_ENTRY flag values seem different between this
1566 * function and HeapWalk(). To be checked.
1568 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1570 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1571 HEAP *heapPtr = HEAP_GetPtr(heap);
1572 SUBHEAP *sub, *currentheap = NULL;
1575 int region_index = 0;
1577 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1579 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1581 /* set ptr to the next arena to be examined */
1583 if (!entry->lpData) /* first call (init) ? */
1585 TRACE("begin walking of heap %p.\n", heap);
1586 currentheap = &heapPtr->subheap;
1587 ptr = (char*)currentheap + currentheap->headerSize;
1591 ptr = entry->lpData;
1592 sub = &heapPtr->subheap;
1595 if (((char *)ptr >= (char *)sub) &&
1596 ((char *)ptr < (char *)sub + sub->size))
1604 if (currentheap == NULL)
1606 ERR("no matching subheap found, shouldn't happen !\n");
1607 ret = STATUS_NO_MORE_ENTRIES;
1611 ptr += entry->cbData; /* point to next arena */
1612 if (ptr > (char *)currentheap + currentheap->size - 1)
1613 { /* proceed with next subheap */
1614 if (!(currentheap = currentheap->next))
1615 { /* successfully finished */
1616 TRACE("end reached.\n");
1617 ret = STATUS_NO_MORE_ENTRIES;
1620 ptr = (char*)currentheap + currentheap->headerSize;
1625 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1627 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1629 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1631 entry->lpData = pArena + 1;
1632 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1633 entry->cbOverhead = sizeof(ARENA_FREE);
1634 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1638 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1640 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1642 entry->lpData = pArena + 1;
1643 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1644 entry->cbOverhead = sizeof(ARENA_INUSE);
1645 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1646 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1647 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1650 entry->iRegionIndex = region_index;
1652 /* first element of heap ? */
1653 if (ptr == (char *)(currentheap + currentheap->headerSize))
1655 entry->wFlags |= PROCESS_HEAP_REGION;
1656 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1657 entry->u.Region.dwUnCommittedSize =
1658 currentheap->size - currentheap->commitSize;
1659 entry->u.Region.lpFirstBlock = /* first valid block */
1660 currentheap + currentheap->headerSize;
1661 entry->u.Region.lpLastBlock = /* first invalid block */
1662 currentheap + currentheap->size;
1664 ret = STATUS_SUCCESS;
1665 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1668 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1673 /***********************************************************************
1674 * RtlGetProcessHeaps (NTDLL.@)
1676 * Get the Heaps belonging to the current process.
1679 * count [I] size of heaps
1680 * heaps [O] Destination array for heap HANDLE's
1683 * Success: The number of Heaps allocated by the process.
1686 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1688 ULONG total = 1; /* main heap */
1691 RtlEnterCriticalSection( &processHeap->critSection );
1692 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1695 *heaps++ = processHeap;
1696 LIST_FOR_EACH( ptr, &processHeap->entry )
1697 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1699 RtlLeaveCriticalSection( &processHeap->critSection );