gdi32: Store the original emf as a sequence of MFCOMMENT records.
[wine/testsucceed.git] / dlls / ntdll / heap.c
blob5466a54a7dc880710329b4f2981216fe1666b82f
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);
47 /* Note: the heap data structures are loosely based on what Pietrek describes in his
48 * book 'Windows 95 System Programming Secrets', with some adaptations for
49 * better compatibility with NT.
52 typedef struct tagARENA_INUSE
54 DWORD size; /* Block size; must be the first field */
55 DWORD magic : 24; /* Magic number */
56 DWORD unused_bytes : 8; /* Number of bytes in the block not used by user data (max value is HEAP_MIN_DATA_SIZE+HEAP_MIN_SHRINK_SIZE) */
57 } ARENA_INUSE;
59 typedef struct tagARENA_FREE
61 DWORD size; /* Block size; must be the first field */
62 DWORD magic; /* Magic number */
63 struct list entry; /* Entry in free list */
64 } ARENA_FREE;
66 typedef struct
68 struct list entry; /* entry in heap large blocks list */
69 SIZE_T data_size; /* size of user data */
70 SIZE_T block_size; /* total size of virtual memory block */
71 DWORD pad[2]; /* padding to ensure 16-byte alignment of data */
72 DWORD size; /* fields for compatibility with normal arenas */
73 DWORD magic; /* these must remain at the end of the structure */
74 } ARENA_LARGE;
76 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
77 #define ARENA_FLAG_PREV_FREE 0x00000002
78 #define ARENA_SIZE_MASK (~3)
79 #define ARENA_LARGE_SIZE 0xfedcba90 /* magic value for 'size' field in large blocks */
81 /* Value for arena 'magic' field */
82 #define ARENA_INUSE_MAGIC 0x455355
83 #define ARENA_FREE_MAGIC 0x45455246
84 #define ARENA_LARGE_MAGIC 0x6752614c
86 #define ARENA_INUSE_FILLER 0x55
87 #define ARENA_FREE_FILLER 0xaa
89 /* everything is aligned on 8 byte boundaries (16 for Win64) */
90 #define ALIGNMENT (2*sizeof(void*))
91 #define LARGE_ALIGNMENT 16 /* large blocks have stricter alignment */
92 #define ARENA_OFFSET (ALIGNMENT - sizeof(ARENA_INUSE))
94 C_ASSERT( sizeof(ARENA_LARGE) % LARGE_ALIGNMENT == 0 );
96 #define ROUND_SIZE(size) ((((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1)) + ARENA_OFFSET)
98 #define QUIET 1 /* Suppress messages */
99 #define NOISY 0 /* Report all errors */
101 /* minimum data size (without arenas) of an allocated block */
102 /* make sure that it's larger than a free list entry */
103 #define HEAP_MIN_DATA_SIZE ROUND_SIZE(2 * sizeof(struct list))
104 /* minimum size that must remain to shrink an allocated block */
105 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
106 /* minimum size to start allocating large blocks */
107 #define HEAP_MIN_LARGE_BLOCK_SIZE 0x7f000
109 /* Max size of the blocks on the free lists */
110 static const SIZE_T HEAP_freeListSizes[] =
112 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
114 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
116 typedef union
118 ARENA_FREE arena;
119 void *alignment[4];
120 } FREE_LIST_ENTRY;
122 struct tagHEAP;
124 typedef struct tagSUBHEAP
126 void *base; /* Base address of the sub-heap memory block */
127 SIZE_T size; /* Size of the whole sub-heap */
128 SIZE_T min_commit; /* Minimum committed size */
129 SIZE_T commitSize; /* Committed size of the sub-heap */
130 struct list entry; /* Entry in sub-heap list */
131 struct tagHEAP *heap; /* Main heap structure */
132 DWORD headerSize; /* Size of the heap header */
133 DWORD magic; /* Magic number */
134 } SUBHEAP;
136 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
138 typedef struct tagHEAP
140 DWORD unknown[3];
141 DWORD flags; /* Heap flags */
142 DWORD force_flags; /* Forced heap flags for debugging */
143 SUBHEAP subheap; /* First sub-heap */
144 struct list entry; /* Entry in process heap list */
145 struct list subheap_list; /* Sub-heap list */
146 struct list large_list; /* Large blocks list */
147 SIZE_T grow_size; /* Size of next subheap for growing heap */
148 DWORD magic; /* Magic number */
149 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
150 FREE_LIST_ENTRY *freeList; /* Free lists */
151 } HEAP;
153 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
155 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
156 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
158 static HEAP *processHeap; /* main process heap */
160 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
162 /* mark a block of memory as free for debugging purposes */
163 static inline void mark_block_free( void *ptr, SIZE_T size )
165 if (TRACE_ON(heap) || WARN_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
166 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
167 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
168 #elif defined( VALGRIND_MAKE_NOACCESS)
169 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
170 #endif
173 /* mark a block of memory as initialized for debugging purposes */
174 static inline void mark_block_initialized( void *ptr, SIZE_T size )
176 #if defined(VALGRIND_MAKE_MEM_DEFINED)
177 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
178 #elif defined(VALGRIND_MAKE_READABLE)
179 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
180 #endif
183 /* mark a block of memory as uninitialized for debugging purposes */
184 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
186 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
187 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
188 #elif defined(VALGRIND_MAKE_WRITABLE)
189 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
190 #endif
191 if (TRACE_ON(heap) || WARN_ON(heap))
193 memset( ptr, ARENA_INUSE_FILLER, size );
194 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
195 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
196 #elif defined(VALGRIND_MAKE_WRITABLE)
197 /* make it uninitialized to valgrind again */
198 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
199 #endif
203 /* clear contents of a block of memory */
204 static inline void clear_block( void *ptr, SIZE_T size )
206 mark_block_initialized( ptr, size );
207 memset( ptr, 0, size );
210 /* notify that a new block of memory has been allocated for debugging purposes */
211 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
213 #ifdef VALGRIND_MALLOCLIKE_BLOCK
214 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
215 #endif
218 /* notify that a block of memory has been freed for debugging purposes */
219 static inline void notify_free( void const *ptr )
221 #ifdef VALGRIND_FREELIKE_BLOCK
222 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
223 #endif
226 static void subheap_notify_free_all(SUBHEAP const *subheap)
228 #ifdef VALGRIND_FREELIKE_BLOCK
229 char const *ptr = (char const *)subheap->base + subheap->headerSize;
231 if (!RUNNING_ON_VALGRIND) return;
233 while (ptr < (char const *)subheap->base + subheap->size)
235 if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
237 ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
238 if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
239 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
241 else
243 ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
244 if (pArena->magic!=ARENA_INUSE_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
245 notify_free(pArena + 1);
246 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
249 #endif
252 /* locate a free list entry of the appropriate size */
253 /* size is the size of the whole block including the arena header */
254 static inline unsigned int get_freelist_index( SIZE_T size )
256 unsigned int i;
258 size -= sizeof(ARENA_FREE);
259 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
260 return i;
263 /* get the memory protection type to use for a given heap */
264 static inline ULONG get_protection_type( DWORD flags )
266 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
269 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
271 0, 0, NULL, /* will be set later */
272 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
273 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
277 /***********************************************************************
278 * HEAP_Dump
280 static void HEAP_Dump( HEAP *heap )
282 unsigned int i;
283 SUBHEAP *subheap;
284 char *ptr;
286 DPRINTF( "Heap: %p\n", heap );
287 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
288 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
290 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
291 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
292 DPRINTF( "%p free %08lx prev=%p next=%p\n",
293 &heap->freeList[i].arena, HEAP_freeListSizes[i],
294 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
295 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
297 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
299 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
300 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
301 subheap, subheap->base, subheap->size, subheap->commitSize );
303 DPRINTF( "\n Block Arena Stat Size Id\n" );
304 ptr = (char *)subheap->base + subheap->headerSize;
305 while (ptr < (char *)subheap->base + subheap->size)
307 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
309 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
310 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
311 pArena, pArena->magic,
312 pArena->size & ARENA_SIZE_MASK,
313 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
314 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
315 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
316 arenaSize += sizeof(ARENA_FREE);
317 freeSize += pArena->size & ARENA_SIZE_MASK;
319 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
321 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
322 DPRINTF( "%p %08x Used %08x back=%p\n",
323 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
324 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
325 arenaSize += sizeof(ARENA_INUSE);
326 usedSize += pArena->size & ARENA_SIZE_MASK;
328 else
330 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
331 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
332 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
333 arenaSize += sizeof(ARENA_INUSE);
334 usedSize += pArena->size & ARENA_SIZE_MASK;
337 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
338 subheap->size, subheap->commitSize, freeSize, usedSize,
339 arenaSize, (arenaSize * 100) / subheap->size );
344 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
346 WORD rem_flags;
347 TRACE( "Dumping entry %p\n", entry );
348 TRACE( "lpData\t\t: %p\n", entry->lpData );
349 TRACE( "cbData\t\t: %08x\n", entry->cbData);
350 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
351 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
352 TRACE( "WFlags\t\t: ");
353 if (entry->wFlags & PROCESS_HEAP_REGION)
354 TRACE( "PROCESS_HEAP_REGION ");
355 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
356 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
357 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
358 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
359 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
360 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
361 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
362 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
363 rem_flags = entry->wFlags &
364 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
365 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
366 PROCESS_HEAP_ENTRY_DDESHARE);
367 if (rem_flags)
368 TRACE( "Unknown %08x", rem_flags);
369 TRACE( "\n");
370 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
371 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
373 /* Treat as block */
374 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
376 if (entry->wFlags & PROCESS_HEAP_REGION)
378 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
379 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
380 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
381 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
385 /***********************************************************************
386 * HEAP_GetPtr
387 * RETURNS
388 * Pointer to the heap
389 * NULL: Failure
391 static HEAP *HEAP_GetPtr(
392 HANDLE heap /* [in] Handle to the heap */
394 HEAP *heapPtr = heap;
395 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
397 ERR("Invalid heap %p!\n", heap );
398 return NULL;
400 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
402 HEAP_Dump( heapPtr );
403 assert( FALSE );
404 return NULL;
406 return heapPtr;
410 /***********************************************************************
411 * HEAP_InsertFreeBlock
413 * Insert a free block into the free list.
415 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
417 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
418 if (last)
420 /* insert at end of free list, i.e. before the next free list entry */
421 pEntry++;
422 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
423 list_add_before( &pEntry->arena.entry, &pArena->entry );
425 else
427 /* insert at head of free list */
428 list_add_after( &pEntry->arena.entry, &pArena->entry );
430 pArena->size |= ARENA_FLAG_FREE;
434 /***********************************************************************
435 * HEAP_FindSubHeap
436 * Find the sub-heap containing a given address.
438 * RETURNS
439 * Pointer: Success
440 * NULL: Failure
442 static SUBHEAP *HEAP_FindSubHeap(
443 const HEAP *heap, /* [in] Heap pointer */
444 LPCVOID ptr ) /* [in] Address */
446 SUBHEAP *sub;
447 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
448 if ((ptr >= sub->base) &&
449 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
450 return sub;
451 return NULL;
455 /***********************************************************************
456 * HEAP_Commit
458 * Make sure the heap storage is committed for a given size in the specified arena.
460 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
462 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
463 SIZE_T size = (char *)ptr - (char *)subheap->base;
464 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
465 if (size > subheap->size) size = subheap->size;
466 if (size <= subheap->commitSize) return TRUE;
467 size -= subheap->commitSize;
468 ptr = (char *)subheap->base + subheap->commitSize;
469 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
470 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
472 WARN("Could not commit %08lx bytes at %p for heap %p\n",
473 size, ptr, subheap->heap );
474 return FALSE;
476 subheap->commitSize += size;
477 return TRUE;
481 /***********************************************************************
482 * HEAP_Decommit
484 * If possible, decommit the heap storage from (including) 'ptr'.
486 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
488 void *addr;
489 SIZE_T decommit_size;
490 SIZE_T size = (char *)ptr - (char *)subheap->base;
492 /* round to next block and add one full block */
493 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
494 size = max( size, subheap->min_commit );
495 if (size >= subheap->commitSize) return TRUE;
496 decommit_size = subheap->commitSize - size;
497 addr = (char *)subheap->base + size;
499 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
501 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
502 decommit_size, (char *)subheap->base + size, subheap->heap );
503 return FALSE;
505 subheap->commitSize -= decommit_size;
506 return TRUE;
510 /***********************************************************************
511 * HEAP_CreateFreeBlock
513 * Create a free block at a specified address. 'size' is the size of the
514 * whole block, including the new arena.
516 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
518 ARENA_FREE *pFree;
519 char *pEnd;
520 BOOL last;
522 /* Create a free arena */
523 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
524 pFree = ptr;
525 pFree->magic = ARENA_FREE_MAGIC;
527 /* If debugging, erase the freed block content */
529 pEnd = (char *)ptr + size;
530 if (pEnd > (char *)subheap->base + subheap->commitSize)
531 pEnd = (char *)subheap->base + subheap->commitSize;
532 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
534 /* Check if next block is free also */
536 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
537 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
539 /* Remove the next arena from the free list */
540 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
541 list_remove( &pNext->entry );
542 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
543 mark_block_free( pNext, sizeof(ARENA_FREE) );
546 /* Set the next block PREV_FREE flag and pointer */
548 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
549 if (!last)
551 DWORD *pNext = (DWORD *)((char *)ptr + size);
552 *pNext |= ARENA_FLAG_PREV_FREE;
553 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
554 *((ARENA_FREE **)pNext - 1) = pFree;
557 /* Last, insert the new block into the free list */
559 pFree->size = size - sizeof(*pFree);
560 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
564 /***********************************************************************
565 * HEAP_MakeInUseBlockFree
567 * Turn an in-use block into a free block. Can also decommit the end of
568 * the heap, and possibly even free the sub-heap altogether.
570 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
572 ARENA_FREE *pFree;
573 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
575 /* Check if we can merge with previous block */
577 if (pArena->size & ARENA_FLAG_PREV_FREE)
579 pFree = *((ARENA_FREE **)pArena - 1);
580 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
581 /* Remove it from the free list */
582 list_remove( &pFree->entry );
584 else pFree = (ARENA_FREE *)pArena;
586 /* Create a free block */
588 HEAP_CreateFreeBlock( subheap, pFree, size );
589 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
590 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
591 return; /* Not the last block, so nothing more to do */
593 /* Free the whole sub-heap if it's empty and not the original one */
595 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
596 (subheap != &subheap->heap->subheap))
598 SIZE_T size = 0;
599 void *addr = subheap->base;
600 /* Remove the free block from the list */
601 list_remove( &pFree->entry );
602 /* Remove the subheap from the list */
603 list_remove( &subheap->entry );
604 /* Free the memory */
605 subheap->magic = 0;
606 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
607 return;
610 /* Decommit the end of the heap */
612 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
616 /***********************************************************************
617 * HEAP_ShrinkBlock
619 * Shrink an in-use block.
621 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
623 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
625 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
626 (pArena->size & ARENA_SIZE_MASK) - size );
627 /* assign size plus previous arena flags */
628 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
630 else
632 /* Turn off PREV_FREE flag in next block */
633 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
634 if (pNext < (char *)subheap->base + subheap->size)
635 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
640 /***********************************************************************
641 * allocate_large_block
643 static void *allocate_large_block( HEAP *heap, DWORD flags, SIZE_T size )
645 ARENA_LARGE *arena;
646 SIZE_T block_size = sizeof(*arena) + ROUND_SIZE(size);
647 LPVOID address = NULL;
649 if (block_size < size) return NULL; /* overflow */
650 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
651 &block_size, MEM_COMMIT, get_protection_type( flags ) ))
653 WARN("Could not allocate block for %08lx bytes\n", size );
654 return NULL;
656 arena = address;
657 arena->data_size = size;
658 arena->block_size = block_size;
659 arena->size = ARENA_LARGE_SIZE;
660 arena->magic = ARENA_LARGE_MAGIC;
661 list_add_tail( &heap->large_list, &arena->entry );
662 return arena + 1;
666 /***********************************************************************
667 * free_large_block
669 static void free_large_block( HEAP *heap, DWORD flags, void *ptr )
671 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
672 LPVOID address = arena;
673 SIZE_T size = 0;
675 list_remove( &arena->entry );
676 NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
680 /***********************************************************************
681 * realloc_large_block
683 static void *realloc_large_block( HEAP *heap, DWORD flags, void *ptr, SIZE_T size )
685 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
686 void *new_ptr;
688 if (arena->block_size - sizeof(*arena) >= size)
690 /* FIXME: we could remap zero-pages instead */
691 if ((flags & HEAP_ZERO_MEMORY) && size > arena->data_size)
692 memset( (char *)ptr + arena->data_size, 0, size - arena->data_size );
693 arena->data_size = size;
694 return ptr;
696 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) return NULL;
697 if (!(new_ptr = allocate_large_block( heap, flags, size )))
699 WARN("Could not allocate block for %08lx bytes\n", size );
700 return NULL;
702 memcpy( new_ptr, ptr, arena->data_size );
703 free_large_block( heap, flags, ptr );
704 return new_ptr;
708 /***********************************************************************
709 * find_large_block
711 static ARENA_LARGE *find_large_block( HEAP *heap, const void *ptr )
713 ARENA_LARGE *arena;
715 LIST_FOR_EACH_ENTRY( arena, &heap->large_list, ARENA_LARGE, entry )
716 if (ptr == arena + 1) return arena;
718 return NULL;
722 /***********************************************************************
723 * validate_large_arena
725 static BOOL validate_large_arena( HEAP *heap, const ARENA_LARGE *arena, BOOL quiet )
727 if ((ULONG_PTR)arena % getpagesize())
729 if (quiet == NOISY)
731 ERR( "Heap %p: invalid large arena pointer %p\n", heap, arena );
732 if (TRACE_ON(heap)) HEAP_Dump( heap );
734 else if (WARN_ON(heap))
736 WARN( "Heap %p: unaligned arena pointer %p\n", heap, arena );
737 if (TRACE_ON(heap)) HEAP_Dump( heap );
739 return FALSE;
741 if (arena->size != ARENA_LARGE_SIZE || arena->magic != ARENA_LARGE_MAGIC)
743 if (quiet == NOISY)
745 ERR( "Heap %p: invalid large arena %p values %x/%x\n",
746 heap, arena, arena->size, arena->magic );
747 if (TRACE_ON(heap)) HEAP_Dump( heap );
749 else if (WARN_ON(heap))
751 WARN( "Heap %p: invalid large arena %p values %x/%x\n",
752 heap, arena, arena->size, arena->magic );
753 if (TRACE_ON(heap)) HEAP_Dump( heap );
755 return FALSE;
757 return TRUE;
761 /***********************************************************************
762 * HEAP_CreateSubHeap
764 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, LPVOID address, DWORD flags,
765 SIZE_T commitSize, SIZE_T totalSize )
767 SUBHEAP *subheap;
768 FREE_LIST_ENTRY *pEntry;
769 unsigned int i;
771 if (!address)
773 /* round-up sizes on a 64K boundary */
774 totalSize = (totalSize + 0xffff) & 0xffff0000;
775 commitSize = (commitSize + 0xffff) & 0xffff0000;
776 if (!commitSize) commitSize = 0x10000;
777 totalSize = min( totalSize, 0xffff0000 ); /* don't allow a heap larger than 4Gb */
778 if (totalSize < commitSize) totalSize = commitSize;
779 if (flags & HEAP_SHARED) commitSize = totalSize; /* always commit everything in a shared heap */
781 /* allocate the memory block */
782 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
783 MEM_RESERVE, get_protection_type( flags ) ))
785 WARN("Could not allocate %08lx bytes\n", totalSize );
786 return NULL;
788 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
789 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
791 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
792 return NULL;
796 if (heap)
798 /* If this is a secondary subheap, insert it into list */
800 subheap = address;
801 subheap->base = address;
802 subheap->heap = heap;
803 subheap->size = totalSize;
804 subheap->min_commit = 0x10000;
805 subheap->commitSize = commitSize;
806 subheap->magic = SUBHEAP_MAGIC;
807 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
808 list_add_head( &heap->subheap_list, &subheap->entry );
810 else
812 /* If this is a primary subheap, initialize main heap */
814 heap = address;
815 heap->flags = flags;
816 heap->magic = HEAP_MAGIC;
817 heap->grow_size = max( HEAP_DEF_SIZE, totalSize );
818 list_init( &heap->subheap_list );
819 list_init( &heap->large_list );
821 subheap = &heap->subheap;
822 subheap->base = address;
823 subheap->heap = heap;
824 subheap->size = totalSize;
825 subheap->min_commit = commitSize;
826 subheap->commitSize = commitSize;
827 subheap->magic = SUBHEAP_MAGIC;
828 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
829 list_add_head( &heap->subheap_list, &subheap->entry );
831 /* Build the free lists */
833 heap->freeList = (FREE_LIST_ENTRY *)((char *)heap + subheap->headerSize);
834 subheap->headerSize += HEAP_NB_FREE_LISTS * sizeof(FREE_LIST_ENTRY);
835 list_init( &heap->freeList[0].arena.entry );
836 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
838 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
839 pEntry->arena.magic = ARENA_FREE_MAGIC;
840 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
843 /* Initialize critical section */
845 if (!processHeap) /* do it by hand to avoid memory allocations */
847 heap->critSection.DebugInfo = &process_heap_critsect_debug;
848 heap->critSection.LockCount = -1;
849 heap->critSection.RecursionCount = 0;
850 heap->critSection.OwningThread = 0;
851 heap->critSection.LockSemaphore = 0;
852 heap->critSection.SpinCount = 0;
853 process_heap_critsect_debug.CriticalSection = &heap->critSection;
855 else
857 RtlInitializeCriticalSection( &heap->critSection );
858 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
861 if (flags & HEAP_SHARED)
863 /* let's assume that only one thread at a time will try to do this */
864 HANDLE sem = heap->critSection.LockSemaphore;
865 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
867 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
868 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
869 heap->critSection.LockSemaphore = sem;
870 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
871 heap->critSection.DebugInfo = NULL;
875 /* Create the first free block */
877 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
878 subheap->size - subheap->headerSize );
880 return subheap;
884 /***********************************************************************
885 * HEAP_FindFreeBlock
887 * Find a free block at least as large as the requested size, and make sure
888 * the requested size is committed.
890 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
891 SUBHEAP **ppSubHeap )
893 SUBHEAP *subheap;
894 struct list *ptr;
895 SIZE_T total_size;
896 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
898 /* Find a suitable free list, and in it find a block large enough */
900 ptr = &pEntry->arena.entry;
901 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
903 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
904 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
905 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
906 if (arena_size >= size)
908 subheap = HEAP_FindSubHeap( heap, pArena );
909 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
910 *ppSubHeap = subheap;
911 return pArena;
915 /* If no block was found, attempt to grow the heap */
917 if (!(heap->flags & HEAP_GROWABLE))
919 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
920 return NULL;
922 /* make sure that we have a big enough size *committed* to fit another
923 * last free arena in !
924 * So just one heap struct, one first free arena which will eventually
925 * get used, and a second free arena that might get assigned all remaining
926 * free space in HEAP_ShrinkBlock() */
927 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
928 if (total_size < size) return NULL; /* overflow */
930 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
931 max( heap->grow_size, total_size ) )))
932 return NULL;
934 if (heap->grow_size < 128 * 1024 * 1024) heap->grow_size *= 2;
936 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
937 subheap, subheap->size, heap );
939 *ppSubHeap = subheap;
940 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
944 /***********************************************************************
945 * HEAP_IsValidArenaPtr
947 * Check that the pointer is inside the range possible for arenas.
949 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
951 unsigned int i;
952 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
953 if (!subheap) return FALSE;
954 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
955 if (subheap != &heap->subheap) return FALSE;
956 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
957 if (ptr == &heap->freeList[i].arena) return TRUE;
958 return FALSE;
962 /***********************************************************************
963 * HEAP_ValidateFreeArena
965 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
967 ARENA_FREE *prev, *next;
968 char *heapEnd = (char *)subheap->base + subheap->size;
970 /* Check for unaligned pointers */
971 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
973 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
974 return FALSE;
977 /* Check magic number */
978 if (pArena->magic != ARENA_FREE_MAGIC)
980 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
981 return FALSE;
983 /* Check size flags */
984 if (!(pArena->size & ARENA_FLAG_FREE) ||
985 (pArena->size & ARENA_FLAG_PREV_FREE))
987 ERR("Heap %p: bad flags %08x for free arena %p\n",
988 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
989 return FALSE;
991 /* Check arena size */
992 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
994 ERR("Heap %p: bad size %08x for free arena %p\n",
995 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
996 return FALSE;
998 /* Check that next pointer is valid */
999 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
1000 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
1002 ERR("Heap %p: bad next ptr %p for arena %p\n",
1003 subheap->heap, next, pArena );
1004 return FALSE;
1006 /* Check that next arena is free */
1007 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1009 ERR("Heap %p: next arena %p invalid for %p\n",
1010 subheap->heap, next, pArena );
1011 return FALSE;
1013 /* Check that prev pointer is valid */
1014 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1015 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1017 ERR("Heap %p: bad prev ptr %p for arena %p\n",
1018 subheap->heap, prev, pArena );
1019 return FALSE;
1021 /* Check that prev arena is free */
1022 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1024 /* this often means that the prev arena got overwritten
1025 * by a memory write before that prev arena */
1026 ERR("Heap %p: prev arena %p invalid for %p\n",
1027 subheap->heap, prev, pArena );
1028 return FALSE;
1030 /* Check that next block has PREV_FREE flag */
1031 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
1033 if (!(*(DWORD *)((char *)(pArena + 1) +
1034 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1036 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1037 subheap->heap, pArena );
1038 return FALSE;
1040 /* Check next block back pointer */
1041 if (*((ARENA_FREE **)((char *)(pArena + 1) +
1042 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
1044 ERR("Heap %p: arena %p has wrong back ptr %p\n",
1045 subheap->heap, pArena,
1046 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
1047 return FALSE;
1050 return TRUE;
1054 /***********************************************************************
1055 * HEAP_ValidateInUseArena
1057 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1059 const char *heapEnd = (const char *)subheap->base + subheap->size;
1061 /* Check for unaligned pointers */
1062 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1064 if ( quiet == NOISY )
1066 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1067 if ( TRACE_ON(heap) )
1068 HEAP_Dump( subheap->heap );
1070 else if ( WARN_ON(heap) )
1072 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1073 if ( TRACE_ON(heap) )
1074 HEAP_Dump( subheap->heap );
1076 return FALSE;
1079 /* Check magic number */
1080 if (pArena->magic != ARENA_INUSE_MAGIC)
1082 if (quiet == NOISY) {
1083 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1084 if (TRACE_ON(heap))
1085 HEAP_Dump( subheap->heap );
1086 } else if (WARN_ON(heap)) {
1087 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1088 if (TRACE_ON(heap))
1089 HEAP_Dump( subheap->heap );
1091 return FALSE;
1093 /* Check size flags */
1094 if (pArena->size & ARENA_FLAG_FREE)
1096 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1097 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1098 return FALSE;
1100 /* Check arena size */
1101 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
1103 ERR("Heap %p: bad size %08x for in-use arena %p\n",
1104 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
1105 return FALSE;
1107 /* Check next arena PREV_FREE flag */
1108 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
1109 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1111 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
1112 subheap->heap, pArena );
1113 return FALSE;
1115 /* Check prev free arena */
1116 if (pArena->size & ARENA_FLAG_PREV_FREE)
1118 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1119 /* Check prev pointer */
1120 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1122 ERR("Heap %p: bad back ptr %p for arena %p\n",
1123 subheap->heap, pPrev, pArena );
1124 return FALSE;
1126 /* Check that prev arena is free */
1127 if (!(pPrev->size & ARENA_FLAG_FREE) ||
1128 (pPrev->magic != ARENA_FREE_MAGIC))
1130 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1131 subheap->heap, pPrev, pArena );
1132 return FALSE;
1134 /* Check that prev arena is really the previous block */
1135 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1137 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1138 subheap->heap, pPrev, pArena );
1139 return FALSE;
1142 return TRUE;
1146 /***********************************************************************
1147 * HEAP_IsRealArena [Internal]
1148 * Validates a block is a valid arena.
1150 * RETURNS
1151 * TRUE: Success
1152 * FALSE: Failure
1154 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1155 DWORD flags, /* [in] Bit flags that control access during operation */
1156 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1157 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1158 * does not complain */
1160 SUBHEAP *subheap;
1161 BOOL ret = TRUE;
1162 const ARENA_LARGE *large_arena;
1164 flags &= HEAP_NO_SERIALIZE;
1165 flags |= heapPtr->flags;
1166 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1167 if (!(flags & HEAP_NO_SERIALIZE))
1168 RtlEnterCriticalSection( &heapPtr->critSection );
1170 if (block) /* only check this single memory block */
1172 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1174 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1175 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1177 if (!(large_arena = find_large_block( heapPtr, block )))
1179 if (quiet == NOISY)
1180 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1181 else if (WARN_ON(heap))
1182 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1183 ret = FALSE;
1185 else
1186 ret = validate_large_arena( heapPtr, large_arena, quiet );
1187 } else
1188 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1190 if (!(flags & HEAP_NO_SERIALIZE))
1191 RtlLeaveCriticalSection( &heapPtr->critSection );
1192 return ret;
1195 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1197 char *ptr = (char *)subheap->base + subheap->headerSize;
1198 while (ptr < (char *)subheap->base + subheap->size)
1200 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1202 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1203 ret = FALSE;
1204 break;
1206 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1208 else
1210 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1211 ret = FALSE;
1212 break;
1214 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1217 if (!ret) break;
1220 LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1221 if (!(ret = validate_large_arena( heapPtr, large_arena, quiet ))) break;
1223 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1224 return ret;
1228 /***********************************************************************
1229 * RtlCreateHeap (NTDLL.@)
1231 * Create a new Heap.
1233 * PARAMS
1234 * flags [I] HEAP_ flags from "winnt.h"
1235 * addr [I] Desired base address
1236 * totalSize [I] Total size of the heap, or 0 for a growable heap
1237 * commitSize [I] Amount of heap space to commit
1238 * unknown [I] Not yet understood
1239 * definition [I] Heap definition
1241 * RETURNS
1242 * Success: A HANDLE to the newly created heap.
1243 * Failure: a NULL HANDLE.
1245 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1246 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1248 SUBHEAP *subheap;
1250 /* Allocate the heap block */
1252 if (!totalSize)
1254 totalSize = HEAP_DEF_SIZE;
1255 flags |= HEAP_GROWABLE;
1258 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1260 /* link it into the per-process heap list */
1261 if (processHeap)
1263 HEAP *heapPtr = subheap->heap;
1264 RtlEnterCriticalSection( &processHeap->critSection );
1265 list_add_head( &processHeap->entry, &heapPtr->entry );
1266 RtlLeaveCriticalSection( &processHeap->critSection );
1268 else if (!addr)
1270 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1271 list_init( &processHeap->entry );
1274 return subheap->heap;
1278 /***********************************************************************
1279 * RtlDestroyHeap (NTDLL.@)
1281 * Destroy a Heap created with RtlCreateHeap().
1283 * PARAMS
1284 * heap [I] Heap to destroy.
1286 * RETURNS
1287 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1288 * Failure: The Heap handle, if heap is the process heap.
1290 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1292 HEAP *heapPtr = HEAP_GetPtr( heap );
1293 SUBHEAP *subheap, *next;
1294 ARENA_LARGE *arena, *arena_next;
1295 SIZE_T size;
1296 void *addr;
1298 TRACE("%p\n", heap );
1299 if (!heapPtr) return heap;
1301 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1303 /* remove it from the per-process list */
1304 RtlEnterCriticalSection( &processHeap->critSection );
1305 list_remove( &heapPtr->entry );
1306 RtlLeaveCriticalSection( &processHeap->critSection );
1308 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1309 RtlDeleteCriticalSection( &heapPtr->critSection );
1311 LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1313 list_remove( &arena->entry );
1314 size = 0;
1315 addr = arena;
1316 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1318 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1320 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1321 subheap_notify_free_all(subheap);
1322 list_remove( &subheap->entry );
1323 size = 0;
1324 addr = subheap->base;
1325 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1327 subheap_notify_free_all(&heapPtr->subheap);
1328 size = 0;
1329 addr = heapPtr->subheap.base;
1330 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1331 return 0;
1335 /***********************************************************************
1336 * RtlAllocateHeap (NTDLL.@)
1338 * Allocate a memory block from a Heap.
1340 * PARAMS
1341 * heap [I] Heap to allocate block from
1342 * flags [I] HEAP_ flags from "winnt.h"
1343 * size [I] Size of the memory block to allocate
1345 * RETURNS
1346 * Success: A pointer to the newly allocated block
1347 * Failure: NULL.
1349 * NOTES
1350 * This call does not SetLastError().
1352 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1354 ARENA_FREE *pArena;
1355 ARENA_INUSE *pInUse;
1356 SUBHEAP *subheap;
1357 HEAP *heapPtr = HEAP_GetPtr( heap );
1358 SIZE_T rounded_size;
1360 /* Validate the parameters */
1362 if (!heapPtr) return NULL;
1363 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1364 flags |= heapPtr->flags;
1365 rounded_size = ROUND_SIZE(size);
1366 if (rounded_size < size) /* overflow */
1368 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1369 return NULL;
1371 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1373 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1375 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1377 void *ret = allocate_large_block( heap, flags, size );
1378 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1379 if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1380 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1381 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1382 return ret;
1385 /* Locate a suitable free block */
1387 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1389 TRACE("(%p,%08x,%08lx): returning NULL\n",
1390 heap, flags, size );
1391 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1392 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1393 return NULL;
1396 /* Remove the arena from the free list */
1398 list_remove( &pArena->entry );
1400 /* Build the in-use arena */
1402 pInUse = (ARENA_INUSE *)pArena;
1404 /* in-use arena is smaller than free arena,
1405 * so we have to add the difference to the size */
1406 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1407 pInUse->magic = ARENA_INUSE_MAGIC;
1409 /* Shrink the block */
1411 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1412 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1414 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1416 if (flags & HEAP_ZERO_MEMORY)
1418 clear_block( pInUse + 1, size );
1419 mark_block_uninitialized( (char *)(pInUse + 1) + size, pInUse->unused_bytes );
1421 else
1422 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1424 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1426 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1427 return pInUse + 1;
1431 /***********************************************************************
1432 * RtlFreeHeap (NTDLL.@)
1434 * Free a memory block allocated with RtlAllocateHeap().
1436 * PARAMS
1437 * heap [I] Heap that block was allocated from
1438 * flags [I] HEAP_ flags from "winnt.h"
1439 * ptr [I] Block to free
1441 * RETURNS
1442 * Success: TRUE, if ptr is NULL or was freed successfully.
1443 * Failure: FALSE.
1445 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1447 ARENA_INUSE *pInUse;
1448 SUBHEAP *subheap;
1449 HEAP *heapPtr;
1451 /* Validate the parameters */
1453 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1455 heapPtr = HEAP_GetPtr( heap );
1456 if (!heapPtr)
1458 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1459 return FALSE;
1462 flags &= HEAP_NO_SERIALIZE;
1463 flags |= heapPtr->flags;
1464 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1466 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1467 notify_free( ptr );
1469 /* Some sanity checks */
1470 pInUse = (ARENA_INUSE *)ptr - 1;
1471 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse )))
1473 if (!find_large_block( heapPtr, ptr )) goto error;
1474 free_large_block( heapPtr, flags, ptr );
1475 goto done;
1477 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1478 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1480 /* Turn the block into a free block */
1482 HEAP_MakeInUseBlockFree( subheap, pInUse );
1484 done:
1485 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1486 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1487 return TRUE;
1489 error:
1490 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1491 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1492 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1493 return FALSE;
1497 /***********************************************************************
1498 * RtlReAllocateHeap (NTDLL.@)
1500 * Change the size of a memory block allocated with RtlAllocateHeap().
1502 * PARAMS
1503 * heap [I] Heap that block was allocated from
1504 * flags [I] HEAP_ flags from "winnt.h"
1505 * ptr [I] Block to resize
1506 * size [I] Size of the memory block to allocate
1508 * RETURNS
1509 * Success: A pointer to the resized block (which may be different).
1510 * Failure: NULL.
1512 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1514 ARENA_INUSE *pArena;
1515 HEAP *heapPtr;
1516 SUBHEAP *subheap;
1517 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1518 void *ret;
1520 if (!ptr) return NULL;
1521 if (!(heapPtr = HEAP_GetPtr( heap )))
1523 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1524 return NULL;
1527 /* Validate the parameters */
1529 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1530 HEAP_REALLOC_IN_PLACE_ONLY;
1531 flags |= heapPtr->flags;
1532 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1534 rounded_size = ROUND_SIZE(size);
1535 if (rounded_size < size) goto oom; /* overflow */
1536 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1538 pArena = (ARENA_INUSE *)ptr - 1;
1539 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena )))
1541 if (!find_large_block( heapPtr, ptr )) goto error;
1542 if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1543 notify_free( ptr );
1544 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1545 goto done;
1547 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1548 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1550 /* Check if we need to grow the block */
1552 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1553 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1554 if (rounded_size > oldBlockSize)
1556 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1558 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1560 if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1561 notify_alloc( ret, size, flags & HEAP_ZERO_MEMORY );
1562 memcpy( ret, pArena + 1, oldActualSize );
1563 notify_free( pArena + 1 );
1564 HEAP_MakeInUseBlockFree( subheap, pArena );
1565 goto done;
1567 if ((pNext < (char *)subheap->base + subheap->size) &&
1568 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1569 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1571 /* The next block is free and large enough */
1572 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1573 list_remove( &pFree->entry );
1574 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1575 if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1576 notify_free( pArena + 1 );
1577 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1578 notify_alloc( pArena + 1, size, FALSE );
1579 /* FIXME: this is wrong as we may lose old VBits settings */
1580 mark_block_initialized( pArena + 1, oldActualSize );
1582 else /* Do it the hard way */
1584 ARENA_FREE *pNew;
1585 ARENA_INUSE *pInUse;
1586 SUBHEAP *newsubheap;
1588 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1589 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1590 goto oom;
1592 /* Build the in-use arena */
1594 list_remove( &pNew->entry );
1595 pInUse = (ARENA_INUSE *)pNew;
1596 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1597 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1598 pInUse->magic = ARENA_INUSE_MAGIC;
1599 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1601 mark_block_initialized( pInUse + 1, oldActualSize );
1602 notify_alloc( pInUse + 1, size, FALSE );
1603 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1605 /* Free the previous block */
1607 notify_free( pArena + 1 );
1608 HEAP_MakeInUseBlockFree( subheap, pArena );
1609 subheap = newsubheap;
1610 pArena = pInUse;
1613 else
1615 /* Shrink the block */
1616 notify_free( pArena + 1 );
1617 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1618 notify_alloc( pArena + 1, size, FALSE );
1619 /* FIXME: this is wrong as we may lose old VBits settings */
1620 mark_block_initialized( pArena + 1, size );
1623 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1625 /* Clear the extra bytes if needed */
1627 if (size > oldActualSize)
1629 if (flags & HEAP_ZERO_MEMORY)
1631 clear_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize );
1632 mark_block_uninitialized( (char *)(pArena + 1) + size, pArena->unused_bytes );
1634 else
1635 mark_block_uninitialized( (char *)(pArena + 1) + oldActualSize,
1636 (pArena->size & ARENA_SIZE_MASK) - oldActualSize );
1639 /* Return the new arena */
1641 ret = pArena + 1;
1642 done:
1643 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1644 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1645 return ret;
1647 oom:
1648 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1649 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1650 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1651 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1652 return NULL;
1654 error:
1655 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1656 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1657 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1658 return NULL;
1662 /***********************************************************************
1663 * RtlCompactHeap (NTDLL.@)
1665 * Compact the free space in a Heap.
1667 * PARAMS
1668 * heap [I] Heap that block was allocated from
1669 * flags [I] HEAP_ flags from "winnt.h"
1671 * RETURNS
1672 * The number of bytes compacted.
1674 * NOTES
1675 * This function is a harmless stub.
1677 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1679 static BOOL reported;
1680 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1681 return 0;
1685 /***********************************************************************
1686 * RtlLockHeap (NTDLL.@)
1688 * Lock a Heap.
1690 * PARAMS
1691 * heap [I] Heap to lock
1693 * RETURNS
1694 * Success: TRUE. The Heap is locked.
1695 * Failure: FALSE, if heap is invalid.
1697 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1699 HEAP *heapPtr = HEAP_GetPtr( heap );
1700 if (!heapPtr) return FALSE;
1701 RtlEnterCriticalSection( &heapPtr->critSection );
1702 return TRUE;
1706 /***********************************************************************
1707 * RtlUnlockHeap (NTDLL.@)
1709 * Unlock a Heap.
1711 * PARAMS
1712 * heap [I] Heap to unlock
1714 * RETURNS
1715 * Success: TRUE. The Heap is unlocked.
1716 * Failure: FALSE, if heap is invalid.
1718 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1720 HEAP *heapPtr = HEAP_GetPtr( heap );
1721 if (!heapPtr) return FALSE;
1722 RtlLeaveCriticalSection( &heapPtr->critSection );
1723 return TRUE;
1727 /***********************************************************************
1728 * RtlSizeHeap (NTDLL.@)
1730 * Get the actual size of a memory block allocated from a Heap.
1732 * PARAMS
1733 * heap [I] Heap that block was allocated from
1734 * flags [I] HEAP_ flags from "winnt.h"
1735 * ptr [I] Block to get the size of
1737 * RETURNS
1738 * Success: The size of the block.
1739 * Failure: -1, heap or ptr are invalid.
1741 * NOTES
1742 * The size may be bigger than what was passed to RtlAllocateHeap().
1744 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1746 SIZE_T ret;
1747 HEAP *heapPtr = HEAP_GetPtr( heap );
1749 if (!heapPtr)
1751 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1752 return ~0UL;
1754 flags &= HEAP_NO_SERIALIZE;
1755 flags |= heapPtr->flags;
1756 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1757 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1759 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1760 ret = ~0UL;
1762 else
1764 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1765 if (pArena->size == ARENA_LARGE_SIZE)
1767 const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
1768 ret = large_arena->data_size;
1770 else ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1772 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1774 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1775 return ret;
1779 /***********************************************************************
1780 * RtlValidateHeap (NTDLL.@)
1782 * Determine if a block is a valid allocation from a heap.
1784 * PARAMS
1785 * heap [I] Heap that block was allocated from
1786 * flags [I] HEAP_ flags from "winnt.h"
1787 * ptr [I] Block to check
1789 * RETURNS
1790 * Success: TRUE. The block was allocated from heap.
1791 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1793 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1795 HEAP *heapPtr = HEAP_GetPtr( heap );
1796 if (!heapPtr) return FALSE;
1797 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1801 /***********************************************************************
1802 * RtlWalkHeap (NTDLL.@)
1804 * FIXME
1805 * The PROCESS_HEAP_ENTRY flag values seem different between this
1806 * function and HeapWalk(). To be checked.
1808 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1810 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1811 HEAP *heapPtr = HEAP_GetPtr(heap);
1812 SUBHEAP *sub, *currentheap = NULL;
1813 NTSTATUS ret;
1814 char *ptr;
1815 int region_index = 0;
1817 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1819 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1821 /* FIXME: enumerate large blocks too */
1823 /* set ptr to the next arena to be examined */
1825 if (!entry->lpData) /* first call (init) ? */
1827 TRACE("begin walking of heap %p.\n", heap);
1828 currentheap = &heapPtr->subheap;
1829 ptr = (char*)currentheap->base + currentheap->headerSize;
1831 else
1833 ptr = entry->lpData;
1834 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1836 if ((ptr >= (char *)sub->base) &&
1837 (ptr < (char *)sub->base + sub->size))
1839 currentheap = sub;
1840 break;
1842 region_index++;
1844 if (currentheap == NULL)
1846 ERR("no matching subheap found, shouldn't happen !\n");
1847 ret = STATUS_NO_MORE_ENTRIES;
1848 goto HW_end;
1851 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1853 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1854 ptr += pArena->size & ARENA_SIZE_MASK;
1856 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1858 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1859 ptr += pArena->size & ARENA_SIZE_MASK;
1861 else
1862 ptr += entry->cbData; /* point to next arena */
1864 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1865 { /* proceed with next subheap */
1866 struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
1867 if (!next)
1868 { /* successfully finished */
1869 TRACE("end reached.\n");
1870 ret = STATUS_NO_MORE_ENTRIES;
1871 goto HW_end;
1873 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1874 ptr = (char *)currentheap->base + currentheap->headerSize;
1878 entry->wFlags = 0;
1879 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1881 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1883 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1885 entry->lpData = pArena + 1;
1886 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1887 entry->cbOverhead = sizeof(ARENA_FREE);
1888 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1890 else
1892 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1894 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1896 entry->lpData = pArena + 1;
1897 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1898 entry->cbOverhead = sizeof(ARENA_INUSE);
1899 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1900 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1901 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1904 entry->iRegionIndex = region_index;
1906 /* first element of heap ? */
1907 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1909 entry->wFlags |= PROCESS_HEAP_REGION;
1910 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1911 entry->u.Region.dwUnCommittedSize =
1912 currentheap->size - currentheap->commitSize;
1913 entry->u.Region.lpFirstBlock = /* first valid block */
1914 (char *)currentheap->base + currentheap->headerSize;
1915 entry->u.Region.lpLastBlock = /* first invalid block */
1916 (char *)currentheap->base + currentheap->size;
1918 ret = STATUS_SUCCESS;
1919 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1921 HW_end:
1922 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1923 return ret;
1927 /***********************************************************************
1928 * RtlGetProcessHeaps (NTDLL.@)
1930 * Get the Heaps belonging to the current process.
1932 * PARAMS
1933 * count [I] size of heaps
1934 * heaps [O] Destination array for heap HANDLE's
1936 * RETURNS
1937 * Success: The number of Heaps allocated by the process.
1938 * Failure: 0.
1940 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1942 ULONG total = 1; /* main heap */
1943 struct list *ptr;
1945 RtlEnterCriticalSection( &processHeap->critSection );
1946 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1947 if (total <= count)
1949 *heaps++ = processHeap;
1950 LIST_FOR_EACH( ptr, &processHeap->entry )
1951 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1953 RtlLeaveCriticalSection( &processHeap->critSection );
1954 return total;