push 97f44e0adb27fff75ba63d8fb97c65db9edfbe82
[wine/hacks.git] / dlls / ntdll / heap.c
bloba68acf3105e8c5c75af0f64790a4f2e9973854af
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"
24 #include <assert.h>
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <string.h>
29 #ifdef HAVE_VALGRIND_MEMCHECK_H
30 #include <valgrind/memcheck.h>
31 #endif
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
35 #include "ntstatus.h"
36 #define WIN32_NO_STATUS
37 #include "windef.h"
38 #include "winnt.h"
39 #include "winternl.h"
40 #include "wine/list.h"
41 #include "wine/debug.h"
42 #include "wine/server.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(heap);
45 WINE_DECLARE_DEBUG_CHANNEL(heap_poison);
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 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
53 * that there is no unaligned accesses to structure fields.
56 typedef struct tagARENA_INUSE
58 DWORD size; /* Block size; must be the first field */
59 DWORD magic : 24; /* Magic number */
60 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) */
61 } ARENA_INUSE;
63 typedef struct tagARENA_FREE
65 DWORD size; /* Block size; must be the first field */
66 DWORD magic; /* Magic number */
67 struct list entry; /* Entry in free list */
68 } ARENA_FREE;
70 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
71 #define ARENA_FLAG_PREV_FREE 0x00000002
72 #define ARENA_SIZE_MASK (~3)
73 #define ARENA_INUSE_MAGIC 0x455355 /* Value for arena 'magic' field */
74 #define ARENA_FREE_MAGIC 0x45455246 /* Value for arena 'magic' field */
76 #define ARENA_INUSE_FILLER 0x55
77 #define ARENA_FREE_FILLER 0xaa
79 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
80 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
82 #define QUIET 1 /* Suppress messages */
83 #define NOISY 0 /* Report all errors */
85 /* minimum data size (without arenas) of an allocated block */
86 /* make sure that it's larger than a free list entry */
87 #define HEAP_MIN_DATA_SIZE (2 * sizeof(struct list))
88 /* minimum size that must remain to shrink an allocated block */
89 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
91 /* Max size of the blocks on the free lists */
92 static const SIZE_T HEAP_freeListSizes[] =
94 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
96 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
98 typedef struct
100 ARENA_FREE arena;
101 } FREE_LIST_ENTRY;
103 struct tagHEAP;
105 typedef struct tagSUBHEAP
107 void *base; /* Base address of the sub-heap memory block */
108 SIZE_T size; /* Size of the whole sub-heap */
109 SIZE_T commitSize; /* Committed size of the sub-heap */
110 struct list entry; /* Entry in sub-heap list */
111 struct tagHEAP *heap; /* Main heap structure */
112 DWORD headerSize; /* Size of the heap header */
113 DWORD magic; /* Magic number */
114 } SUBHEAP;
116 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
118 typedef struct tagHEAP
120 DWORD unknown[3];
121 DWORD flags; /* Heap flags */
122 DWORD force_flags; /* Forced heap flags for debugging */
123 SUBHEAP subheap; /* First sub-heap */
124 struct list entry; /* Entry in process heap list */
125 struct list subheap_list; /* Sub-heap list */
126 DWORD magic; /* Magic number */
127 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
128 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
129 } HEAP;
131 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
133 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
134 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
136 static HEAP *processHeap; /* main process heap */
138 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
140 /* mark a block of memory as free for debugging purposes */
141 static inline void mark_block_free( void *ptr, SIZE_T size )
143 if (TRACE_ON(heap) || WARN_ON(heap) || TRACE_ON(heap_poison)) memset( ptr, ARENA_FREE_FILLER, size );
144 #ifdef VALGRIND_MAKE_NOACCESS
145 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
146 #endif
149 /* mark a block of memory as initialized for debugging purposes */
150 static inline void mark_block_initialized( void *ptr, SIZE_T size )
152 #ifdef VALGRIND_MAKE_READABLE
153 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
154 #endif
157 /* mark a block of memory as uninitialized for debugging purposes */
158 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
160 #ifdef VALGRIND_MAKE_WRITABLE
161 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
162 #endif
163 if (TRACE_ON(heap) || WARN_ON(heap) || TRACE_ON(heap_poison))
165 memset( ptr, ARENA_INUSE_FILLER, size );
166 #ifdef VALGRIND_MAKE_WRITABLE
167 /* make it uninitialized to valgrind again */
168 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
169 #endif
173 /* clear contents of a block of memory */
174 static inline void clear_block( void *ptr, SIZE_T size )
176 mark_block_initialized( ptr, size );
177 memset( ptr, 0, size );
180 /* notify that a new block of memory has been allocated for debugging purposes */
181 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
183 #ifdef VALGRIND_MALLOCLIKE_BLOCK
184 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
185 #endif
188 /* notify that a block of memory has been freed for debugging purposes */
189 static inline void notify_free( void *ptr )
191 #ifdef VALGRIND_FREELIKE_BLOCK
192 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
193 #endif
196 /* locate a free list entry of the appropriate size */
197 /* size is the size of the whole block including the arena header */
198 static inline unsigned int get_freelist_index( SIZE_T size )
200 unsigned int i;
202 size -= sizeof(ARENA_FREE);
203 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
204 return i;
207 /* get the memory protection type to use for a given heap */
208 static inline ULONG get_protection_type( DWORD flags )
210 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
213 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
215 0, 0, NULL, /* will be set later */
216 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
217 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
221 /***********************************************************************
222 * HEAP_Dump
224 static void HEAP_Dump( HEAP *heap )
226 int i;
227 SUBHEAP *subheap;
228 char *ptr;
230 DPRINTF( "Heap: %p\n", heap );
231 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
232 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
234 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
235 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
236 DPRINTF( "%p free %08lx prev=%p next=%p\n",
237 &heap->freeList[i].arena, HEAP_freeListSizes[i],
238 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
239 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
241 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
243 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
244 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
245 subheap, subheap->base, subheap->size, subheap->commitSize );
247 DPRINTF( "\n Block Stat Size Id\n" );
248 ptr = (char *)subheap->base + subheap->headerSize;
249 while (ptr < (char *)subheap->base + subheap->size)
251 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
253 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
254 DPRINTF( "%p free %08x prev=%p next=%p\n",
255 pArena, pArena->size & ARENA_SIZE_MASK,
256 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
257 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
258 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
259 arenaSize += sizeof(ARENA_FREE);
260 freeSize += pArena->size & ARENA_SIZE_MASK;
262 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
264 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
265 DPRINTF( "%p Used %08x back=%p\n",
266 pArena, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
267 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
268 arenaSize += sizeof(ARENA_INUSE);
269 usedSize += pArena->size & ARENA_SIZE_MASK;
271 else
273 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
274 DPRINTF( "%p used %08x\n", pArena, pArena->size & ARENA_SIZE_MASK );
275 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
276 arenaSize += sizeof(ARENA_INUSE);
277 usedSize += pArena->size & ARENA_SIZE_MASK;
280 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
281 subheap->size, subheap->commitSize, freeSize, usedSize,
282 arenaSize, (arenaSize * 100) / subheap->size );
287 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
289 WORD rem_flags;
290 TRACE( "Dumping entry %p\n", entry );
291 TRACE( "lpData\t\t: %p\n", entry->lpData );
292 TRACE( "cbData\t\t: %08x\n", entry->cbData);
293 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
294 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
295 TRACE( "WFlags\t\t: ");
296 if (entry->wFlags & PROCESS_HEAP_REGION)
297 TRACE( "PROCESS_HEAP_REGION ");
298 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
299 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
300 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
301 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
302 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
303 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
304 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
305 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
306 rem_flags = entry->wFlags &
307 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
308 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
309 PROCESS_HEAP_ENTRY_DDESHARE);
310 if (rem_flags)
311 TRACE( "Unknown %08x", rem_flags);
312 TRACE( "\n");
313 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
314 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
316 /* Treat as block */
317 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
319 if (entry->wFlags & PROCESS_HEAP_REGION)
321 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
322 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
323 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
324 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
328 /***********************************************************************
329 * HEAP_GetPtr
330 * RETURNS
331 * Pointer to the heap
332 * NULL: Failure
334 static HEAP *HEAP_GetPtr(
335 HANDLE heap /* [in] Handle to the heap */
337 HEAP *heapPtr = (HEAP *)heap;
338 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
340 ERR("Invalid heap %p!\n", heap );
341 return NULL;
343 if ((TRACE_ON(heap)|| TRACE_ON(heap_poison)) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
345 HEAP_Dump( heapPtr );
346 assert( FALSE );
347 return NULL;
349 return heapPtr;
353 /***********************************************************************
354 * HEAP_InsertFreeBlock
356 * Insert a free block into the free list.
358 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
360 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
361 if (last)
363 /* insert at end of free list, i.e. before the next free list entry */
364 pEntry++;
365 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
366 list_add_before( &pEntry->arena.entry, &pArena->entry );
368 else
370 /* insert at head of free list */
371 list_add_after( &pEntry->arena.entry, &pArena->entry );
373 pArena->size |= ARENA_FLAG_FREE;
377 /***********************************************************************
378 * HEAP_FindSubHeap
379 * Find the sub-heap containing a given address.
381 * RETURNS
382 * Pointer: Success
383 * NULL: Failure
385 static SUBHEAP *HEAP_FindSubHeap(
386 const HEAP *heap, /* [in] Heap pointer */
387 LPCVOID ptr ) /* [in] Address */
389 SUBHEAP *sub;
390 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
391 if (((const char *)ptr >= (const char *)sub->base) &&
392 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
393 return sub;
394 return NULL;
398 /***********************************************************************
399 * HEAP_Commit
401 * Make sure the heap storage is committed for a given size in the specified arena.
403 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
405 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
406 SIZE_T size = (char *)ptr - (char *)subheap->base;
407 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
408 if (size > subheap->size) size = subheap->size;
409 if (size <= subheap->commitSize) return TRUE;
410 size -= subheap->commitSize;
411 ptr = (char *)subheap->base + subheap->commitSize;
412 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
413 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
415 WARN("Could not commit %08lx bytes at %p for heap %p\n",
416 size, ptr, subheap->heap );
417 return FALSE;
419 subheap->commitSize += size;
420 return TRUE;
424 /***********************************************************************
425 * HEAP_Decommit
427 * If possible, decommit the heap storage from (including) 'ptr'.
429 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
431 void *addr;
432 SIZE_T decommit_size;
433 SIZE_T size = (char *)ptr - (char *)subheap->base;
435 /* round to next block and add one full block */
436 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
437 if (size >= subheap->commitSize) return TRUE;
438 decommit_size = subheap->commitSize - size;
439 addr = (char *)subheap->base + size;
441 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
443 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
444 decommit_size, (char *)subheap->base + size, subheap->heap );
445 return FALSE;
447 subheap->commitSize -= decommit_size;
448 return TRUE;
452 /***********************************************************************
453 * HEAP_CreateFreeBlock
455 * Create a free block at a specified address. 'size' is the size of the
456 * whole block, including the new arena.
458 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
460 ARENA_FREE *pFree;
461 char *pEnd;
462 BOOL last;
464 /* Create a free arena */
465 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
466 pFree = (ARENA_FREE *)ptr;
467 pFree->magic = ARENA_FREE_MAGIC;
469 /* If debugging, erase the freed block content */
471 pEnd = (char *)ptr + size;
472 if (pEnd > (char *)subheap->base + subheap->commitSize)
473 pEnd = (char *)subheap->base + subheap->commitSize;
474 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
476 /* Check if next block is free also */
478 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
479 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
481 /* Remove the next arena from the free list */
482 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
483 list_remove( &pNext->entry );
484 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
485 mark_block_free( pNext, sizeof(ARENA_FREE) );
488 /* Set the next block PREV_FREE flag and pointer */
490 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
491 if (!last)
493 DWORD *pNext = (DWORD *)((char *)ptr + size);
494 *pNext |= ARENA_FLAG_PREV_FREE;
495 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
496 *((ARENA_FREE **)pNext - 1) = pFree;
499 /* Last, insert the new block into the free list */
501 pFree->size = size - sizeof(*pFree);
502 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
506 /***********************************************************************
507 * HEAP_MakeInUseBlockFree
509 * Turn an in-use block into a free block. Can also decommit the end of
510 * the heap, and possibly even free the sub-heap altogether.
512 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
514 ARENA_FREE *pFree;
515 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
517 /* Check if we can merge with previous block */
519 if (pArena->size & ARENA_FLAG_PREV_FREE)
521 pFree = *((ARENA_FREE **)pArena - 1);
522 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
523 /* Remove it from the free list */
524 list_remove( &pFree->entry );
526 else pFree = (ARENA_FREE *)pArena;
528 /* Create a free block */
530 HEAP_CreateFreeBlock( subheap, pFree, size );
531 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
532 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
533 return; /* Not the last block, so nothing more to do */
535 /* Free the whole sub-heap if it's empty and not the original one */
537 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
538 (subheap != &subheap->heap->subheap))
540 SIZE_T size = 0;
541 void *addr = subheap->base;
542 /* Remove the free block from the list */
543 list_remove( &pFree->entry );
544 /* Remove the subheap from the list */
545 list_remove( &subheap->entry );
546 /* Free the memory */
547 subheap->magic = 0;
548 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
549 return;
552 /* Decommit the end of the heap */
554 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
558 /***********************************************************************
559 * HEAP_ShrinkBlock
561 * Shrink an in-use block.
563 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
565 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
567 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
568 (pArena->size & ARENA_SIZE_MASK) - size );
569 /* assign size plus previous arena flags */
570 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
572 else
574 /* Turn off PREV_FREE flag in next block */
575 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
576 if (pNext < (char *)subheap->base + subheap->size)
577 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
581 /***********************************************************************
582 * HEAP_InitSubHeap
584 static SUBHEAP *HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
585 SIZE_T commitSize, SIZE_T totalSize )
587 SUBHEAP *subheap;
588 FREE_LIST_ENTRY *pEntry;
589 int i;
591 /* Commit memory */
593 if (flags & HEAP_SHARED)
594 commitSize = totalSize; /* always commit everything in a shared heap */
595 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
596 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
598 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
599 return NULL;
602 if (heap)
604 /* If this is a secondary subheap, insert it into list */
606 subheap = (SUBHEAP *)address;
607 subheap->base = address;
608 subheap->heap = heap;
609 subheap->size = totalSize;
610 subheap->commitSize = commitSize;
611 subheap->magic = SUBHEAP_MAGIC;
612 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
613 list_add_head( &heap->subheap_list, &subheap->entry );
615 else
617 /* If this is a primary subheap, initialize main heap */
619 heap = (HEAP *)address;
620 heap->flags = flags;
621 heap->magic = HEAP_MAGIC;
622 list_init( &heap->subheap_list );
624 subheap = &heap->subheap;
625 subheap->base = address;
626 subheap->heap = heap;
627 subheap->size = totalSize;
628 subheap->commitSize = commitSize;
629 subheap->magic = SUBHEAP_MAGIC;
630 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
631 list_add_head( &heap->subheap_list, &subheap->entry );
633 /* Build the free lists */
635 list_init( &heap->freeList[0].arena.entry );
636 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
638 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
639 pEntry->arena.magic = ARENA_FREE_MAGIC;
640 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
643 /* Initialize critical section */
645 if (!processHeap) /* do it by hand to avoid memory allocations */
647 if(TRACE_ON(heap_poison))
648 TRACE_(heap_poison)("poisioning heap\n");
649 heap->critSection.DebugInfo = &process_heap_critsect_debug;
650 heap->critSection.LockCount = -1;
651 heap->critSection.RecursionCount = 0;
652 heap->critSection.OwningThread = 0;
653 heap->critSection.LockSemaphore = 0;
654 heap->critSection.SpinCount = 0;
655 process_heap_critsect_debug.CriticalSection = &heap->critSection;
657 else
659 RtlInitializeCriticalSection( &heap->critSection );
660 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
663 if (flags & HEAP_SHARED)
665 /* let's assume that only one thread at a time will try to do this */
666 HANDLE sem = heap->critSection.LockSemaphore;
667 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
669 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
670 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
671 heap->critSection.LockSemaphore = sem;
672 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
673 heap->critSection.DebugInfo = NULL;
677 /* Create the first free block */
679 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
680 subheap->size - subheap->headerSize );
682 return subheap;
685 /***********************************************************************
686 * HEAP_CreateSubHeap
688 * Create a sub-heap of the given size.
689 * If heap == NULL, creates a main heap.
691 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
692 SIZE_T commitSize, SIZE_T totalSize )
694 LPVOID address = base;
695 SUBHEAP *ret;
697 /* round-up sizes on a 64K boundary */
698 totalSize = (totalSize + 0xffff) & 0xffff0000;
699 commitSize = (commitSize + 0xffff) & 0xffff0000;
700 if (!commitSize) commitSize = 0x10000;
701 if (totalSize < commitSize) totalSize = commitSize;
703 if (!address)
705 /* allocate the memory block */
706 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
707 MEM_RESERVE, get_protection_type( flags ) ))
709 WARN("Could not allocate %08lx bytes\n", totalSize );
710 return NULL;
714 /* Initialize subheap */
716 if (!(ret = HEAP_InitSubHeap( heap, address, flags, commitSize, totalSize )))
718 SIZE_T size = 0;
719 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
721 return ret;
725 /***********************************************************************
726 * HEAP_FindFreeBlock
728 * Find a free block at least as large as the requested size, and make sure
729 * the requested size is committed.
731 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
732 SUBHEAP **ppSubHeap )
734 SUBHEAP *subheap;
735 struct list *ptr;
736 SIZE_T total_size;
737 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
739 /* Find a suitable free list, and in it find a block large enough */
741 ptr = &pEntry->arena.entry;
742 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
744 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
745 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
746 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
747 if (arena_size >= size)
749 subheap = HEAP_FindSubHeap( heap, pArena );
750 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
751 *ppSubHeap = subheap;
752 return pArena;
756 /* If no block was found, attempt to grow the heap */
758 if (!(heap->flags & HEAP_GROWABLE))
760 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
761 return NULL;
763 /* make sure that we have a big enough size *committed* to fit another
764 * last free arena in !
765 * So just one heap struct, one first free arena which will eventually
766 * get used, and a second free arena that might get assigned all remaining
767 * free space in HEAP_ShrinkBlock() */
768 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
769 if (total_size < size) return NULL; /* overflow */
771 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
772 max( HEAP_DEF_SIZE, total_size ) )))
773 return NULL;
775 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
776 subheap, total_size, heap );
778 *ppSubHeap = subheap;
779 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
783 /***********************************************************************
784 * HEAP_IsValidArenaPtr
786 * Check that the pointer is inside the range possible for arenas.
788 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
790 int i;
791 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
792 if (!subheap) return FALSE;
793 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
794 if (subheap != &heap->subheap) return FALSE;
795 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
796 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
797 return FALSE;
801 /***********************************************************************
802 * HEAP_ValidateFreeArena
804 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
806 ARENA_FREE *prev, *next;
807 char *heapEnd = (char *)subheap->base + subheap->size;
809 /* Check for unaligned pointers */
810 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
812 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
813 return FALSE;
816 /* Check magic number */
817 if (pArena->magic != ARENA_FREE_MAGIC)
819 ERR("Heap %p: invalid free arena magic for %p\n", subheap->heap, pArena );
820 return FALSE;
822 /* Check size flags */
823 if (!(pArena->size & ARENA_FLAG_FREE) ||
824 (pArena->size & ARENA_FLAG_PREV_FREE))
826 ERR("Heap %p: bad flags %08x for free arena %p\n",
827 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
828 return FALSE;
830 /* Check arena size */
831 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
833 ERR("Heap %p: bad size %08x for free arena %p\n",
834 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
835 return FALSE;
837 /* Check that next pointer is valid */
838 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
839 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
841 ERR("Heap %p: bad next ptr %p for arena %p\n",
842 subheap->heap, next, pArena );
843 return FALSE;
845 /* Check that next arena is free */
846 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
848 ERR("Heap %p: next arena %p invalid for %p\n",
849 subheap->heap, next, pArena );
850 return FALSE;
852 /* Check that prev pointer is valid */
853 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
854 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
856 ERR("Heap %p: bad prev ptr %p for arena %p\n",
857 subheap->heap, prev, pArena );
858 return FALSE;
860 /* Check that prev arena is free */
861 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
863 /* this often means that the prev arena got overwritten
864 * by a memory write before that prev arena */
865 ERR("Heap %p: prev arena %p invalid for %p\n",
866 subheap->heap, prev, pArena );
867 return FALSE;
869 /* Check that next block has PREV_FREE flag */
870 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
872 if (!(*(DWORD *)((char *)(pArena + 1) +
873 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
875 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
876 subheap->heap, pArena );
877 return FALSE;
879 /* Check next block back pointer */
880 if (*((ARENA_FREE **)((char *)(pArena + 1) +
881 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
883 ERR("Heap %p: arena %p has wrong back ptr %p\n",
884 subheap->heap, pArena,
885 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
886 return FALSE;
889 return TRUE;
893 /***********************************************************************
894 * HEAP_ValidateInUseArena
896 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
898 const char *heapEnd = (const char *)subheap->base + subheap->size;
900 /* Check for unaligned pointers */
901 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
903 if ( quiet == NOISY )
905 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
906 if ( TRACE_ON(heap) )
907 HEAP_Dump( subheap->heap );
909 else if ( WARN_ON(heap) )
911 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
912 if ( TRACE_ON(heap) )
913 HEAP_Dump( subheap->heap );
915 return FALSE;
918 /* Check magic number */
919 if (pArena->magic != ARENA_INUSE_MAGIC)
921 if (quiet == NOISY) {
922 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
923 if (TRACE_ON(heap))
924 HEAP_Dump( subheap->heap );
925 } else if (WARN_ON(heap)) {
926 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
927 if (TRACE_ON(heap))
928 HEAP_Dump( subheap->heap );
930 return FALSE;
932 /* Check size flags */
933 if (pArena->size & ARENA_FLAG_FREE)
935 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
936 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
937 return FALSE;
939 /* Check arena size */
940 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
942 ERR("Heap %p: bad size %08x for in-use arena %p\n",
943 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
944 return FALSE;
946 /* Check next arena PREV_FREE flag */
947 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
948 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
950 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
951 subheap->heap, pArena );
952 return FALSE;
954 /* Check prev free arena */
955 if (pArena->size & ARENA_FLAG_PREV_FREE)
957 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
958 /* Check prev pointer */
959 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
961 ERR("Heap %p: bad back ptr %p for arena %p\n",
962 subheap->heap, pPrev, pArena );
963 return FALSE;
965 /* Check that prev arena is free */
966 if (!(pPrev->size & ARENA_FLAG_FREE) ||
967 (pPrev->magic != ARENA_FREE_MAGIC))
969 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
970 subheap->heap, pPrev, pArena );
971 return FALSE;
973 /* Check that prev arena is really the previous block */
974 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
976 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
977 subheap->heap, pPrev, pArena );
978 return FALSE;
981 return TRUE;
985 /***********************************************************************
986 * HEAP_IsRealArena [Internal]
987 * Validates a block is a valid arena.
989 * RETURNS
990 * TRUE: Success
991 * FALSE: Failure
993 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
994 DWORD flags, /* [in] Bit flags that control access during operation */
995 LPCVOID block, /* [in] Optional pointer to memory block to validate */
996 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
997 * does not complain */
999 SUBHEAP *subheap;
1000 BOOL ret = TRUE;
1002 flags &= HEAP_NO_SERIALIZE;
1003 flags |= heapPtr->flags;
1004 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1005 if (!(flags & HEAP_NO_SERIALIZE))
1006 RtlEnterCriticalSection( &heapPtr->critSection );
1008 if (block) /* only check this single memory block */
1010 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1012 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1013 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1015 if (quiet == NOISY)
1016 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1017 else if (WARN_ON(heap))
1018 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1019 ret = FALSE;
1020 } else
1021 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1023 if (!(flags & HEAP_NO_SERIALIZE))
1024 RtlLeaveCriticalSection( &heapPtr->critSection );
1025 return ret;
1028 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1030 char *ptr = (char *)subheap->base + subheap->headerSize;
1031 while (ptr < (char *)subheap->base + subheap->size)
1033 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1035 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1036 ret = FALSE;
1037 break;
1039 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1041 else
1043 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1044 ret = FALSE;
1045 break;
1047 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1050 if (!ret) break;
1053 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1054 return ret;
1058 /***********************************************************************
1059 * RtlCreateHeap (NTDLL.@)
1061 * Create a new Heap.
1063 * PARAMS
1064 * flags [I] HEAP_ flags from "winnt.h"
1065 * addr [I] Desired base address
1066 * totalSize [I] Total size of the heap, or 0 for a growable heap
1067 * commitSize [I] Amount of heap space to commit
1068 * unknown [I] Not yet understood
1069 * definition [I] Heap definition
1071 * RETURNS
1072 * Success: A HANDLE to the newly created heap.
1073 * Failure: a NULL HANDLE.
1075 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1076 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1078 SUBHEAP *subheap;
1080 /* Allocate the heap block */
1082 if (!totalSize)
1084 totalSize = HEAP_DEF_SIZE;
1085 flags |= HEAP_GROWABLE;
1088 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1090 /* link it into the per-process heap list */
1091 if (processHeap)
1093 HEAP *heapPtr = subheap->heap;
1094 RtlEnterCriticalSection( &processHeap->critSection );
1095 list_add_head( &processHeap->entry, &heapPtr->entry );
1096 RtlLeaveCriticalSection( &processHeap->critSection );
1098 else
1100 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1101 list_init( &processHeap->entry );
1102 /* make sure structure alignment is correct */
1103 assert( (ULONG_PTR)&processHeap->freeList % ALIGNMENT == 0 );
1106 return (HANDLE)subheap->heap;
1110 /***********************************************************************
1111 * RtlDestroyHeap (NTDLL.@)
1113 * Destroy a Heap created with RtlCreateHeap().
1115 * PARAMS
1116 * heap [I] Heap to destroy.
1118 * RETURNS
1119 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1120 * Failure: The Heap handle, if heap is the process heap.
1122 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1124 HEAP *heapPtr = HEAP_GetPtr( heap );
1125 SUBHEAP *subheap, *next;
1126 SIZE_T size;
1127 void *addr;
1129 TRACE("%p\n", heap );
1130 if (!heapPtr) return heap;
1132 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1134 /* remove it from the per-process list */
1135 RtlEnterCriticalSection( &processHeap->critSection );
1136 list_remove( &heapPtr->entry );
1137 RtlLeaveCriticalSection( &processHeap->critSection );
1139 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1140 RtlDeleteCriticalSection( &heapPtr->critSection );
1142 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1144 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1145 list_remove( &subheap->entry );
1146 size = 0;
1147 addr = subheap->base;
1148 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1150 size = 0;
1151 addr = heapPtr->subheap.base;
1152 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1153 return 0;
1157 /***********************************************************************
1158 * RtlAllocateHeap (NTDLL.@)
1160 * Allocate a memory block from a Heap.
1162 * PARAMS
1163 * heap [I] Heap to allocate block from
1164 * flags [I] HEAP_ flags from "winnt.h"
1165 * size [I] Size of the memory block to allocate
1167 * RETURNS
1168 * Success: A pointer to the newly allocated block
1169 * Failure: NULL.
1171 * NOTES
1172 * This call does not SetLastError().
1174 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1176 ARENA_FREE *pArena;
1177 ARENA_INUSE *pInUse;
1178 SUBHEAP *subheap;
1179 HEAP *heapPtr = HEAP_GetPtr( heap );
1180 SIZE_T rounded_size;
1182 /* Validate the parameters */
1184 if (!heapPtr) return NULL;
1185 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1186 flags |= heapPtr->flags;
1187 rounded_size = ROUND_SIZE(size);
1188 if (rounded_size < size) /* overflow */
1190 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1191 return NULL;
1193 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1195 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1196 /* Locate a suitable free block */
1198 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1200 TRACE("(%p,%08x,%08lx): returning NULL\n",
1201 heap, flags, size );
1202 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1203 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1204 return NULL;
1207 /* Remove the arena from the free list */
1209 list_remove( &pArena->entry );
1211 /* Build the in-use arena */
1213 pInUse = (ARENA_INUSE *)pArena;
1215 /* in-use arena is smaller than free arena,
1216 * so we have to add the difference to the size */
1217 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1218 pInUse->magic = ARENA_INUSE_MAGIC;
1220 /* Shrink the block */
1222 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1223 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1225 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1227 if (flags & HEAP_ZERO_MEMORY)
1228 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1229 else
1230 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1232 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1234 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1235 return (LPVOID)(pInUse + 1);
1239 /***********************************************************************
1240 * RtlFreeHeap (NTDLL.@)
1242 * Free a memory block allocated with RtlAllocateHeap().
1244 * PARAMS
1245 * heap [I] Heap that block was allocated from
1246 * flags [I] HEAP_ flags from "winnt.h"
1247 * ptr [I] Block to free
1249 * RETURNS
1250 * Success: TRUE, if ptr is NULL or was freed successfully.
1251 * Failure: FALSE.
1253 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1255 ARENA_INUSE *pInUse;
1256 SUBHEAP *subheap;
1257 HEAP *heapPtr;
1259 /* Validate the parameters */
1261 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1263 heapPtr = HEAP_GetPtr( heap );
1264 if (!heapPtr)
1266 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1267 return FALSE;
1270 flags &= HEAP_NO_SERIALIZE;
1271 flags |= heapPtr->flags;
1272 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1274 /* Some sanity checks */
1276 pInUse = (ARENA_INUSE *)ptr - 1;
1277 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse ))) goto error;
1278 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1279 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1281 /* Turn the block into a free block */
1283 notify_free( ptr );
1285 HEAP_MakeInUseBlockFree( subheap, pInUse );
1287 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1289 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1290 return TRUE;
1292 error:
1293 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1294 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1295 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1296 return FALSE;
1300 /***********************************************************************
1301 * RtlReAllocateHeap (NTDLL.@)
1303 * Change the size of a memory block allocated with RtlAllocateHeap().
1305 * PARAMS
1306 * heap [I] Heap that block was allocated from
1307 * flags [I] HEAP_ flags from "winnt.h"
1308 * ptr [I] Block to resize
1309 * size [I] Size of the memory block to allocate
1311 * RETURNS
1312 * Success: A pointer to the resized block (which may be different).
1313 * Failure: NULL.
1315 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1317 ARENA_INUSE *pArena;
1318 HEAP *heapPtr;
1319 SUBHEAP *subheap;
1320 SIZE_T oldSize, rounded_size;
1322 if (!ptr) return NULL;
1323 if (!(heapPtr = HEAP_GetPtr( heap )))
1325 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1326 return NULL;
1329 /* Validate the parameters */
1331 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1332 HEAP_REALLOC_IN_PLACE_ONLY;
1333 flags |= heapPtr->flags;
1334 rounded_size = ROUND_SIZE(size);
1335 if (rounded_size < size) /* overflow */
1337 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1338 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1339 return NULL;
1341 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1343 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1345 pArena = (ARENA_INUSE *)ptr - 1;
1346 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena ))) goto error;
1347 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1348 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1350 /* Check if we need to grow the block */
1352 oldSize = (pArena->size & ARENA_SIZE_MASK);
1353 if (rounded_size > oldSize)
1355 char *pNext = (char *)(pArena + 1) + oldSize;
1356 if ((pNext < (char *)subheap->base + subheap->size) &&
1357 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1358 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1360 /* The next block is free and large enough */
1361 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1362 list_remove( &pFree->entry );
1363 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1364 if (!HEAP_Commit( subheap, pArena, rounded_size ))
1366 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1367 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1368 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1369 return NULL;
1371 notify_free( pArena + 1 );
1372 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1373 notify_alloc( pArena + 1, size, FALSE );
1374 /* FIXME: this is wrong as we may lose old VBits settings */
1375 mark_block_initialized( pArena + 1, oldSize );
1377 else /* Do it the hard way */
1379 ARENA_FREE *pNew;
1380 ARENA_INUSE *pInUse;
1381 SUBHEAP *newsubheap;
1383 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1384 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1386 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1387 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1388 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1389 return NULL;
1392 /* Build the in-use arena */
1394 list_remove( &pNew->entry );
1395 pInUse = (ARENA_INUSE *)pNew;
1396 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1397 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1398 pInUse->magic = ARENA_INUSE_MAGIC;
1399 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1400 mark_block_initialized( pInUse + 1, oldSize );
1401 notify_alloc( pInUse + 1, size, FALSE );
1402 memcpy( pInUse + 1, pArena + 1, oldSize );
1404 /* Free the previous block */
1406 notify_free( pArena + 1 );
1407 HEAP_MakeInUseBlockFree( subheap, pArena );
1408 subheap = newsubheap;
1409 pArena = pInUse;
1412 else
1414 /* Shrink the block */
1415 notify_free( pArena + 1 );
1416 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1417 notify_alloc( pArena + 1, size, FALSE );
1418 /* FIXME: this is wrong as we may lose old VBits settings */
1419 mark_block_initialized( pArena + 1, size );
1422 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1424 /* Clear the extra bytes if needed */
1426 if (rounded_size > oldSize)
1428 if (flags & HEAP_ZERO_MEMORY)
1429 clear_block( (char *)(pArena + 1) + oldSize,
1430 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1431 else
1432 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1433 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1436 /* Return the new arena */
1438 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1440 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1441 return (LPVOID)(pArena + 1);
1443 error:
1444 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1445 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1446 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1447 return NULL;
1451 /***********************************************************************
1452 * RtlCompactHeap (NTDLL.@)
1454 * Compact the free space in a Heap.
1456 * PARAMS
1457 * heap [I] Heap that block was allocated from
1458 * flags [I] HEAP_ flags from "winnt.h"
1460 * RETURNS
1461 * The number of bytes compacted.
1463 * NOTES
1464 * This function is a harmless stub.
1466 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1468 static BOOL reported;
1469 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1470 return 0;
1474 /***********************************************************************
1475 * RtlLockHeap (NTDLL.@)
1477 * Lock a Heap.
1479 * PARAMS
1480 * heap [I] Heap to lock
1482 * RETURNS
1483 * Success: TRUE. The Heap is locked.
1484 * Failure: FALSE, if heap is invalid.
1486 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1488 HEAP *heapPtr = HEAP_GetPtr( heap );
1489 if (!heapPtr) return FALSE;
1490 RtlEnterCriticalSection( &heapPtr->critSection );
1491 return TRUE;
1495 /***********************************************************************
1496 * RtlUnlockHeap (NTDLL.@)
1498 * Unlock a Heap.
1500 * PARAMS
1501 * heap [I] Heap to unlock
1503 * RETURNS
1504 * Success: TRUE. The Heap is unlocked.
1505 * Failure: FALSE, if heap is invalid.
1507 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1509 HEAP *heapPtr = HEAP_GetPtr( heap );
1510 if (!heapPtr) return FALSE;
1511 RtlLeaveCriticalSection( &heapPtr->critSection );
1512 return TRUE;
1516 /***********************************************************************
1517 * RtlSizeHeap (NTDLL.@)
1519 * Get the actual size of a memory block allocated from a Heap.
1521 * PARAMS
1522 * heap [I] Heap that block was allocated from
1523 * flags [I] HEAP_ flags from "winnt.h"
1524 * ptr [I] Block to get the size of
1526 * RETURNS
1527 * Success: The size of the block.
1528 * Failure: -1, heap or ptr are invalid.
1530 * NOTES
1531 * The size may be bigger than what was passed to RtlAllocateHeap().
1533 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1535 SIZE_T ret;
1536 HEAP *heapPtr = HEAP_GetPtr( heap );
1538 if (!heapPtr)
1540 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1541 return ~0UL;
1543 flags &= HEAP_NO_SERIALIZE;
1544 flags |= heapPtr->flags;
1545 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1546 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1548 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1549 ret = ~0UL;
1551 else
1553 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1554 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1556 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1558 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1559 return ret;
1563 /***********************************************************************
1564 * RtlValidateHeap (NTDLL.@)
1566 * Determine if a block is a valid allocation from a heap.
1568 * PARAMS
1569 * heap [I] Heap that block was allocated from
1570 * flags [I] HEAP_ flags from "winnt.h"
1571 * ptr [I] Block to check
1573 * RETURNS
1574 * Success: TRUE. The block was allocated from heap.
1575 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1577 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1579 HEAP *heapPtr = HEAP_GetPtr( heap );
1580 if (!heapPtr) return FALSE;
1581 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1585 /***********************************************************************
1586 * RtlWalkHeap (NTDLL.@)
1588 * FIXME
1589 * The PROCESS_HEAP_ENTRY flag values seem different between this
1590 * function and HeapWalk(). To be checked.
1592 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1594 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1595 HEAP *heapPtr = HEAP_GetPtr(heap);
1596 SUBHEAP *sub, *currentheap = NULL;
1597 NTSTATUS ret;
1598 char *ptr;
1599 int region_index = 0;
1601 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1603 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1605 /* set ptr to the next arena to be examined */
1607 if (!entry->lpData) /* first call (init) ? */
1609 TRACE("begin walking of heap %p.\n", heap);
1610 currentheap = &heapPtr->subheap;
1611 ptr = (char*)currentheap->base + currentheap->headerSize;
1613 else
1615 ptr = entry->lpData;
1616 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1618 if (((char *)ptr >= (char *)sub->base) &&
1619 ((char *)ptr < (char *)sub->base + sub->size))
1621 currentheap = sub;
1622 break;
1624 region_index++;
1626 if (currentheap == NULL)
1628 ERR("no matching subheap found, shouldn't happen !\n");
1629 ret = STATUS_NO_MORE_ENTRIES;
1630 goto HW_end;
1633 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1635 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1636 ptr += pArena->size & ARENA_SIZE_MASK;
1638 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1640 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1641 ptr += pArena->size & ARENA_SIZE_MASK;
1643 else
1644 ptr += entry->cbData; /* point to next arena */
1646 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1647 { /* proceed with next subheap */
1648 struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
1649 if (!next)
1650 { /* successfully finished */
1651 TRACE("end reached.\n");
1652 ret = STATUS_NO_MORE_ENTRIES;
1653 goto HW_end;
1655 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1656 ptr = (char *)currentheap->base + currentheap->headerSize;
1660 entry->wFlags = 0;
1661 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1663 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1665 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1667 entry->lpData = pArena + 1;
1668 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1669 entry->cbOverhead = sizeof(ARENA_FREE);
1670 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1672 else
1674 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1676 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1678 entry->lpData = pArena + 1;
1679 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1680 entry->cbOverhead = sizeof(ARENA_INUSE);
1681 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1682 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1683 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1686 entry->iRegionIndex = region_index;
1688 /* first element of heap ? */
1689 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1691 entry->wFlags |= PROCESS_HEAP_REGION;
1692 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1693 entry->u.Region.dwUnCommittedSize =
1694 currentheap->size - currentheap->commitSize;
1695 entry->u.Region.lpFirstBlock = /* first valid block */
1696 (char *)currentheap->base + currentheap->headerSize;
1697 entry->u.Region.lpLastBlock = /* first invalid block */
1698 (char *)currentheap->base + currentheap->size;
1700 ret = STATUS_SUCCESS;
1701 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1703 HW_end:
1704 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1705 return ret;
1709 /***********************************************************************
1710 * RtlGetProcessHeaps (NTDLL.@)
1712 * Get the Heaps belonging to the current process.
1714 * PARAMS
1715 * count [I] size of heaps
1716 * heaps [O] Destination array for heap HANDLE's
1718 * RETURNS
1719 * Success: The number of Heaps allocated by the process.
1720 * Failure: 0.
1722 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1724 ULONG total = 1; /* main heap */
1725 struct list *ptr;
1727 RtlEnterCriticalSection( &processHeap->critSection );
1728 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1729 if (total <= count)
1731 *heaps++ = processHeap;
1732 LIST_FOR_EACH( ptr, &processHeap->entry )
1733 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1735 RtlLeaveCriticalSection( &processHeap->critSection );
1736 return total;