push 20d539bd3127e997ce79233e3988ba5740356ce5
[wine/hacks.git] / dlls / ntdll / heap.c
bloba4fac224801c3022f517be69712ebb2db6f6d922
1 /*
2 * Win32 heap functions
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
22 #include "config.h"
23 #include "wine/port.h"
25 #include <assert.h>
26 #include <stdlib.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <string.h>
30 #ifdef HAVE_VALGRIND_MEMCHECK_H
31 #include <valgrind/memcheck.h>
32 #endif
34 #define NONAMELESSUNION
35 #define NONAMELESSSTRUCT
36 #include "ntstatus.h"
37 #define WIN32_NO_STATUS
38 #include "windef.h"
39 #include "winnt.h"
40 #include "winternl.h"
41 #include "wine/list.h"
42 #include "wine/debug.h"
43 #include "wine/server.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(heap);
46 WINE_DECLARE_DEBUG_CHANNEL(heap_poison);
48 /* Note: the heap data structures are loosely based on what Pietrek describes in his
49 * book 'Windows 95 System Programming Secrets', with some adaptations for
50 * better compatibility with NT.
53 typedef struct tagARENA_INUSE
55 DWORD size; /* Block size; must be the first field */
56 DWORD magic : 24; /* Magic number */
57 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) */
58 } ARENA_INUSE;
60 typedef struct tagARENA_FREE
62 DWORD size; /* Block size; must be the first field */
63 DWORD magic; /* Magic number */
64 struct list entry; /* Entry in free list */
65 } ARENA_FREE;
67 typedef struct
69 struct list entry; /* entry in heap large blocks list */
70 SIZE_T data_size; /* size of user data */
71 SIZE_T block_size; /* total size of virtual memory block */
72 DWORD pad[2]; /* padding to ensure 16-byte alignment of data */
73 DWORD size; /* fields for compatibility with normal arenas */
74 DWORD magic; /* these must remain at the end of the structure */
75 } ARENA_LARGE;
77 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
78 #define ARENA_FLAG_PREV_FREE 0x00000002
79 #define ARENA_SIZE_MASK (~3)
80 #define ARENA_LARGE_SIZE 0xfedcba90 /* magic value for 'size' field in large blocks */
82 /* Value for arena 'magic' field */
83 #define ARENA_INUSE_MAGIC 0x455355
84 #define ARENA_FREE_MAGIC 0x45455246
85 #define ARENA_LARGE_MAGIC 0x6752614c
87 #define ARENA_INUSE_FILLER 0x55
88 #define ARENA_FREE_FILLER 0xaa
90 /* everything is aligned on 8 byte boundaries (16 for Win64) */
91 #define ALIGNMENT (2*sizeof(void*))
92 #define LARGE_ALIGNMENT 16 /* large blocks have stricter alignment */
93 #define ARENA_OFFSET (ALIGNMENT - sizeof(ARENA_INUSE))
95 #define ROUND_SIZE(size) ((((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1)) + ARENA_OFFSET)
97 #define QUIET 1 /* Suppress messages */
98 #define NOISY 0 /* Report all errors */
100 /* minimum data size (without arenas) of an allocated block */
101 /* make sure that it's larger than a free list entry */
102 #define HEAP_MIN_DATA_SIZE ROUND_SIZE(2 * sizeof(struct list))
103 /* minimum size that must remain to shrink an allocated block */
104 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
105 /* minimum size to start allocating large blocks */
106 #define HEAP_MIN_LARGE_BLOCK_SIZE 0x7f000
108 /* Max size of the blocks on the free lists */
109 static const SIZE_T HEAP_freeListSizes[] =
111 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
113 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
115 typedef union
117 ARENA_FREE arena;
118 void *alignment[4];
119 } FREE_LIST_ENTRY;
121 struct tagHEAP;
123 typedef struct tagSUBHEAP
125 void *base; /* Base address of the sub-heap memory block */
126 SIZE_T size; /* Size of the whole sub-heap */
127 SIZE_T commitSize; /* Committed size of the sub-heap */
128 struct list entry; /* Entry in sub-heap list */
129 struct tagHEAP *heap; /* Main heap structure */
130 DWORD headerSize; /* Size of the heap header */
131 DWORD magic; /* Magic number */
132 } SUBHEAP;
134 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
136 typedef struct tagHEAP
138 DWORD unknown[3];
139 DWORD flags; /* Heap flags */
140 DWORD force_flags; /* Forced heap flags for debugging */
141 SUBHEAP subheap; /* First sub-heap */
142 struct list entry; /* Entry in process heap list */
143 struct list subheap_list; /* Sub-heap list */
144 struct list large_list; /* Large blocks list */
145 SIZE_T grow_size; /* Size of next subheap for growing heap */
146 DWORD magic; /* Magic number */
147 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
148 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS] DECLSPEC_ALIGN(8); /* Free lists */
149 } HEAP;
151 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
153 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
154 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
156 static HEAP *processHeap; /* main process heap */
158 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
160 /* mark a block of memory as free for debugging purposes */
161 static inline void mark_block_free( void *ptr, SIZE_T size )
163 if (TRACE_ON(heap) || WARN_ON(heap) || TRACE_ON(heap_poison)) memset( ptr, ARENA_FREE_FILLER, size );
164 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
165 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
166 #elif defined( VALGRIND_MAKE_NOACCESS)
167 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
168 #endif
171 /* mark a block of memory as initialized for debugging purposes */
172 static inline void mark_block_initialized( void *ptr, SIZE_T size )
174 #if defined(VALGRIND_MAKE_MEM_DEFINED)
175 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
176 #elif defined(VALGRIND_MAKE_READABLE)
177 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
178 #endif
181 /* mark a block of memory as uninitialized for debugging purposes */
182 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
184 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
185 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
186 #elif defined(VALGRIND_MAKE_WRITABLE)
187 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
188 #endif
189 if (TRACE_ON(heap) || WARN_ON(heap) || TRACE_ON(heap_poison))
191 memset( ptr, ARENA_INUSE_FILLER, size );
192 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
193 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
194 #elif defined(VALGRIND_MAKE_WRITABLE)
195 /* make it uninitialized to valgrind again */
196 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
197 #endif
201 /* clear contents of a block of memory */
202 static inline void clear_block( void *ptr, SIZE_T size )
204 mark_block_initialized( ptr, size );
205 memset( ptr, 0, size );
208 /* notify that a new block of memory has been allocated for debugging purposes */
209 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
211 #ifdef VALGRIND_MALLOCLIKE_BLOCK
212 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
213 #endif
216 /* notify that a block of memory has been freed for debugging purposes */
217 static inline void notify_free( void const *ptr )
219 #ifdef VALGRIND_FREELIKE_BLOCK
220 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
221 #endif
224 static void subheap_notify_free_all(SUBHEAP const *subheap)
226 #ifdef VALGRIND_FREELIKE_BLOCK
227 char const *ptr = (char const *)subheap->base + subheap->headerSize;
229 if (!RUNNING_ON_VALGRIND) return;
231 while (ptr < (char const *)subheap->base + subheap->size)
233 if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
235 ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
236 if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
237 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
239 else
241 ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
242 if (pArena->magic!=ARENA_INUSE_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
243 notify_free(pArena + 1);
244 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
247 #endif
250 /* locate a free list entry of the appropriate size */
251 /* size is the size of the whole block including the arena header */
252 static inline unsigned int get_freelist_index( SIZE_T size )
254 unsigned int i;
256 size -= sizeof(ARENA_FREE);
257 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
258 return i;
261 /* get the memory protection type to use for a given heap */
262 static inline ULONG get_protection_type( DWORD flags )
264 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
267 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
269 0, 0, NULL, /* will be set later */
270 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
271 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
275 /***********************************************************************
276 * HEAP_Dump
278 static void HEAP_Dump( HEAP *heap )
280 unsigned int i;
281 SUBHEAP *subheap;
282 char *ptr;
284 DPRINTF( "Heap: %p\n", heap );
285 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
286 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
288 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
289 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
290 DPRINTF( "%p free %08lx prev=%p next=%p\n",
291 &heap->freeList[i].arena, HEAP_freeListSizes[i],
292 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
293 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
295 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
297 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
298 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
299 subheap, subheap->base, subheap->size, subheap->commitSize );
301 DPRINTF( "\n Block Arena Stat Size Id\n" );
302 ptr = (char *)subheap->base + subheap->headerSize;
303 while (ptr < (char *)subheap->base + subheap->size)
305 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
307 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
308 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
309 pArena, pArena->magic,
310 pArena->size & ARENA_SIZE_MASK,
311 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
312 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
313 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
314 arenaSize += sizeof(ARENA_FREE);
315 freeSize += pArena->size & ARENA_SIZE_MASK;
317 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
319 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
320 DPRINTF( "%p %08x Used %08x back=%p\n",
321 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
322 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
323 arenaSize += sizeof(ARENA_INUSE);
324 usedSize += pArena->size & ARENA_SIZE_MASK;
326 else
328 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
329 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
330 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
331 arenaSize += sizeof(ARENA_INUSE);
332 usedSize += pArena->size & ARENA_SIZE_MASK;
335 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
336 subheap->size, subheap->commitSize, freeSize, usedSize,
337 arenaSize, (arenaSize * 100) / subheap->size );
342 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
344 WORD rem_flags;
345 TRACE( "Dumping entry %p\n", entry );
346 TRACE( "lpData\t\t: %p\n", entry->lpData );
347 TRACE( "cbData\t\t: %08x\n", entry->cbData);
348 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
349 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
350 TRACE( "WFlags\t\t: ");
351 if (entry->wFlags & PROCESS_HEAP_REGION)
352 TRACE( "PROCESS_HEAP_REGION ");
353 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
354 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
355 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
356 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
357 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
358 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
359 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
360 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
361 rem_flags = entry->wFlags &
362 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
363 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
364 PROCESS_HEAP_ENTRY_DDESHARE);
365 if (rem_flags)
366 TRACE( "Unknown %08x", rem_flags);
367 TRACE( "\n");
368 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
369 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
371 /* Treat as block */
372 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
374 if (entry->wFlags & PROCESS_HEAP_REGION)
376 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
377 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
378 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
379 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
383 /***********************************************************************
384 * HEAP_GetPtr
385 * RETURNS
386 * Pointer to the heap
387 * NULL: Failure
389 static HEAP *HEAP_GetPtr(
390 HANDLE heap /* [in] Handle to the heap */
392 HEAP *heapPtr = heap;
393 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
395 ERR("Invalid heap %p!\n", heap );
396 return NULL;
398 if ((TRACE_ON(heap)|| TRACE_ON(heap_poison)) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
400 HEAP_Dump( heapPtr );
401 assert( FALSE );
402 return NULL;
404 return heapPtr;
408 /***********************************************************************
409 * HEAP_InsertFreeBlock
411 * Insert a free block into the free list.
413 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
415 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
416 if (last)
418 /* insert at end of free list, i.e. before the next free list entry */
419 pEntry++;
420 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
421 list_add_before( &pEntry->arena.entry, &pArena->entry );
423 else
425 /* insert at head of free list */
426 list_add_after( &pEntry->arena.entry, &pArena->entry );
428 pArena->size |= ARENA_FLAG_FREE;
432 /***********************************************************************
433 * HEAP_FindSubHeap
434 * Find the sub-heap containing a given address.
436 * RETURNS
437 * Pointer: Success
438 * NULL: Failure
440 static SUBHEAP *HEAP_FindSubHeap(
441 const HEAP *heap, /* [in] Heap pointer */
442 LPCVOID ptr ) /* [in] Address */
444 SUBHEAP *sub;
445 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
446 if ((ptr >= sub->base) &&
447 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
448 return sub;
449 return NULL;
453 /***********************************************************************
454 * HEAP_Commit
456 * Make sure the heap storage is committed for a given size in the specified arena.
458 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
460 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
461 SIZE_T size = (char *)ptr - (char *)subheap->base;
462 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
463 if (size > subheap->size) size = subheap->size;
464 if (size <= subheap->commitSize) return TRUE;
465 size -= subheap->commitSize;
466 ptr = (char *)subheap->base + subheap->commitSize;
467 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
468 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
470 WARN("Could not commit %08lx bytes at %p for heap %p\n",
471 size, ptr, subheap->heap );
472 return FALSE;
474 subheap->commitSize += size;
475 return TRUE;
479 /***********************************************************************
480 * HEAP_Decommit
482 * If possible, decommit the heap storage from (including) 'ptr'.
484 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
486 void *addr;
487 SIZE_T decommit_size;
488 SIZE_T size = (char *)ptr - (char *)subheap->base;
490 /* round to next block and add one full block */
491 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
492 if (size >= subheap->commitSize) return TRUE;
493 decommit_size = subheap->commitSize - size;
494 addr = (char *)subheap->base + size;
496 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
498 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
499 decommit_size, (char *)subheap->base + size, subheap->heap );
500 return FALSE;
502 subheap->commitSize -= decommit_size;
503 return TRUE;
507 /***********************************************************************
508 * HEAP_CreateFreeBlock
510 * Create a free block at a specified address. 'size' is the size of the
511 * whole block, including the new arena.
513 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
515 ARENA_FREE *pFree;
516 char *pEnd;
517 BOOL last;
519 /* Create a free arena */
520 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
521 pFree = ptr;
522 pFree->magic = ARENA_FREE_MAGIC;
524 /* If debugging, erase the freed block content */
526 pEnd = (char *)ptr + size;
527 if (pEnd > (char *)subheap->base + subheap->commitSize)
528 pEnd = (char *)subheap->base + subheap->commitSize;
529 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
531 /* Check if next block is free also */
533 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
534 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
536 /* Remove the next arena from the free list */
537 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
538 list_remove( &pNext->entry );
539 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
540 mark_block_free( pNext, sizeof(ARENA_FREE) );
543 /* Set the next block PREV_FREE flag and pointer */
545 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
546 if (!last)
548 DWORD *pNext = (DWORD *)((char *)ptr + size);
549 *pNext |= ARENA_FLAG_PREV_FREE;
550 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
551 *((ARENA_FREE **)pNext - 1) = pFree;
554 /* Last, insert the new block into the free list */
556 pFree->size = size - sizeof(*pFree);
557 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
561 /***********************************************************************
562 * HEAP_MakeInUseBlockFree
564 * Turn an in-use block into a free block. Can also decommit the end of
565 * the heap, and possibly even free the sub-heap altogether.
567 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
569 ARENA_FREE *pFree;
570 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
572 /* Check if we can merge with previous block */
574 if (pArena->size & ARENA_FLAG_PREV_FREE)
576 pFree = *((ARENA_FREE **)pArena - 1);
577 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
578 /* Remove it from the free list */
579 list_remove( &pFree->entry );
581 else pFree = (ARENA_FREE *)pArena;
583 /* Create a free block */
585 HEAP_CreateFreeBlock( subheap, pFree, size );
586 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
587 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
588 return; /* Not the last block, so nothing more to do */
590 /* Free the whole sub-heap if it's empty and not the original one */
592 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
593 (subheap != &subheap->heap->subheap))
595 SIZE_T size = 0;
596 void *addr = subheap->base;
597 /* Remove the free block from the list */
598 list_remove( &pFree->entry );
599 /* Remove the subheap from the list */
600 list_remove( &subheap->entry );
601 /* Free the memory */
602 subheap->magic = 0;
603 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
604 return;
607 /* Decommit the end of the heap */
609 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
613 /***********************************************************************
614 * HEAP_ShrinkBlock
616 * Shrink an in-use block.
618 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
620 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
622 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
623 (pArena->size & ARENA_SIZE_MASK) - size );
624 /* assign size plus previous arena flags */
625 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
627 else
629 /* Turn off PREV_FREE flag in next block */
630 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
631 if (pNext < (char *)subheap->base + subheap->size)
632 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
637 /***********************************************************************
638 * allocate_large_block
640 static void *allocate_large_block( HEAP *heap, DWORD flags, SIZE_T size )
642 ARENA_LARGE *arena;
643 SIZE_T block_size = sizeof(*arena) + ROUND_SIZE(size);
644 LPVOID address = NULL;
646 if (block_size < size) return NULL; /* overflow */
647 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
648 &block_size, MEM_COMMIT, get_protection_type( flags ) ))
650 WARN("Could not allocate block for %08lx bytes\n", size );
651 return NULL;
653 arena = address;
654 arena->data_size = size;
655 arena->block_size = block_size;
656 arena->size = ARENA_LARGE_SIZE;
657 arena->magic = ARENA_LARGE_MAGIC;
658 list_add_tail( &heap->large_list, &arena->entry );
659 return arena + 1;
663 /***********************************************************************
664 * free_large_block
666 static void free_large_block( HEAP *heap, DWORD flags, void *ptr )
668 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
669 LPVOID address = arena;
670 SIZE_T size = 0;
672 list_remove( &arena->entry );
673 NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
677 /***********************************************************************
678 * realloc_large_block
680 static void *realloc_large_block( HEAP *heap, DWORD flags, void *ptr, SIZE_T size )
682 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
683 void *new_ptr;
685 if (arena->block_size - sizeof(*arena) >= size)
687 /* FIXME: we could remap zero-pages instead */
688 if ((flags & HEAP_ZERO_MEMORY) && size > arena->data_size)
689 memset( (char *)ptr + arena->data_size, 0, size - arena->data_size );
690 arena->data_size = size;
691 return ptr;
693 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) return NULL;
694 if (!(new_ptr = allocate_large_block( heap, flags, size )))
696 WARN("Could not allocate block for %08lx bytes\n", size );
697 return NULL;
699 memcpy( new_ptr, ptr, arena->data_size );
700 free_large_block( heap, flags, ptr );
701 return new_ptr;
705 /***********************************************************************
706 * find_large_block
708 static ARENA_LARGE *find_large_block( HEAP *heap, const void *ptr )
710 ARENA_LARGE *arena;
712 LIST_FOR_EACH_ENTRY( arena, &heap->large_list, ARENA_LARGE, entry )
713 if (ptr == arena + 1) return arena;
715 return NULL;
719 /***********************************************************************
720 * validate_large_arena
722 static BOOL validate_large_arena( HEAP *heap, const ARENA_LARGE *arena, BOOL quiet )
724 if ((ULONG_PTR)arena % getpagesize())
726 if (quiet == NOISY)
728 ERR( "Heap %p: invalid large arena pointer %p\n", heap, arena );
729 if (TRACE_ON(heap)) HEAP_Dump( heap );
731 else if (WARN_ON(heap))
733 WARN( "Heap %p: unaligned arena pointer %p\n", heap, arena );
734 if (TRACE_ON(heap)) HEAP_Dump( heap );
736 return FALSE;
738 if (arena->size != ARENA_LARGE_SIZE || arena->magic != ARENA_LARGE_MAGIC)
740 if (quiet == NOISY)
742 ERR( "Heap %p: invalid large arena %p values %x/%x\n",
743 heap, arena, arena->size, arena->magic );
744 if (TRACE_ON(heap)) HEAP_Dump( heap );
746 else if (WARN_ON(heap))
748 WARN( "Heap %p: invalid large arena %p values %x/%x\n",
749 heap, arena, arena->size, arena->magic );
750 if (TRACE_ON(heap)) HEAP_Dump( heap );
752 return FALSE;
754 return TRUE;
758 /***********************************************************************
759 * HEAP_CreateSubHeap
761 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, LPVOID address, DWORD flags,
762 SIZE_T commitSize, SIZE_T totalSize )
764 SUBHEAP *subheap;
765 FREE_LIST_ENTRY *pEntry;
766 unsigned int i;
768 if (!address)
770 /* round-up sizes on a 64K boundary */
771 totalSize = (totalSize + 0xffff) & 0xffff0000;
772 commitSize = (commitSize + 0xffff) & 0xffff0000;
773 if (!commitSize) commitSize = 0x10000;
774 totalSize = min( totalSize, 0xffff0000 ); /* don't allow a heap larger than 4Gb */
775 if (totalSize < commitSize) totalSize = commitSize;
776 if (flags & HEAP_SHARED) commitSize = totalSize; /* always commit everything in a shared heap */
778 /* allocate the memory block */
779 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
780 MEM_RESERVE, get_protection_type( flags ) ))
782 WARN("Could not allocate %08lx bytes\n", totalSize );
783 return NULL;
785 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
786 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
788 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
789 return NULL;
793 if (heap)
795 /* If this is a secondary subheap, insert it into list */
797 subheap = address;
798 subheap->base = address;
799 subheap->heap = heap;
800 subheap->size = totalSize;
801 subheap->commitSize = commitSize;
802 subheap->magic = SUBHEAP_MAGIC;
803 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
804 list_add_head( &heap->subheap_list, &subheap->entry );
806 else
808 /* If this is a primary subheap, initialize main heap */
810 heap = address;
811 heap->flags = flags;
812 heap->magic = HEAP_MAGIC;
813 heap->grow_size = max( HEAP_DEF_SIZE, totalSize );
814 list_init( &heap->subheap_list );
815 list_init( &heap->large_list );
817 subheap = &heap->subheap;
818 subheap->base = address;
819 subheap->heap = heap;
820 subheap->size = totalSize;
821 subheap->commitSize = commitSize;
822 subheap->magic = SUBHEAP_MAGIC;
823 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
824 list_add_head( &heap->subheap_list, &subheap->entry );
826 /* Build the free lists */
828 list_init( &heap->freeList[0].arena.entry );
829 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
831 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
832 pEntry->arena.magic = ARENA_FREE_MAGIC;
833 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
836 /* Initialize critical section */
838 if (!processHeap) /* do it by hand to avoid memory allocations */
840 if(TRACE_ON(heap_poison))
841 TRACE_(heap_poison)("poisioning heap\n");
842 heap->critSection.DebugInfo = &process_heap_critsect_debug;
843 heap->critSection.LockCount = -1;
844 heap->critSection.RecursionCount = 0;
845 heap->critSection.OwningThread = 0;
846 heap->critSection.LockSemaphore = 0;
847 heap->critSection.SpinCount = 0;
848 process_heap_critsect_debug.CriticalSection = &heap->critSection;
850 else
852 RtlInitializeCriticalSection( &heap->critSection );
853 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
856 if (flags & HEAP_SHARED)
858 /* let's assume that only one thread at a time will try to do this */
859 HANDLE sem = heap->critSection.LockSemaphore;
860 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
862 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
863 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
864 heap->critSection.LockSemaphore = sem;
865 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
866 heap->critSection.DebugInfo = NULL;
870 /* Create the first free block */
872 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
873 subheap->size - subheap->headerSize );
875 return subheap;
879 /***********************************************************************
880 * HEAP_FindFreeBlock
882 * Find a free block at least as large as the requested size, and make sure
883 * the requested size is committed.
885 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
886 SUBHEAP **ppSubHeap )
888 SUBHEAP *subheap;
889 struct list *ptr;
890 SIZE_T total_size;
891 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
893 /* Find a suitable free list, and in it find a block large enough */
895 ptr = &pEntry->arena.entry;
896 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
898 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
899 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
900 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
901 if (arena_size >= size)
903 subheap = HEAP_FindSubHeap( heap, pArena );
904 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
905 *ppSubHeap = subheap;
906 return pArena;
910 /* If no block was found, attempt to grow the heap */
912 if (!(heap->flags & HEAP_GROWABLE))
914 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
915 return NULL;
917 /* make sure that we have a big enough size *committed* to fit another
918 * last free arena in !
919 * So just one heap struct, one first free arena which will eventually
920 * get used, and a second free arena that might get assigned all remaining
921 * free space in HEAP_ShrinkBlock() */
922 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
923 if (total_size < size) return NULL; /* overflow */
925 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
926 max( heap->grow_size, total_size ) )))
927 return NULL;
929 if (heap->grow_size < 128 * 1024 * 1024) heap->grow_size *= 2;
931 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
932 subheap, subheap->size, heap );
934 *ppSubHeap = subheap;
935 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
939 /***********************************************************************
940 * HEAP_IsValidArenaPtr
942 * Check that the pointer is inside the range possible for arenas.
944 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
946 unsigned int i;
947 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
948 if (!subheap) return FALSE;
949 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
950 if (subheap != &heap->subheap) return FALSE;
951 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
952 if (ptr == &heap->freeList[i].arena) return TRUE;
953 return FALSE;
957 /***********************************************************************
958 * HEAP_ValidateFreeArena
960 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
962 ARENA_FREE *prev, *next;
963 char *heapEnd = (char *)subheap->base + subheap->size;
965 /* Check for unaligned pointers */
966 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
968 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
969 return FALSE;
972 /* Check magic number */
973 if (pArena->magic != ARENA_FREE_MAGIC)
975 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
976 return FALSE;
978 /* Check size flags */
979 if (!(pArena->size & ARENA_FLAG_FREE) ||
980 (pArena->size & ARENA_FLAG_PREV_FREE))
982 ERR("Heap %p: bad flags %08x for free arena %p\n",
983 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
984 return FALSE;
986 /* Check arena size */
987 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
989 ERR("Heap %p: bad size %08x for free arena %p\n",
990 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
991 return FALSE;
993 /* Check that next pointer is valid */
994 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
995 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
997 ERR("Heap %p: bad next ptr %p for arena %p\n",
998 subheap->heap, next, pArena );
999 return FALSE;
1001 /* Check that next arena is free */
1002 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1004 ERR("Heap %p: next arena %p invalid for %p\n",
1005 subheap->heap, next, pArena );
1006 return FALSE;
1008 /* Check that prev pointer is valid */
1009 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1010 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1012 ERR("Heap %p: bad prev ptr %p for arena %p\n",
1013 subheap->heap, prev, pArena );
1014 return FALSE;
1016 /* Check that prev arena is free */
1017 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1019 /* this often means that the prev arena got overwritten
1020 * by a memory write before that prev arena */
1021 ERR("Heap %p: prev arena %p invalid for %p\n",
1022 subheap->heap, prev, pArena );
1023 return FALSE;
1025 /* Check that next block has PREV_FREE flag */
1026 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
1028 if (!(*(DWORD *)((char *)(pArena + 1) +
1029 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1031 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1032 subheap->heap, pArena );
1033 return FALSE;
1035 /* Check next block back pointer */
1036 if (*((ARENA_FREE **)((char *)(pArena + 1) +
1037 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
1039 ERR("Heap %p: arena %p has wrong back ptr %p\n",
1040 subheap->heap, pArena,
1041 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
1042 return FALSE;
1045 return TRUE;
1049 /***********************************************************************
1050 * HEAP_ValidateInUseArena
1052 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1054 const char *heapEnd = (const char *)subheap->base + subheap->size;
1056 /* Check for unaligned pointers */
1057 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1059 if ( quiet == NOISY )
1061 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1062 if ( TRACE_ON(heap) )
1063 HEAP_Dump( subheap->heap );
1065 else if ( WARN_ON(heap) )
1067 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1068 if ( TRACE_ON(heap) )
1069 HEAP_Dump( subheap->heap );
1071 return FALSE;
1074 /* Check magic number */
1075 if (pArena->magic != ARENA_INUSE_MAGIC)
1077 if (quiet == NOISY) {
1078 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1079 if (TRACE_ON(heap))
1080 HEAP_Dump( subheap->heap );
1081 } else if (WARN_ON(heap)) {
1082 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1083 if (TRACE_ON(heap))
1084 HEAP_Dump( subheap->heap );
1086 return FALSE;
1088 /* Check size flags */
1089 if (pArena->size & ARENA_FLAG_FREE)
1091 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1092 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1093 return FALSE;
1095 /* Check arena size */
1096 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
1098 ERR("Heap %p: bad size %08x for in-use arena %p\n",
1099 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
1100 return FALSE;
1102 /* Check next arena PREV_FREE flag */
1103 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
1104 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1106 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
1107 subheap->heap, pArena );
1108 return FALSE;
1110 /* Check prev free arena */
1111 if (pArena->size & ARENA_FLAG_PREV_FREE)
1113 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1114 /* Check prev pointer */
1115 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1117 ERR("Heap %p: bad back ptr %p for arena %p\n",
1118 subheap->heap, pPrev, pArena );
1119 return FALSE;
1121 /* Check that prev arena is free */
1122 if (!(pPrev->size & ARENA_FLAG_FREE) ||
1123 (pPrev->magic != ARENA_FREE_MAGIC))
1125 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1126 subheap->heap, pPrev, pArena );
1127 return FALSE;
1129 /* Check that prev arena is really the previous block */
1130 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1132 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1133 subheap->heap, pPrev, pArena );
1134 return FALSE;
1137 return TRUE;
1141 /***********************************************************************
1142 * HEAP_IsRealArena [Internal]
1143 * Validates a block is a valid arena.
1145 * RETURNS
1146 * TRUE: Success
1147 * FALSE: Failure
1149 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1150 DWORD flags, /* [in] Bit flags that control access during operation */
1151 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1152 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1153 * does not complain */
1155 SUBHEAP *subheap;
1156 BOOL ret = TRUE;
1157 const ARENA_LARGE *large_arena;
1159 flags &= HEAP_NO_SERIALIZE;
1160 flags |= heapPtr->flags;
1161 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1162 if (!(flags & HEAP_NO_SERIALIZE))
1163 RtlEnterCriticalSection( &heapPtr->critSection );
1165 if (block) /* only check this single memory block */
1167 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1169 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1170 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1172 if (!(large_arena = find_large_block( heapPtr, block )))
1174 if (quiet == NOISY)
1175 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1176 else if (WARN_ON(heap))
1177 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1178 ret = FALSE;
1180 else
1181 ret = validate_large_arena( heapPtr, large_arena, quiet );
1182 } else
1183 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1185 if (!(flags & HEAP_NO_SERIALIZE))
1186 RtlLeaveCriticalSection( &heapPtr->critSection );
1187 return ret;
1190 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1192 char *ptr = (char *)subheap->base + subheap->headerSize;
1193 while (ptr < (char *)subheap->base + subheap->size)
1195 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1197 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1198 ret = FALSE;
1199 break;
1201 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1203 else
1205 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1206 ret = FALSE;
1207 break;
1209 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1212 if (!ret) break;
1215 LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1216 if (!(ret = validate_large_arena( heapPtr, large_arena, quiet ))) break;
1218 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1219 return ret;
1223 /***********************************************************************
1224 * RtlCreateHeap (NTDLL.@)
1226 * Create a new Heap.
1228 * PARAMS
1229 * flags [I] HEAP_ flags from "winnt.h"
1230 * addr [I] Desired base address
1231 * totalSize [I] Total size of the heap, or 0 for a growable heap
1232 * commitSize [I] Amount of heap space to commit
1233 * unknown [I] Not yet understood
1234 * definition [I] Heap definition
1236 * RETURNS
1237 * Success: A HANDLE to the newly created heap.
1238 * Failure: a NULL HANDLE.
1240 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1241 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1243 SUBHEAP *subheap;
1245 /* Allocate the heap block */
1247 if (!totalSize)
1249 totalSize = HEAP_DEF_SIZE;
1250 flags |= HEAP_GROWABLE;
1253 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1255 /* link it into the per-process heap list */
1256 if (processHeap)
1258 HEAP *heapPtr = subheap->heap;
1259 RtlEnterCriticalSection( &processHeap->critSection );
1260 list_add_head( &processHeap->entry, &heapPtr->entry );
1261 RtlLeaveCriticalSection( &processHeap->critSection );
1263 else if (!addr)
1265 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1266 list_init( &processHeap->entry );
1267 /* make sure structure alignment is correct */
1268 assert( (ULONG_PTR)processHeap->freeList % ALIGNMENT == ARENA_OFFSET );
1269 assert( sizeof(ARENA_LARGE) % LARGE_ALIGNMENT == 0 );
1272 return subheap->heap;
1276 /***********************************************************************
1277 * RtlDestroyHeap (NTDLL.@)
1279 * Destroy a Heap created with RtlCreateHeap().
1281 * PARAMS
1282 * heap [I] Heap to destroy.
1284 * RETURNS
1285 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1286 * Failure: The Heap handle, if heap is the process heap.
1288 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1290 HEAP *heapPtr = HEAP_GetPtr( heap );
1291 SUBHEAP *subheap, *next;
1292 ARENA_LARGE *arena, *arena_next;
1293 SIZE_T size;
1294 void *addr;
1296 TRACE("%p\n", heap );
1297 if (!heapPtr) return heap;
1299 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1301 /* remove it from the per-process list */
1302 RtlEnterCriticalSection( &processHeap->critSection );
1303 list_remove( &heapPtr->entry );
1304 RtlLeaveCriticalSection( &processHeap->critSection );
1306 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1307 RtlDeleteCriticalSection( &heapPtr->critSection );
1309 LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1311 list_remove( &arena->entry );
1312 size = 0;
1313 addr = arena;
1314 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1316 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1318 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1319 subheap_notify_free_all(subheap);
1320 list_remove( &subheap->entry );
1321 size = 0;
1322 addr = subheap->base;
1323 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1325 subheap_notify_free_all(&heapPtr->subheap);
1326 size = 0;
1327 addr = heapPtr->subheap.base;
1328 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1329 return 0;
1333 /***********************************************************************
1334 * RtlAllocateHeap (NTDLL.@)
1336 * Allocate a memory block from a Heap.
1338 * PARAMS
1339 * heap [I] Heap to allocate block from
1340 * flags [I] HEAP_ flags from "winnt.h"
1341 * size [I] Size of the memory block to allocate
1343 * RETURNS
1344 * Success: A pointer to the newly allocated block
1345 * Failure: NULL.
1347 * NOTES
1348 * This call does not SetLastError().
1350 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1352 ARENA_FREE *pArena;
1353 ARENA_INUSE *pInUse;
1354 SUBHEAP *subheap;
1355 HEAP *heapPtr = HEAP_GetPtr( heap );
1356 SIZE_T rounded_size;
1358 /* Validate the parameters */
1360 if (!heapPtr) return NULL;
1361 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1362 flags |= heapPtr->flags;
1363 rounded_size = ROUND_SIZE(size);
1364 if (rounded_size < size) /* overflow */
1366 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1367 return NULL;
1369 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1371 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1373 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1375 void *ret = allocate_large_block( heap, flags, size );
1376 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1377 if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1378 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1379 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1380 return ret;
1383 /* Locate a suitable free block */
1385 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1387 TRACE("(%p,%08x,%08lx): returning NULL\n",
1388 heap, flags, size );
1389 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1390 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1391 return NULL;
1394 /* Remove the arena from the free list */
1396 list_remove( &pArena->entry );
1398 /* Build the in-use arena */
1400 pInUse = (ARENA_INUSE *)pArena;
1402 /* in-use arena is smaller than free arena,
1403 * so we have to add the difference to the size */
1404 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1405 pInUse->magic = ARENA_INUSE_MAGIC;
1407 /* Shrink the block */
1409 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1410 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1412 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1414 if (flags & HEAP_ZERO_MEMORY)
1416 clear_block( pInUse + 1, size );
1417 mark_block_uninitialized( (char *)(pInUse + 1) + size, pInUse->unused_bytes );
1419 else
1420 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1422 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1424 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1425 return pInUse + 1;
1429 /***********************************************************************
1430 * RtlFreeHeap (NTDLL.@)
1432 * Free a memory block allocated with RtlAllocateHeap().
1434 * PARAMS
1435 * heap [I] Heap that block was allocated from
1436 * flags [I] HEAP_ flags from "winnt.h"
1437 * ptr [I] Block to free
1439 * RETURNS
1440 * Success: TRUE, if ptr is NULL or was freed successfully.
1441 * Failure: FALSE.
1443 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1445 ARENA_INUSE *pInUse;
1446 SUBHEAP *subheap;
1447 HEAP *heapPtr;
1449 /* Validate the parameters */
1451 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1453 heapPtr = HEAP_GetPtr( heap );
1454 if (!heapPtr)
1456 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1457 return FALSE;
1460 flags &= HEAP_NO_SERIALIZE;
1461 flags |= heapPtr->flags;
1462 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1464 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1465 notify_free( ptr );
1467 /* Some sanity checks */
1468 pInUse = (ARENA_INUSE *)ptr - 1;
1469 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse )))
1471 if (!find_large_block( heapPtr, ptr )) goto error;
1472 free_large_block( heapPtr, flags, ptr );
1473 goto done;
1475 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1476 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1478 /* Turn the block into a free block */
1480 HEAP_MakeInUseBlockFree( subheap, pInUse );
1482 done:
1483 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1484 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1485 return TRUE;
1487 error:
1488 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1489 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1490 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1491 return FALSE;
1495 /***********************************************************************
1496 * RtlReAllocateHeap (NTDLL.@)
1498 * Change the size of a memory block allocated with RtlAllocateHeap().
1500 * PARAMS
1501 * heap [I] Heap that block was allocated from
1502 * flags [I] HEAP_ flags from "winnt.h"
1503 * ptr [I] Block to resize
1504 * size [I] Size of the memory block to allocate
1506 * RETURNS
1507 * Success: A pointer to the resized block (which may be different).
1508 * Failure: NULL.
1510 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1512 ARENA_INUSE *pArena;
1513 HEAP *heapPtr;
1514 SUBHEAP *subheap;
1515 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1516 void *ret;
1518 if (!ptr) return NULL;
1519 if (!(heapPtr = HEAP_GetPtr( heap )))
1521 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1522 return NULL;
1525 /* Validate the parameters */
1527 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1528 HEAP_REALLOC_IN_PLACE_ONLY;
1529 flags |= heapPtr->flags;
1530 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1532 rounded_size = ROUND_SIZE(size);
1533 if (rounded_size < size) goto oom; /* overflow */
1534 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1536 pArena = (ARENA_INUSE *)ptr - 1;
1537 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena )))
1539 if (!find_large_block( heapPtr, ptr )) goto error;
1540 if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1541 notify_free( ptr );
1542 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1543 goto done;
1545 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1546 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1548 /* Check if we need to grow the block */
1550 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1551 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1552 if (rounded_size > oldBlockSize)
1554 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1556 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1558 if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1559 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1560 memcpy( ret, pArena + 1, oldActualSize );
1561 /* FIXME: free old memory here! */
1562 goto done;
1564 if ((pNext < (char *)subheap->base + subheap->size) &&
1565 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1566 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1568 /* The next block is free and large enough */
1569 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1570 list_remove( &pFree->entry );
1571 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1572 if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1573 notify_free( pArena + 1 );
1574 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1575 notify_alloc( pArena + 1, size, FALSE );
1576 /* FIXME: this is wrong as we may lose old VBits settings */
1577 mark_block_initialized( pArena + 1, oldActualSize );
1579 else /* Do it the hard way */
1581 ARENA_FREE *pNew;
1582 ARENA_INUSE *pInUse;
1583 SUBHEAP *newsubheap;
1585 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1586 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1587 goto oom;
1589 /* Build the in-use arena */
1591 list_remove( &pNew->entry );
1592 pInUse = (ARENA_INUSE *)pNew;
1593 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1594 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1595 pInUse->magic = ARENA_INUSE_MAGIC;
1596 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1598 mark_block_initialized( pInUse + 1, oldActualSize );
1599 notify_alloc( pInUse + 1, size, FALSE );
1600 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1602 /* Free the previous block */
1604 notify_free( pArena + 1 );
1605 HEAP_MakeInUseBlockFree( subheap, pArena );
1606 subheap = newsubheap;
1607 pArena = pInUse;
1610 else
1612 /* Shrink the block */
1613 notify_free( pArena + 1 );
1614 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1615 notify_alloc( pArena + 1, size, FALSE );
1616 /* FIXME: this is wrong as we may lose old VBits settings */
1617 mark_block_initialized( pArena + 1, size );
1620 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1622 /* Clear the extra bytes if needed */
1624 if (size > oldActualSize)
1626 if (flags & HEAP_ZERO_MEMORY)
1628 clear_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize );
1629 mark_block_uninitialized( (char *)(pArena + 1) + size, pArena->unused_bytes );
1631 else
1632 mark_block_uninitialized( (char *)(pArena + 1) + oldActualSize,
1633 (pArena->size & ARENA_SIZE_MASK) - oldActualSize );
1636 /* Return the new arena */
1638 ret = pArena + 1;
1639 done:
1640 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1641 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1642 return ret;
1644 oom:
1645 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1646 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1647 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1648 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1649 return NULL;
1651 error:
1652 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1653 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1654 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1655 return NULL;
1659 /***********************************************************************
1660 * RtlCompactHeap (NTDLL.@)
1662 * Compact the free space in a Heap.
1664 * PARAMS
1665 * heap [I] Heap that block was allocated from
1666 * flags [I] HEAP_ flags from "winnt.h"
1668 * RETURNS
1669 * The number of bytes compacted.
1671 * NOTES
1672 * This function is a harmless stub.
1674 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1676 static BOOL reported;
1677 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1678 return 0;
1682 /***********************************************************************
1683 * RtlLockHeap (NTDLL.@)
1685 * Lock a Heap.
1687 * PARAMS
1688 * heap [I] Heap to lock
1690 * RETURNS
1691 * Success: TRUE. The Heap is locked.
1692 * Failure: FALSE, if heap is invalid.
1694 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1696 HEAP *heapPtr = HEAP_GetPtr( heap );
1697 if (!heapPtr) return FALSE;
1698 RtlEnterCriticalSection( &heapPtr->critSection );
1699 return TRUE;
1703 /***********************************************************************
1704 * RtlUnlockHeap (NTDLL.@)
1706 * Unlock a Heap.
1708 * PARAMS
1709 * heap [I] Heap to unlock
1711 * RETURNS
1712 * Success: TRUE. The Heap is unlocked.
1713 * Failure: FALSE, if heap is invalid.
1715 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1717 HEAP *heapPtr = HEAP_GetPtr( heap );
1718 if (!heapPtr) return FALSE;
1719 RtlLeaveCriticalSection( &heapPtr->critSection );
1720 return TRUE;
1724 /***********************************************************************
1725 * RtlSizeHeap (NTDLL.@)
1727 * Get the actual size of a memory block allocated from a Heap.
1729 * PARAMS
1730 * heap [I] Heap that block was allocated from
1731 * flags [I] HEAP_ flags from "winnt.h"
1732 * ptr [I] Block to get the size of
1734 * RETURNS
1735 * Success: The size of the block.
1736 * Failure: -1, heap or ptr are invalid.
1738 * NOTES
1739 * The size may be bigger than what was passed to RtlAllocateHeap().
1741 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1743 SIZE_T ret;
1744 HEAP *heapPtr = HEAP_GetPtr( heap );
1746 if (!heapPtr)
1748 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1749 return ~0UL;
1751 flags &= HEAP_NO_SERIALIZE;
1752 flags |= heapPtr->flags;
1753 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1754 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1756 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1757 ret = ~0UL;
1759 else
1761 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1762 if (pArena->size == ARENA_LARGE_SIZE)
1764 const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
1765 ret = large_arena->data_size;
1767 else ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1769 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1771 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1772 return ret;
1776 /***********************************************************************
1777 * RtlValidateHeap (NTDLL.@)
1779 * Determine if a block is a valid allocation from a heap.
1781 * PARAMS
1782 * heap [I] Heap that block was allocated from
1783 * flags [I] HEAP_ flags from "winnt.h"
1784 * ptr [I] Block to check
1786 * RETURNS
1787 * Success: TRUE. The block was allocated from heap.
1788 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1790 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1792 HEAP *heapPtr = HEAP_GetPtr( heap );
1793 if (!heapPtr) return FALSE;
1794 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1798 /***********************************************************************
1799 * RtlWalkHeap (NTDLL.@)
1801 * FIXME
1802 * The PROCESS_HEAP_ENTRY flag values seem different between this
1803 * function and HeapWalk(). To be checked.
1805 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1807 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1808 HEAP *heapPtr = HEAP_GetPtr(heap);
1809 SUBHEAP *sub, *currentheap = NULL;
1810 NTSTATUS ret;
1811 char *ptr;
1812 int region_index = 0;
1814 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1816 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1818 /* FIXME: enumerate large blocks too */
1820 /* set ptr to the next arena to be examined */
1822 if (!entry->lpData) /* first call (init) ? */
1824 TRACE("begin walking of heap %p.\n", heap);
1825 currentheap = &heapPtr->subheap;
1826 ptr = (char*)currentheap->base + currentheap->headerSize;
1828 else
1830 ptr = entry->lpData;
1831 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1833 if ((ptr >= (char *)sub->base) &&
1834 (ptr < (char *)sub->base + sub->size))
1836 currentheap = sub;
1837 break;
1839 region_index++;
1841 if (currentheap == NULL)
1843 ERR("no matching subheap found, shouldn't happen !\n");
1844 ret = STATUS_NO_MORE_ENTRIES;
1845 goto HW_end;
1848 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1850 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1851 ptr += pArena->size & ARENA_SIZE_MASK;
1853 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1855 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1856 ptr += pArena->size & ARENA_SIZE_MASK;
1858 else
1859 ptr += entry->cbData; /* point to next arena */
1861 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1862 { /* proceed with next subheap */
1863 struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
1864 if (!next)
1865 { /* successfully finished */
1866 TRACE("end reached.\n");
1867 ret = STATUS_NO_MORE_ENTRIES;
1868 goto HW_end;
1870 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1871 ptr = (char *)currentheap->base + currentheap->headerSize;
1875 entry->wFlags = 0;
1876 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1878 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1880 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1882 entry->lpData = pArena + 1;
1883 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1884 entry->cbOverhead = sizeof(ARENA_FREE);
1885 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1887 else
1889 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1891 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1893 entry->lpData = pArena + 1;
1894 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1895 entry->cbOverhead = sizeof(ARENA_INUSE);
1896 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1897 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1898 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1901 entry->iRegionIndex = region_index;
1903 /* first element of heap ? */
1904 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1906 entry->wFlags |= PROCESS_HEAP_REGION;
1907 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1908 entry->u.Region.dwUnCommittedSize =
1909 currentheap->size - currentheap->commitSize;
1910 entry->u.Region.lpFirstBlock = /* first valid block */
1911 (char *)currentheap->base + currentheap->headerSize;
1912 entry->u.Region.lpLastBlock = /* first invalid block */
1913 (char *)currentheap->base + currentheap->size;
1915 ret = STATUS_SUCCESS;
1916 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1918 HW_end:
1919 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1920 return ret;
1924 /***********************************************************************
1925 * RtlGetProcessHeaps (NTDLL.@)
1927 * Get the Heaps belonging to the current process.
1929 * PARAMS
1930 * count [I] size of heaps
1931 * heaps [O] Destination array for heap HANDLE's
1933 * RETURNS
1934 * Success: The number of Heaps allocated by the process.
1935 * Failure: 0.
1937 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1939 ULONG total = 1; /* main heap */
1940 struct list *ptr;
1942 RtlEnterCriticalSection( &processHeap->critSection );
1943 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1944 if (total <= count)
1946 *heaps++ = processHeap;
1947 LIST_FOR_EACH( ptr, &processHeap->entry )
1948 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1950 RtlLeaveCriticalSection( &processHeap->critSection );
1951 return total;