push 9eb9af089d68d39110a91889d3a673043db63c4b
[wine/hacks.git] / dlls / ntdll / heap.c
blobcdd1f70ea892362060774fe76af59f1a41f37d48
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 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
54 * that there is no unaligned accesses to structure fields.
57 typedef struct tagARENA_INUSE
59 DWORD size; /* Block size; must be the first field */
60 DWORD magic : 24; /* Magic number */
61 DWORD unused_bytes : 8; /* Number of bytes in the block not used by user data (max value is HEAP_MIN_DATA_SIZE+HEAP_MIN_SHRINK_SIZE) */
62 } ARENA_INUSE;
64 typedef struct tagARENA_FREE
66 DWORD size; /* Block size; must be the first field */
67 DWORD magic; /* Magic number */
68 struct list entry; /* Entry in free list */
69 } ARENA_FREE;
71 typedef struct
73 struct list entry; /* entry in heap large blocks list */
74 SIZE_T data_size; /* size of user data */
75 SIZE_T block_size; /* total size of virtual memory block */
76 DWORD pad[2]; /* padding to ensure 16-byte alignment of data */
77 DWORD size; /* fields for compatibility with normal arenas */
78 DWORD magic; /* these must remain at the end of the structure */
79 } ARENA_LARGE;
81 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
82 #define ARENA_FLAG_PREV_FREE 0x00000002
83 #define ARENA_SIZE_MASK (~3)
84 #define ARENA_LARGE_SIZE 0xfedcba90 /* magic value for 'size' field in large blocks */
86 /* Value for arena 'magic' field */
87 #define ARENA_INUSE_MAGIC 0x455355
88 #define ARENA_FREE_MAGIC 0x45455246
89 #define ARENA_LARGE_MAGIC 0x6752614c
91 #define ARENA_INUSE_FILLER 0x55
92 #define ARENA_FREE_FILLER 0xaa
94 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
95 #define LARGE_ALIGNMENT 16 /* large blocks have stricter alignment */
97 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
99 #define QUIET 1 /* Suppress messages */
100 #define NOISY 0 /* Report all errors */
102 /* minimum data size (without arenas) of an allocated block */
103 /* make sure that it's larger than a free list entry */
104 #define HEAP_MIN_DATA_SIZE (2 * sizeof(struct list))
105 /* minimum size that must remain to shrink an allocated block */
106 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
107 /* minimum size to start allocating large blocks */
108 #define HEAP_MIN_LARGE_BLOCK_SIZE 0x7f000
110 /* Max size of the blocks on the free lists */
111 static const SIZE_T HEAP_freeListSizes[] =
113 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
115 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
117 typedef struct
119 ARENA_FREE arena;
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 commitSize; /* Committed size of the sub-heap */
129 struct list entry; /* Entry in sub-heap list */
130 struct tagHEAP *heap; /* Main heap structure */
131 DWORD headerSize; /* Size of the heap header */
132 DWORD magic; /* Magic number */
133 } SUBHEAP;
135 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
137 typedef struct tagHEAP
139 DWORD unknown[3];
140 DWORD flags; /* Heap flags */
141 DWORD force_flags; /* Forced heap flags for debugging */
142 SUBHEAP subheap; /* First sub-heap */
143 struct list entry; /* Entry in process heap list */
144 struct list subheap_list; /* Sub-heap list */
145 struct list large_list; /* Large blocks list */
146 DWORD magic; /* Magic number */
147 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
148 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* 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 *)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 (((const char *)ptr >= (const char *)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 = (ARENA_FREE *)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 == (const void *)(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 if (totalSize < commitSize) totalSize = commitSize;
775 if (flags & HEAP_SHARED) commitSize = totalSize; /* always commit everything in a shared heap */
777 /* allocate the memory block */
778 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
779 MEM_RESERVE, get_protection_type( flags ) ))
781 WARN("Could not allocate %08lx bytes\n", totalSize );
782 return NULL;
784 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
785 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
787 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
788 return NULL;
792 if (heap)
794 /* If this is a secondary subheap, insert it into list */
796 subheap = (SUBHEAP *)address;
797 subheap->base = address;
798 subheap->heap = heap;
799 subheap->size = totalSize;
800 subheap->commitSize = commitSize;
801 subheap->magic = SUBHEAP_MAGIC;
802 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
803 list_add_head( &heap->subheap_list, &subheap->entry );
805 else
807 /* If this is a primary subheap, initialize main heap */
809 heap = (HEAP *)address;
810 heap->flags = flags;
811 heap->magic = HEAP_MAGIC;
812 list_init( &heap->subheap_list );
813 list_init( &heap->large_list );
815 subheap = &heap->subheap;
816 subheap->base = address;
817 subheap->heap = heap;
818 subheap->size = totalSize;
819 subheap->commitSize = commitSize;
820 subheap->magic = SUBHEAP_MAGIC;
821 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
822 list_add_head( &heap->subheap_list, &subheap->entry );
824 /* Build the free lists */
826 list_init( &heap->freeList[0].arena.entry );
827 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
829 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
830 pEntry->arena.magic = ARENA_FREE_MAGIC;
831 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
834 /* Initialize critical section */
836 if (!processHeap) /* do it by hand to avoid memory allocations */
838 if(TRACE_ON(heap_poison))
839 TRACE_(heap_poison)("poisioning heap\n");
840 heap->critSection.DebugInfo = &process_heap_critsect_debug;
841 heap->critSection.LockCount = -1;
842 heap->critSection.RecursionCount = 0;
843 heap->critSection.OwningThread = 0;
844 heap->critSection.LockSemaphore = 0;
845 heap->critSection.SpinCount = 0;
846 process_heap_critsect_debug.CriticalSection = &heap->critSection;
848 else
850 RtlInitializeCriticalSection( &heap->critSection );
851 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
854 if (flags & HEAP_SHARED)
856 /* let's assume that only one thread at a time will try to do this */
857 HANDLE sem = heap->critSection.LockSemaphore;
858 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
860 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
861 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
862 heap->critSection.LockSemaphore = sem;
863 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
864 heap->critSection.DebugInfo = NULL;
868 /* Create the first free block */
870 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
871 subheap->size - subheap->headerSize );
873 return subheap;
877 /***********************************************************************
878 * HEAP_FindFreeBlock
880 * Find a free block at least as large as the requested size, and make sure
881 * the requested size is committed.
883 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
884 SUBHEAP **ppSubHeap )
886 SUBHEAP *subheap;
887 struct list *ptr;
888 SIZE_T total_size;
889 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
891 /* Find a suitable free list, and in it find a block large enough */
893 ptr = &pEntry->arena.entry;
894 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
896 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
897 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
898 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
899 if (arena_size >= size)
901 subheap = HEAP_FindSubHeap( heap, pArena );
902 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
903 *ppSubHeap = subheap;
904 return pArena;
908 /* If no block was found, attempt to grow the heap */
910 if (!(heap->flags & HEAP_GROWABLE))
912 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
913 return NULL;
915 /* make sure that we have a big enough size *committed* to fit another
916 * last free arena in !
917 * So just one heap struct, one first free arena which will eventually
918 * get used, and a second free arena that might get assigned all remaining
919 * free space in HEAP_ShrinkBlock() */
920 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
921 if (total_size < size) return NULL; /* overflow */
923 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
924 max( HEAP_DEF_SIZE, total_size ) )))
925 return NULL;
927 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
928 subheap, total_size, heap );
930 *ppSubHeap = subheap;
931 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
935 /***********************************************************************
936 * HEAP_IsValidArenaPtr
938 * Check that the pointer is inside the range possible for arenas.
940 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
942 unsigned int i;
943 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
944 if (!subheap) return FALSE;
945 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
946 if (subheap != &heap->subheap) return FALSE;
947 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
948 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
949 return FALSE;
953 /***********************************************************************
954 * HEAP_ValidateFreeArena
956 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
958 ARENA_FREE *prev, *next;
959 char *heapEnd = (char *)subheap->base + subheap->size;
961 /* Check for unaligned pointers */
962 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
964 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
965 return FALSE;
968 /* Check magic number */
969 if (pArena->magic != ARENA_FREE_MAGIC)
971 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
972 return FALSE;
974 /* Check size flags */
975 if (!(pArena->size & ARENA_FLAG_FREE) ||
976 (pArena->size & ARENA_FLAG_PREV_FREE))
978 ERR("Heap %p: bad flags %08x for free arena %p\n",
979 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
980 return FALSE;
982 /* Check arena size */
983 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
985 ERR("Heap %p: bad size %08x for free arena %p\n",
986 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
987 return FALSE;
989 /* Check that next pointer is valid */
990 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
991 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
993 ERR("Heap %p: bad next ptr %p for arena %p\n",
994 subheap->heap, next, pArena );
995 return FALSE;
997 /* Check that next arena is free */
998 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1000 ERR("Heap %p: next arena %p invalid for %p\n",
1001 subheap->heap, next, pArena );
1002 return FALSE;
1004 /* Check that prev pointer is valid */
1005 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1006 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1008 ERR("Heap %p: bad prev ptr %p for arena %p\n",
1009 subheap->heap, prev, pArena );
1010 return FALSE;
1012 /* Check that prev arena is free */
1013 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1015 /* this often means that the prev arena got overwritten
1016 * by a memory write before that prev arena */
1017 ERR("Heap %p: prev arena %p invalid for %p\n",
1018 subheap->heap, prev, pArena );
1019 return FALSE;
1021 /* Check that next block has PREV_FREE flag */
1022 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
1024 if (!(*(DWORD *)((char *)(pArena + 1) +
1025 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1027 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1028 subheap->heap, pArena );
1029 return FALSE;
1031 /* Check next block back pointer */
1032 if (*((ARENA_FREE **)((char *)(pArena + 1) +
1033 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
1035 ERR("Heap %p: arena %p has wrong back ptr %p\n",
1036 subheap->heap, pArena,
1037 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
1038 return FALSE;
1041 return TRUE;
1045 /***********************************************************************
1046 * HEAP_ValidateInUseArena
1048 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1050 const char *heapEnd = (const char *)subheap->base + subheap->size;
1052 /* Check for unaligned pointers */
1053 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
1055 if ( quiet == NOISY )
1057 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1058 if ( TRACE_ON(heap) )
1059 HEAP_Dump( subheap->heap );
1061 else if ( WARN_ON(heap) )
1063 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1064 if ( TRACE_ON(heap) )
1065 HEAP_Dump( subheap->heap );
1067 return FALSE;
1070 /* Check magic number */
1071 if (pArena->magic != ARENA_INUSE_MAGIC)
1073 if (quiet == NOISY) {
1074 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1075 if (TRACE_ON(heap))
1076 HEAP_Dump( subheap->heap );
1077 } else if (WARN_ON(heap)) {
1078 WARN("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 );
1082 return FALSE;
1084 /* Check size flags */
1085 if (pArena->size & ARENA_FLAG_FREE)
1087 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1088 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1089 return FALSE;
1091 /* Check arena size */
1092 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
1094 ERR("Heap %p: bad size %08x for in-use arena %p\n",
1095 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
1096 return FALSE;
1098 /* Check next arena PREV_FREE flag */
1099 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
1100 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
1102 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
1103 subheap->heap, pArena );
1104 return FALSE;
1106 /* Check prev free arena */
1107 if (pArena->size & ARENA_FLAG_PREV_FREE)
1109 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1110 /* Check prev pointer */
1111 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1113 ERR("Heap %p: bad back ptr %p for arena %p\n",
1114 subheap->heap, pPrev, pArena );
1115 return FALSE;
1117 /* Check that prev arena is free */
1118 if (!(pPrev->size & ARENA_FLAG_FREE) ||
1119 (pPrev->magic != ARENA_FREE_MAGIC))
1121 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1122 subheap->heap, pPrev, pArena );
1123 return FALSE;
1125 /* Check that prev arena is really the previous block */
1126 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1128 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1129 subheap->heap, pPrev, pArena );
1130 return FALSE;
1133 return TRUE;
1137 /***********************************************************************
1138 * HEAP_IsRealArena [Internal]
1139 * Validates a block is a valid arena.
1141 * RETURNS
1142 * TRUE: Success
1143 * FALSE: Failure
1145 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1146 DWORD flags, /* [in] Bit flags that control access during operation */
1147 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1148 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1149 * does not complain */
1151 SUBHEAP *subheap;
1152 BOOL ret = TRUE;
1153 const ARENA_LARGE *large_arena;
1155 flags &= HEAP_NO_SERIALIZE;
1156 flags |= heapPtr->flags;
1157 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1158 if (!(flags & HEAP_NO_SERIALIZE))
1159 RtlEnterCriticalSection( &heapPtr->critSection );
1161 if (block) /* only check this single memory block */
1163 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1165 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1166 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1168 if (!(large_arena = find_large_block( heapPtr, block )))
1170 if (quiet == NOISY)
1171 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1172 else if (WARN_ON(heap))
1173 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1174 ret = FALSE;
1176 else
1177 ret = validate_large_arena( heapPtr, large_arena, quiet );
1178 } else
1179 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1181 if (!(flags & HEAP_NO_SERIALIZE))
1182 RtlLeaveCriticalSection( &heapPtr->critSection );
1183 return ret;
1186 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1188 char *ptr = (char *)subheap->base + subheap->headerSize;
1189 while (ptr < (char *)subheap->base + subheap->size)
1191 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1193 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1194 ret = FALSE;
1195 break;
1197 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1199 else
1201 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1202 ret = FALSE;
1203 break;
1205 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1208 if (!ret) break;
1211 LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1212 if (!(ret = validate_large_arena( heapPtr, large_arena, quiet ))) break;
1214 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1215 return ret;
1219 /***********************************************************************
1220 * RtlCreateHeap (NTDLL.@)
1222 * Create a new Heap.
1224 * PARAMS
1225 * flags [I] HEAP_ flags from "winnt.h"
1226 * addr [I] Desired base address
1227 * totalSize [I] Total size of the heap, or 0 for a growable heap
1228 * commitSize [I] Amount of heap space to commit
1229 * unknown [I] Not yet understood
1230 * definition [I] Heap definition
1232 * RETURNS
1233 * Success: A HANDLE to the newly created heap.
1234 * Failure: a NULL HANDLE.
1236 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1237 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1239 SUBHEAP *subheap;
1241 /* Allocate the heap block */
1243 if (!totalSize)
1245 totalSize = HEAP_DEF_SIZE;
1246 flags |= HEAP_GROWABLE;
1249 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1251 /* link it into the per-process heap list */
1252 if (processHeap)
1254 HEAP *heapPtr = subheap->heap;
1255 RtlEnterCriticalSection( &processHeap->critSection );
1256 list_add_head( &processHeap->entry, &heapPtr->entry );
1257 RtlLeaveCriticalSection( &processHeap->critSection );
1259 else if (!addr)
1261 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1262 list_init( &processHeap->entry );
1263 /* make sure structure alignment is correct */
1264 assert( (ULONG_PTR)processHeap->freeList % ALIGNMENT == 0 );
1265 assert( sizeof(ARENA_LARGE) % LARGE_ALIGNMENT == 0 );
1268 return (HANDLE)subheap->heap;
1272 /***********************************************************************
1273 * RtlDestroyHeap (NTDLL.@)
1275 * Destroy a Heap created with RtlCreateHeap().
1277 * PARAMS
1278 * heap [I] Heap to destroy.
1280 * RETURNS
1281 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1282 * Failure: The Heap handle, if heap is the process heap.
1284 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1286 HEAP *heapPtr = HEAP_GetPtr( heap );
1287 SUBHEAP *subheap, *next;
1288 ARENA_LARGE *arena, *arena_next;
1289 SIZE_T size;
1290 void *addr;
1292 TRACE("%p\n", heap );
1293 if (!heapPtr) return heap;
1295 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1297 /* remove it from the per-process list */
1298 RtlEnterCriticalSection( &processHeap->critSection );
1299 list_remove( &heapPtr->entry );
1300 RtlLeaveCriticalSection( &processHeap->critSection );
1302 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1303 RtlDeleteCriticalSection( &heapPtr->critSection );
1305 LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1307 list_remove( &arena->entry );
1308 size = 0;
1309 addr = arena;
1310 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1312 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1314 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1315 subheap_notify_free_all(subheap);
1316 list_remove( &subheap->entry );
1317 size = 0;
1318 addr = subheap->base;
1319 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1321 subheap_notify_free_all(&heapPtr->subheap);
1322 size = 0;
1323 addr = heapPtr->subheap.base;
1324 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1325 return 0;
1329 /***********************************************************************
1330 * RtlAllocateHeap (NTDLL.@)
1332 * Allocate a memory block from a Heap.
1334 * PARAMS
1335 * heap [I] Heap to allocate block from
1336 * flags [I] HEAP_ flags from "winnt.h"
1337 * size [I] Size of the memory block to allocate
1339 * RETURNS
1340 * Success: A pointer to the newly allocated block
1341 * Failure: NULL.
1343 * NOTES
1344 * This call does not SetLastError().
1346 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1348 ARENA_FREE *pArena;
1349 ARENA_INUSE *pInUse;
1350 SUBHEAP *subheap;
1351 HEAP *heapPtr = HEAP_GetPtr( heap );
1352 SIZE_T rounded_size;
1354 /* Validate the parameters */
1356 if (!heapPtr) return NULL;
1357 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1358 flags |= heapPtr->flags;
1359 rounded_size = ROUND_SIZE(size);
1360 if (rounded_size < size) /* overflow */
1362 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1363 return NULL;
1365 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1367 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1369 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1371 void *ret = allocate_large_block( heap, flags, size );
1372 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1373 if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1374 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1375 return ret;
1378 /* Locate a suitable free block */
1380 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1382 TRACE("(%p,%08x,%08lx): returning NULL\n",
1383 heap, flags, size );
1384 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1385 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1386 return NULL;
1389 /* Remove the arena from the free list */
1391 list_remove( &pArena->entry );
1393 /* Build the in-use arena */
1395 pInUse = (ARENA_INUSE *)pArena;
1397 /* in-use arena is smaller than free arena,
1398 * so we have to add the difference to the size */
1399 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1400 pInUse->magic = ARENA_INUSE_MAGIC;
1402 /* Shrink the block */
1404 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1405 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1407 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1409 if (flags & HEAP_ZERO_MEMORY)
1411 clear_block( pInUse + 1, size );
1412 mark_block_uninitialized( (char *)(pInUse + 1) + size, pInUse->unused_bytes );
1414 else
1415 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1417 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1419 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1420 return (LPVOID)(pInUse + 1);
1424 /***********************************************************************
1425 * RtlFreeHeap (NTDLL.@)
1427 * Free a memory block allocated with RtlAllocateHeap().
1429 * PARAMS
1430 * heap [I] Heap that block was allocated from
1431 * flags [I] HEAP_ flags from "winnt.h"
1432 * ptr [I] Block to free
1434 * RETURNS
1435 * Success: TRUE, if ptr is NULL or was freed successfully.
1436 * Failure: FALSE.
1438 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1440 ARENA_INUSE *pInUse;
1441 SUBHEAP *subheap;
1442 HEAP *heapPtr;
1444 /* Validate the parameters */
1446 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1448 heapPtr = HEAP_GetPtr( heap );
1449 if (!heapPtr)
1451 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1452 return FALSE;
1455 flags &= HEAP_NO_SERIALIZE;
1456 flags |= heapPtr->flags;
1457 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1459 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1460 notify_free( ptr );
1462 /* Some sanity checks */
1463 pInUse = (ARENA_INUSE *)ptr - 1;
1464 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse )))
1466 if (!find_large_block( heapPtr, ptr )) goto error;
1467 free_large_block( heapPtr, flags, ptr );
1468 goto done;
1470 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1471 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1473 /* Turn the block into a free block */
1475 HEAP_MakeInUseBlockFree( subheap, pInUse );
1477 done:
1478 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1479 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1480 return TRUE;
1482 error:
1483 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1484 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1485 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1486 return FALSE;
1490 /***********************************************************************
1491 * RtlReAllocateHeap (NTDLL.@)
1493 * Change the size of a memory block allocated with RtlAllocateHeap().
1495 * PARAMS
1496 * heap [I] Heap that block was allocated from
1497 * flags [I] HEAP_ flags from "winnt.h"
1498 * ptr [I] Block to resize
1499 * size [I] Size of the memory block to allocate
1501 * RETURNS
1502 * Success: A pointer to the resized block (which may be different).
1503 * Failure: NULL.
1505 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1507 ARENA_INUSE *pArena;
1508 HEAP *heapPtr;
1509 SUBHEAP *subheap;
1510 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1511 void *ret;
1513 if (!ptr) return NULL;
1514 if (!(heapPtr = HEAP_GetPtr( heap )))
1516 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1517 return NULL;
1520 /* Validate the parameters */
1522 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1523 HEAP_REALLOC_IN_PLACE_ONLY;
1524 flags |= heapPtr->flags;
1525 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1527 rounded_size = ROUND_SIZE(size);
1528 if (rounded_size < size) goto oom; /* overflow */
1529 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1531 pArena = (ARENA_INUSE *)ptr - 1;
1532 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena )))
1534 if (!find_large_block( heapPtr, ptr )) goto error;
1535 if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1536 goto done;
1538 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1539 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1541 /* Check if we need to grow the block */
1543 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1544 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1545 if (rounded_size > oldBlockSize)
1547 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1549 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1551 if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1552 memcpy( ret, pArena + 1, oldActualSize );
1553 goto done;
1555 if ((pNext < (char *)subheap->base + subheap->size) &&
1556 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1557 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1559 /* The next block is free and large enough */
1560 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1561 list_remove( &pFree->entry );
1562 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1563 if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1564 notify_free( pArena + 1 );
1565 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1566 notify_alloc( pArena + 1, size, FALSE );
1567 /* FIXME: this is wrong as we may lose old VBits settings */
1568 mark_block_initialized( pArena + 1, oldActualSize );
1570 else /* Do it the hard way */
1572 ARENA_FREE *pNew;
1573 ARENA_INUSE *pInUse;
1574 SUBHEAP *newsubheap;
1576 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1577 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1578 goto oom;
1580 /* Build the in-use arena */
1582 list_remove( &pNew->entry );
1583 pInUse = (ARENA_INUSE *)pNew;
1584 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1585 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1586 pInUse->magic = ARENA_INUSE_MAGIC;
1587 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1589 mark_block_initialized( pInUse + 1, oldActualSize );
1590 notify_alloc( pInUse + 1, size, FALSE );
1591 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1593 /* Free the previous block */
1595 notify_free( pArena + 1 );
1596 HEAP_MakeInUseBlockFree( subheap, pArena );
1597 subheap = newsubheap;
1598 pArena = pInUse;
1601 else
1603 /* Shrink the block */
1604 notify_free( pArena + 1 );
1605 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1606 notify_alloc( pArena + 1, size, FALSE );
1607 /* FIXME: this is wrong as we may lose old VBits settings */
1608 mark_block_initialized( pArena + 1, size );
1611 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1613 /* Clear the extra bytes if needed */
1615 if (size > oldActualSize)
1617 if (flags & HEAP_ZERO_MEMORY)
1619 clear_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize );
1620 mark_block_uninitialized( (char *)(pArena + 1) + size, pArena->unused_bytes );
1622 else
1623 mark_block_uninitialized( (char *)(pArena + 1) + oldActualSize,
1624 (pArena->size & ARENA_SIZE_MASK) - oldActualSize );
1627 /* Return the new arena */
1629 ret = pArena + 1;
1630 done:
1631 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1632 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1633 return ret;
1635 oom:
1636 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1637 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1638 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1639 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1640 return NULL;
1642 error:
1643 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1644 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1645 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1646 return NULL;
1650 /***********************************************************************
1651 * RtlCompactHeap (NTDLL.@)
1653 * Compact the free space in a Heap.
1655 * PARAMS
1656 * heap [I] Heap that block was allocated from
1657 * flags [I] HEAP_ flags from "winnt.h"
1659 * RETURNS
1660 * The number of bytes compacted.
1662 * NOTES
1663 * This function is a harmless stub.
1665 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1667 static BOOL reported;
1668 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1669 return 0;
1673 /***********************************************************************
1674 * RtlLockHeap (NTDLL.@)
1676 * Lock a Heap.
1678 * PARAMS
1679 * heap [I] Heap to lock
1681 * RETURNS
1682 * Success: TRUE. The Heap is locked.
1683 * Failure: FALSE, if heap is invalid.
1685 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1687 HEAP *heapPtr = HEAP_GetPtr( heap );
1688 if (!heapPtr) return FALSE;
1689 RtlEnterCriticalSection( &heapPtr->critSection );
1690 return TRUE;
1694 /***********************************************************************
1695 * RtlUnlockHeap (NTDLL.@)
1697 * Unlock a Heap.
1699 * PARAMS
1700 * heap [I] Heap to unlock
1702 * RETURNS
1703 * Success: TRUE. The Heap is unlocked.
1704 * Failure: FALSE, if heap is invalid.
1706 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1708 HEAP *heapPtr = HEAP_GetPtr( heap );
1709 if (!heapPtr) return FALSE;
1710 RtlLeaveCriticalSection( &heapPtr->critSection );
1711 return TRUE;
1715 /***********************************************************************
1716 * RtlSizeHeap (NTDLL.@)
1718 * Get the actual size of a memory block allocated from a Heap.
1720 * PARAMS
1721 * heap [I] Heap that block was allocated from
1722 * flags [I] HEAP_ flags from "winnt.h"
1723 * ptr [I] Block to get the size of
1725 * RETURNS
1726 * Success: The size of the block.
1727 * Failure: -1, heap or ptr are invalid.
1729 * NOTES
1730 * The size may be bigger than what was passed to RtlAllocateHeap().
1732 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1734 SIZE_T ret;
1735 HEAP *heapPtr = HEAP_GetPtr( heap );
1737 if (!heapPtr)
1739 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1740 return ~0UL;
1742 flags &= HEAP_NO_SERIALIZE;
1743 flags |= heapPtr->flags;
1744 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1745 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1747 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1748 ret = ~0UL;
1750 else
1752 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1753 if (pArena->size == ARENA_LARGE_SIZE)
1755 const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
1756 ret = large_arena->data_size;
1758 else ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1760 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1762 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1763 return ret;
1767 /***********************************************************************
1768 * RtlValidateHeap (NTDLL.@)
1770 * Determine if a block is a valid allocation from a heap.
1772 * PARAMS
1773 * heap [I] Heap that block was allocated from
1774 * flags [I] HEAP_ flags from "winnt.h"
1775 * ptr [I] Block to check
1777 * RETURNS
1778 * Success: TRUE. The block was allocated from heap.
1779 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1781 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1783 HEAP *heapPtr = HEAP_GetPtr( heap );
1784 if (!heapPtr) return FALSE;
1785 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1789 /***********************************************************************
1790 * RtlWalkHeap (NTDLL.@)
1792 * FIXME
1793 * The PROCESS_HEAP_ENTRY flag values seem different between this
1794 * function and HeapWalk(). To be checked.
1796 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1798 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1799 HEAP *heapPtr = HEAP_GetPtr(heap);
1800 SUBHEAP *sub, *currentheap = NULL;
1801 NTSTATUS ret;
1802 char *ptr;
1803 int region_index = 0;
1805 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1807 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1809 /* FIXME: enumerate large blocks too */
1811 /* set ptr to the next arena to be examined */
1813 if (!entry->lpData) /* first call (init) ? */
1815 TRACE("begin walking of heap %p.\n", heap);
1816 currentheap = &heapPtr->subheap;
1817 ptr = (char*)currentheap->base + currentheap->headerSize;
1819 else
1821 ptr = entry->lpData;
1822 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1824 if ((ptr >= (char *)sub->base) &&
1825 (ptr < (char *)sub->base + sub->size))
1827 currentheap = sub;
1828 break;
1830 region_index++;
1832 if (currentheap == NULL)
1834 ERR("no matching subheap found, shouldn't happen !\n");
1835 ret = STATUS_NO_MORE_ENTRIES;
1836 goto HW_end;
1839 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1841 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1842 ptr += pArena->size & ARENA_SIZE_MASK;
1844 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1846 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1847 ptr += pArena->size & ARENA_SIZE_MASK;
1849 else
1850 ptr += entry->cbData; /* point to next arena */
1852 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1853 { /* proceed with next subheap */
1854 struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
1855 if (!next)
1856 { /* successfully finished */
1857 TRACE("end reached.\n");
1858 ret = STATUS_NO_MORE_ENTRIES;
1859 goto HW_end;
1861 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1862 ptr = (char *)currentheap->base + currentheap->headerSize;
1866 entry->wFlags = 0;
1867 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1869 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1871 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1873 entry->lpData = pArena + 1;
1874 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1875 entry->cbOverhead = sizeof(ARENA_FREE);
1876 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1878 else
1880 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1882 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1884 entry->lpData = pArena + 1;
1885 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1886 entry->cbOverhead = sizeof(ARENA_INUSE);
1887 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1888 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1889 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1892 entry->iRegionIndex = region_index;
1894 /* first element of heap ? */
1895 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1897 entry->wFlags |= PROCESS_HEAP_REGION;
1898 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1899 entry->u.Region.dwUnCommittedSize =
1900 currentheap->size - currentheap->commitSize;
1901 entry->u.Region.lpFirstBlock = /* first valid block */
1902 (char *)currentheap->base + currentheap->headerSize;
1903 entry->u.Region.lpLastBlock = /* first invalid block */
1904 (char *)currentheap->base + currentheap->size;
1906 ret = STATUS_SUCCESS;
1907 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1909 HW_end:
1910 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1911 return ret;
1915 /***********************************************************************
1916 * RtlGetProcessHeaps (NTDLL.@)
1918 * Get the Heaps belonging to the current process.
1920 * PARAMS
1921 * count [I] size of heaps
1922 * heaps [O] Destination array for heap HANDLE's
1924 * RETURNS
1925 * Success: The number of Heaps allocated by the process.
1926 * Failure: 0.
1928 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1930 ULONG total = 1; /* main heap */
1931 struct list *ptr;
1933 RtlEnterCriticalSection( &processHeap->critSection );
1934 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1935 if (total <= count)
1937 *heaps++ = processHeap;
1938 LIST_FOR_EACH( ptr, &processHeap->entry )
1939 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1941 RtlLeaveCriticalSection( &processHeap->critSection );
1942 return total;