winepulse v18: Latency and compilation improvements
[wine/multimedia.git] / dlls / ntdll / heap.c
bloba9044714f86b3bef1e780a96549b004047651634
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 #else
33 #define RUNNING_ON_VALGRIND 0
34 #endif
36 #define NONAMELESSUNION
37 #define NONAMELESSSTRUCT
38 #include "ntstatus.h"
39 #define WIN32_NO_STATUS
40 #include "windef.h"
41 #include "winnt.h"
42 #include "winternl.h"
43 #include "wine/list.h"
44 #include "wine/debug.h"
45 #include "wine/server.h"
47 WINE_DEFAULT_DEBUG_CHANNEL(heap);
49 /* Note: the heap data structures are loosely based on what Pietrek describes in his
50 * book 'Windows 95 System Programming Secrets', with some adaptations for
51 * better compatibility with NT.
54 typedef struct tagARENA_INUSE
56 DWORD size; /* Block size; must be the first field */
57 DWORD magic : 24; /* Magic number */
58 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) */
59 } ARENA_INUSE;
61 typedef struct tagARENA_FREE
63 DWORD size; /* Block size; must be the first field */
64 DWORD magic; /* Magic number */
65 struct list entry; /* Entry in free list */
66 } ARENA_FREE;
68 typedef struct
70 struct list entry; /* entry in heap large blocks list */
71 SIZE_T data_size; /* size of user data */
72 SIZE_T block_size; /* total size of virtual memory block */
73 DWORD pad[2]; /* padding to ensure 16-byte alignment of data */
74 DWORD size; /* fields for compatibility with normal arenas */
75 DWORD magic; /* these must remain at the end of the structure */
76 } ARENA_LARGE;
78 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
79 #define ARENA_FLAG_PREV_FREE 0x00000002
80 #define ARENA_SIZE_MASK (~3)
81 #define ARENA_LARGE_SIZE 0xfedcba90 /* magic value for 'size' field in large blocks */
83 /* Value for arena 'magic' field */
84 #define ARENA_INUSE_MAGIC 0x455355
85 #define ARENA_PENDING_MAGIC 0xbedead
86 #define ARENA_FREE_MAGIC 0x45455246
87 #define ARENA_LARGE_MAGIC 0x6752614c
89 #define ARENA_INUSE_FILLER 0x55
90 #define ARENA_TAIL_FILLER 0xab
91 #define ARENA_FREE_FILLER 0xfeeefeee
93 /* everything is aligned on 8 byte boundaries (16 for Win64) */
94 #define ALIGNMENT (2*sizeof(void*))
95 #define LARGE_ALIGNMENT 16 /* large blocks have stricter alignment */
96 #define ARENA_OFFSET (ALIGNMENT - sizeof(ARENA_INUSE))
98 C_ASSERT( sizeof(ARENA_LARGE) % LARGE_ALIGNMENT == 0 );
100 #define ROUND_SIZE(size) ((((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1)) + ARENA_OFFSET)
102 #define QUIET 1 /* Suppress messages */
103 #define NOISY 0 /* Report all errors */
105 /* minimum data size (without arenas) of an allocated block */
106 /* make sure that it's larger than a free list entry */
107 #define HEAP_MIN_DATA_SIZE ROUND_SIZE(2 * sizeof(struct list))
108 /* minimum size that must remain to shrink an allocated block */
109 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
110 /* minimum size to start allocating large blocks */
111 #define HEAP_MIN_LARGE_BLOCK_SIZE 0x7f000
112 /* extra size to add at the end of block for tail checking */
113 #define HEAP_TAIL_EXTRA_SIZE(flags) \
114 ((flags & HEAP_TAIL_CHECKING_ENABLED) || RUNNING_ON_VALGRIND ? ALIGNMENT : 0)
116 /* Max size of the blocks on the free lists */
117 static const SIZE_T HEAP_freeListSizes[] =
119 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
121 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
123 typedef union
125 ARENA_FREE arena;
126 void *alignment[4];
127 } FREE_LIST_ENTRY;
129 struct tagHEAP;
131 typedef struct tagSUBHEAP
133 void *base; /* Base address of the sub-heap memory block */
134 SIZE_T size; /* Size of the whole sub-heap */
135 SIZE_T min_commit; /* Minimum committed size */
136 SIZE_T commitSize; /* Committed size of the sub-heap */
137 struct list entry; /* Entry in sub-heap list */
138 struct tagHEAP *heap; /* Main heap structure */
139 DWORD headerSize; /* Size of the heap header */
140 DWORD magic; /* Magic number */
141 } SUBHEAP;
143 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
145 typedef struct tagHEAP
147 DWORD_PTR unknown1[2];
148 DWORD unknown2;
149 DWORD flags; /* Heap flags */
150 DWORD force_flags; /* Forced heap flags for debugging */
151 SUBHEAP subheap; /* First sub-heap */
152 struct list entry; /* Entry in process heap list */
153 struct list subheap_list; /* Sub-heap list */
154 struct list large_list; /* Large blocks list */
155 SIZE_T grow_size; /* Size of next subheap for growing heap */
156 DWORD magic; /* Magic number */
157 DWORD pending_pos; /* Position in pending free requests ring */
158 ARENA_INUSE **pending_free; /* Ring buffer for pending free requests */
159 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
160 FREE_LIST_ENTRY *freeList; /* Free lists */
161 } HEAP;
163 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
165 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
166 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
167 #define MAX_FREE_PENDING 1024 /* max number of free requests to delay */
169 /* some undocumented flags (names are made up) */
170 #define HEAP_PAGE_ALLOCS 0x01000000
171 #define HEAP_VALIDATE 0x10000000
172 #define HEAP_VALIDATE_ALL 0x20000000
173 #define HEAP_VALIDATE_PARAMS 0x40000000
175 static HEAP *processHeap; /* main process heap */
177 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
179 /* mark a block of memory as free for debugging purposes */
180 static inline void mark_block_free( void *ptr, SIZE_T size, DWORD flags )
182 if (flags & HEAP_FREE_CHECKING_ENABLED)
184 SIZE_T i;
185 for (i = 0; i < size / sizeof(DWORD); i++) ((DWORD *)ptr)[i] = ARENA_FREE_FILLER;
187 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
188 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
189 #elif defined( VALGRIND_MAKE_NOACCESS)
190 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
191 #endif
194 /* mark a block of memory as initialized for debugging purposes */
195 static inline void mark_block_initialized( void *ptr, SIZE_T size )
197 #if defined(VALGRIND_MAKE_MEM_DEFINED)
198 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
199 #elif defined(VALGRIND_MAKE_READABLE)
200 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
201 #endif
204 /* mark a block of memory as uninitialized for debugging purposes */
205 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
207 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
208 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
209 #elif defined(VALGRIND_MAKE_WRITABLE)
210 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
211 #endif
214 /* mark a block of memory as a tail block */
215 static inline void mark_block_tail( void *ptr, SIZE_T size, DWORD flags )
217 if (flags & HEAP_TAIL_CHECKING_ENABLED)
219 mark_block_uninitialized( ptr, size );
220 memset( ptr, ARENA_TAIL_FILLER, size );
222 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
223 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
224 #elif defined( VALGRIND_MAKE_NOACCESS)
225 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
226 #endif
229 /* initialize contents of a newly created block of memory */
230 static inline void initialize_block( void *ptr, SIZE_T size, SIZE_T unused, DWORD flags )
232 if (flags & HEAP_ZERO_MEMORY)
234 mark_block_initialized( ptr, size );
235 memset( ptr, 0, size );
237 else
239 mark_block_uninitialized( ptr, size );
240 if (flags & HEAP_FREE_CHECKING_ENABLED)
242 memset( ptr, ARENA_INUSE_FILLER, size );
243 mark_block_uninitialized( ptr, size );
247 mark_block_tail( (char *)ptr + size, unused, flags );
250 /* notify that a new block of memory has been allocated for debugging purposes */
251 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
253 #ifdef VALGRIND_MALLOCLIKE_BLOCK
254 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
255 #endif
258 /* notify that a block of memory has been freed for debugging purposes */
259 static inline void notify_free( void const *ptr )
261 #ifdef VALGRIND_FREELIKE_BLOCK
262 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
263 #endif
266 static inline void notify_realloc( void const *ptr, SIZE_T size_old, SIZE_T size_new )
268 #ifdef VALGRIND_RESIZEINPLACE_BLOCK
269 VALGRIND_RESIZEINPLACE_BLOCK( ptr, size_old, size_new, 0 );
270 #endif
273 static void subheap_notify_free_all(SUBHEAP const *subheap)
275 #ifdef VALGRIND_FREELIKE_BLOCK
276 char const *ptr = (char const *)subheap->base + subheap->headerSize;
278 if (!RUNNING_ON_VALGRIND) return;
280 while (ptr < (char const *)subheap->base + subheap->size)
282 if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
284 ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
285 if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
286 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
288 else
290 ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
291 if (pArena->magic == ARENA_INUSE_MAGIC) notify_free(pArena + 1);
292 else if (pArena->magic != ARENA_PENDING_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
293 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
296 #endif
299 /* locate a free list entry of the appropriate size */
300 /* size is the size of the whole block including the arena header */
301 static inline unsigned int get_freelist_index( SIZE_T size )
303 unsigned int i;
305 size -= sizeof(ARENA_FREE);
306 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
307 return i;
310 /* get the memory protection type to use for a given heap */
311 static inline ULONG get_protection_type( DWORD flags )
313 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
316 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
318 0, 0, NULL, /* will be set later */
319 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
320 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
324 /***********************************************************************
325 * HEAP_Dump
327 static void HEAP_Dump( HEAP *heap )
329 unsigned int i;
330 SUBHEAP *subheap;
331 char *ptr;
333 DPRINTF( "Heap: %p\n", heap );
334 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
335 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
337 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
338 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
339 DPRINTF( "%p free %08lx prev=%p next=%p\n",
340 &heap->freeList[i].arena, HEAP_freeListSizes[i],
341 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
342 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
344 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
346 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
347 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
348 subheap, subheap->base, subheap->size, subheap->commitSize );
350 DPRINTF( "\n Block Arena Stat Size Id\n" );
351 ptr = (char *)subheap->base + subheap->headerSize;
352 while (ptr < (char *)subheap->base + subheap->size)
354 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
356 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
357 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
358 pArena, pArena->magic,
359 pArena->size & ARENA_SIZE_MASK,
360 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
361 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
362 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
363 arenaSize += sizeof(ARENA_FREE);
364 freeSize += pArena->size & ARENA_SIZE_MASK;
366 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
368 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
369 DPRINTF( "%p %08x Used %08x back=%p\n",
370 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
371 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
372 arenaSize += sizeof(ARENA_INUSE);
373 usedSize += pArena->size & ARENA_SIZE_MASK;
375 else
377 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
378 DPRINTF( "%p %08x %s %08x\n",
379 pArena, pArena->magic, pArena->magic == ARENA_INUSE_MAGIC ? "used" : "pend",
380 pArena->size & ARENA_SIZE_MASK );
381 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
382 arenaSize += sizeof(ARENA_INUSE);
383 usedSize += pArena->size & ARENA_SIZE_MASK;
386 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
387 subheap->size, subheap->commitSize, freeSize, usedSize,
388 arenaSize, (arenaSize * 100) / subheap->size );
393 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
395 WORD rem_flags;
396 TRACE( "Dumping entry %p\n", entry );
397 TRACE( "lpData\t\t: %p\n", entry->lpData );
398 TRACE( "cbData\t\t: %08x\n", entry->cbData);
399 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
400 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
401 TRACE( "WFlags\t\t: ");
402 if (entry->wFlags & PROCESS_HEAP_REGION)
403 TRACE( "PROCESS_HEAP_REGION ");
404 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
405 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
406 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
407 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
408 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
409 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
410 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
411 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
412 rem_flags = entry->wFlags &
413 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
414 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
415 PROCESS_HEAP_ENTRY_DDESHARE);
416 if (rem_flags)
417 TRACE( "Unknown %08x", rem_flags);
418 TRACE( "\n");
419 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
420 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
422 /* Treat as block */
423 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
425 if (entry->wFlags & PROCESS_HEAP_REGION)
427 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
428 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
429 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
430 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
434 /***********************************************************************
435 * HEAP_GetPtr
436 * RETURNS
437 * Pointer to the heap
438 * NULL: Failure
440 static HEAP *HEAP_GetPtr(
441 HANDLE heap /* [in] Handle to the heap */
443 HEAP *heapPtr = heap;
444 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
446 ERR("Invalid heap %p!\n", heap );
447 return NULL;
449 if ((heapPtr->flags & HEAP_VALIDATE_ALL) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
451 if (TRACE_ON(heap))
453 HEAP_Dump( heapPtr );
454 assert( FALSE );
456 return NULL;
458 return heapPtr;
462 /***********************************************************************
463 * HEAP_InsertFreeBlock
465 * Insert a free block into the free list.
467 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
469 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
470 if (last)
472 /* insert at end of free list, i.e. before the next free list entry */
473 pEntry++;
474 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
475 list_add_before( &pEntry->arena.entry, &pArena->entry );
477 else
479 /* insert at head of free list */
480 list_add_after( &pEntry->arena.entry, &pArena->entry );
482 pArena->size |= ARENA_FLAG_FREE;
486 /***********************************************************************
487 * HEAP_FindSubHeap
488 * Find the sub-heap containing a given address.
490 * RETURNS
491 * Pointer: Success
492 * NULL: Failure
494 static SUBHEAP *HEAP_FindSubHeap(
495 const HEAP *heap, /* [in] Heap pointer */
496 LPCVOID ptr ) /* [in] Address */
498 SUBHEAP *sub;
499 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
500 if ((ptr >= sub->base) &&
501 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
502 return sub;
503 return NULL;
507 /***********************************************************************
508 * HEAP_Commit
510 * Make sure the heap storage is committed for a given size in the specified arena.
512 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
514 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
515 SIZE_T size = (char *)ptr - (char *)subheap->base;
516 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
517 if (size > subheap->size) size = subheap->size;
518 if (size <= subheap->commitSize) return TRUE;
519 size -= subheap->commitSize;
520 ptr = (char *)subheap->base + subheap->commitSize;
521 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
522 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
524 WARN("Could not commit %08lx bytes at %p for heap %p\n",
525 size, ptr, subheap->heap );
526 return FALSE;
528 subheap->commitSize += size;
529 return TRUE;
533 /***********************************************************************
534 * HEAP_Decommit
536 * If possible, decommit the heap storage from (including) 'ptr'.
538 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
540 void *addr;
541 SIZE_T decommit_size;
542 SIZE_T size = (char *)ptr - (char *)subheap->base;
544 /* round to next block and add one full block */
545 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
546 size = max( size, subheap->min_commit );
547 if (size >= subheap->commitSize) return TRUE;
548 decommit_size = subheap->commitSize - size;
549 addr = (char *)subheap->base + size;
551 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
553 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
554 decommit_size, (char *)subheap->base + size, subheap->heap );
555 return FALSE;
557 subheap->commitSize -= decommit_size;
558 return TRUE;
562 /***********************************************************************
563 * HEAP_CreateFreeBlock
565 * Create a free block at a specified address. 'size' is the size of the
566 * whole block, including the new arena.
568 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
570 ARENA_FREE *pFree;
571 char *pEnd;
572 BOOL last;
573 DWORD flags = subheap->heap->flags;
575 /* Create a free arena */
576 mark_block_uninitialized( ptr, sizeof(ARENA_FREE) );
577 pFree = ptr;
578 pFree->magic = ARENA_FREE_MAGIC;
580 /* If debugging, erase the freed block content */
582 pEnd = (char *)ptr + size;
583 if (pEnd > (char *)subheap->base + subheap->commitSize)
584 pEnd = (char *)subheap->base + subheap->commitSize;
585 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1), flags );
587 /* Check if next block is free also */
589 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
590 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
592 /* Remove the next arena from the free list */
593 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
594 list_remove( &pNext->entry );
595 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
596 mark_block_free( pNext, sizeof(ARENA_FREE), flags );
599 /* Set the next block PREV_FREE flag and pointer */
601 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
602 if (!last)
604 DWORD *pNext = (DWORD *)((char *)ptr + size);
605 *pNext |= ARENA_FLAG_PREV_FREE;
606 mark_block_initialized( (ARENA_FREE **)pNext - 1, sizeof( ARENA_FREE * ) );
607 *((ARENA_FREE **)pNext - 1) = pFree;
610 /* Last, insert the new block into the free list */
612 pFree->size = size - sizeof(*pFree);
613 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
617 /***********************************************************************
618 * HEAP_MakeInUseBlockFree
620 * Turn an in-use block into a free block. Can also decommit the end of
621 * the heap, and possibly even free the sub-heap altogether.
623 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
625 HEAP *heap = subheap->heap;
626 ARENA_FREE *pFree;
627 SIZE_T size;
629 if (heap->pending_free)
631 ARENA_INUSE *prev = heap->pending_free[heap->pending_pos];
632 heap->pending_free[heap->pending_pos] = pArena;
633 heap->pending_pos = (heap->pending_pos + 1) % MAX_FREE_PENDING;
634 pArena->magic = ARENA_PENDING_MAGIC;
635 mark_block_free( pArena + 1, pArena->size & ARENA_SIZE_MASK, heap->flags );
636 if (!prev) return;
637 pArena = prev;
638 subheap = HEAP_FindSubHeap( heap, pArena );
641 /* Check if we can merge with previous block */
643 size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
644 if (pArena->size & ARENA_FLAG_PREV_FREE)
646 pFree = *((ARENA_FREE **)pArena - 1);
647 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
648 /* Remove it from the free list */
649 list_remove( &pFree->entry );
651 else pFree = (ARENA_FREE *)pArena;
653 /* Create a free block */
655 HEAP_CreateFreeBlock( subheap, pFree, size );
656 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
657 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
658 return; /* Not the last block, so nothing more to do */
660 /* Free the whole sub-heap if it's empty and not the original one */
662 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
663 (subheap != &subheap->heap->subheap))
665 void *addr = subheap->base;
667 size = 0;
668 /* Remove the free block from the list */
669 list_remove( &pFree->entry );
670 /* Remove the subheap from the list */
671 list_remove( &subheap->entry );
672 /* Free the memory */
673 subheap->magic = 0;
674 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
675 return;
678 /* Decommit the end of the heap */
680 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
684 /***********************************************************************
685 * HEAP_ShrinkBlock
687 * Shrink an in-use block.
689 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
691 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
693 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
694 (pArena->size & ARENA_SIZE_MASK) - size );
695 /* assign size plus previous arena flags */
696 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
698 else
700 /* Turn off PREV_FREE flag in next block */
701 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
702 if (pNext < (char *)subheap->base + subheap->size)
703 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
708 /***********************************************************************
709 * allocate_large_block
711 static void *allocate_large_block( HEAP *heap, DWORD flags, SIZE_T size )
713 ARENA_LARGE *arena;
714 SIZE_T block_size = sizeof(*arena) + ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE(flags);
715 LPVOID address = NULL;
717 if (block_size < size) return NULL; /* overflow */
718 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 5,
719 &block_size, MEM_COMMIT, get_protection_type( flags ) ))
721 WARN("Could not allocate block for %08lx bytes\n", size );
722 return NULL;
724 arena = address;
725 arena->data_size = size;
726 arena->block_size = block_size;
727 arena->size = ARENA_LARGE_SIZE;
728 arena->magic = ARENA_LARGE_MAGIC;
729 mark_block_tail( (char *)(arena + 1) + size, block_size - sizeof(*arena) - size, flags );
730 list_add_tail( &heap->large_list, &arena->entry );
731 notify_alloc( arena + 1, size, flags & HEAP_ZERO_MEMORY );
732 return arena + 1;
736 /***********************************************************************
737 * free_large_block
739 static void free_large_block( HEAP *heap, DWORD flags, void *ptr )
741 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
742 LPVOID address = arena;
743 SIZE_T size = 0;
745 list_remove( &arena->entry );
746 NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
750 /***********************************************************************
751 * realloc_large_block
753 static void *realloc_large_block( HEAP *heap, DWORD flags, void *ptr, SIZE_T size )
755 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
756 void *new_ptr;
758 if (arena->block_size - sizeof(*arena) >= size)
760 SIZE_T unused = arena->block_size - sizeof(*arena) - size;
762 /* FIXME: we could remap zero-pages instead */
763 #ifdef VALGRIND_RESIZEINPLACE_BLOCK
764 if (RUNNING_ON_VALGRIND)
765 notify_realloc( arena + 1, arena->data_size, size );
766 else
767 #endif
768 if (size > arena->data_size)
769 initialize_block( (char *)ptr + arena->data_size, size - arena->data_size, unused, flags );
770 else
771 mark_block_tail( (char *)ptr + size, unused, flags );
772 arena->data_size = size;
773 return ptr;
775 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) return NULL;
776 if (!(new_ptr = allocate_large_block( heap, flags, size )))
778 WARN("Could not allocate block for %08lx bytes\n", size );
779 return NULL;
781 memcpy( new_ptr, ptr, arena->data_size );
782 free_large_block( heap, flags, ptr );
783 notify_free( ptr );
784 return new_ptr;
788 /***********************************************************************
789 * find_large_block
791 static ARENA_LARGE *find_large_block( HEAP *heap, const void *ptr )
793 ARENA_LARGE *arena;
795 LIST_FOR_EACH_ENTRY( arena, &heap->large_list, ARENA_LARGE, entry )
796 if (ptr == arena + 1) return arena;
798 return NULL;
802 /***********************************************************************
803 * validate_large_arena
805 static BOOL validate_large_arena( HEAP *heap, const ARENA_LARGE *arena, BOOL quiet )
807 DWORD flags = heap->flags;
809 if ((ULONG_PTR)arena % getpagesize())
811 if (quiet == NOISY)
813 ERR( "Heap %p: invalid large arena pointer %p\n", heap, arena );
814 if (TRACE_ON(heap)) HEAP_Dump( heap );
816 else if (WARN_ON(heap))
818 WARN( "Heap %p: unaligned arena pointer %p\n", heap, arena );
819 if (TRACE_ON(heap)) HEAP_Dump( heap );
821 return FALSE;
823 if (arena->size != ARENA_LARGE_SIZE || arena->magic != ARENA_LARGE_MAGIC)
825 if (quiet == NOISY)
827 ERR( "Heap %p: invalid large arena %p values %x/%x\n",
828 heap, arena, arena->size, arena->magic );
829 if (TRACE_ON(heap)) HEAP_Dump( heap );
831 else if (WARN_ON(heap))
833 WARN( "Heap %p: invalid large arena %p values %x/%x\n",
834 heap, arena, arena->size, arena->magic );
835 if (TRACE_ON(heap)) HEAP_Dump( heap );
837 return FALSE;
839 if (arena->data_size > arena->block_size - sizeof(*arena))
841 ERR( "Heap %p: invalid large arena %p size %lx/%lx\n",
842 heap, arena, arena->data_size, arena->block_size );
843 return FALSE;
845 if (flags & HEAP_TAIL_CHECKING_ENABLED)
847 SIZE_T i, unused = arena->block_size - sizeof(*arena) - arena->data_size;
848 const unsigned char *data = (const unsigned char *)(arena + 1) + arena->data_size;
850 for (i = 0; i < unused; i++)
852 if (data[i] == ARENA_TAIL_FILLER) continue;
853 ERR("Heap %p: block %p tail overwritten at %p (byte %lu/%lu == 0x%02x)\n",
854 heap, arena + 1, data + i, i, unused, data[i] );
855 return FALSE;
858 return TRUE;
862 /***********************************************************************
863 * HEAP_CreateSubHeap
865 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, LPVOID address, DWORD flags,
866 SIZE_T commitSize, SIZE_T totalSize )
868 SUBHEAP *subheap;
869 FREE_LIST_ENTRY *pEntry;
870 unsigned int i;
872 if (!address)
874 if (!commitSize) commitSize = COMMIT_MASK + 1;
875 totalSize = min( totalSize, 0xffff0000 ); /* don't allow a heap larger than 4Gb */
876 if (totalSize < commitSize) totalSize = commitSize;
877 if (flags & HEAP_SHARED) commitSize = totalSize; /* always commit everything in a shared heap */
878 commitSize = min( totalSize, (commitSize + COMMIT_MASK) & ~COMMIT_MASK );
880 /* allocate the memory block */
881 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 5, &totalSize,
882 MEM_RESERVE, get_protection_type( flags ) ))
884 WARN("Could not allocate %08lx bytes\n", totalSize );
885 return NULL;
887 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
888 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
890 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
891 return NULL;
895 if (heap)
897 /* If this is a secondary subheap, insert it into list */
899 subheap = address;
900 subheap->base = address;
901 subheap->heap = heap;
902 subheap->size = totalSize;
903 subheap->min_commit = 0x10000;
904 subheap->commitSize = commitSize;
905 subheap->magic = SUBHEAP_MAGIC;
906 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
907 list_add_head( &heap->subheap_list, &subheap->entry );
909 else
911 /* If this is a primary subheap, initialize main heap */
913 heap = address;
914 heap->flags = flags;
915 heap->magic = HEAP_MAGIC;
916 heap->grow_size = max( HEAP_DEF_SIZE, totalSize );
917 list_init( &heap->subheap_list );
918 list_init( &heap->large_list );
920 subheap = &heap->subheap;
921 subheap->base = address;
922 subheap->heap = heap;
923 subheap->size = totalSize;
924 subheap->min_commit = commitSize;
925 subheap->commitSize = commitSize;
926 subheap->magic = SUBHEAP_MAGIC;
927 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
928 list_add_head( &heap->subheap_list, &subheap->entry );
930 /* Build the free lists */
932 heap->freeList = (FREE_LIST_ENTRY *)((char *)heap + subheap->headerSize);
933 subheap->headerSize += HEAP_NB_FREE_LISTS * sizeof(FREE_LIST_ENTRY);
934 list_init( &heap->freeList[0].arena.entry );
935 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
937 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
938 pEntry->arena.magic = ARENA_FREE_MAGIC;
939 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
942 /* Initialize critical section */
944 if (!processHeap) /* do it by hand to avoid memory allocations */
946 heap->critSection.DebugInfo = &process_heap_critsect_debug;
947 heap->critSection.LockCount = -1;
948 heap->critSection.RecursionCount = 0;
949 heap->critSection.OwningThread = 0;
950 heap->critSection.LockSemaphore = 0;
951 heap->critSection.SpinCount = 0;
952 process_heap_critsect_debug.CriticalSection = &heap->critSection;
954 else
956 RtlInitializeCriticalSection( &heap->critSection );
957 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
960 if (flags & HEAP_SHARED)
962 /* let's assume that only one thread at a time will try to do this */
963 HANDLE sem = heap->critSection.LockSemaphore;
964 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
966 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
967 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
968 heap->critSection.LockSemaphore = sem;
969 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
970 heap->critSection.DebugInfo = NULL;
974 /* Create the first free block */
976 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
977 subheap->size - subheap->headerSize );
979 return subheap;
983 /***********************************************************************
984 * HEAP_FindFreeBlock
986 * Find a free block at least as large as the requested size, and make sure
987 * the requested size is committed.
989 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
990 SUBHEAP **ppSubHeap )
992 SUBHEAP *subheap;
993 struct list *ptr;
994 SIZE_T total_size;
995 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
997 /* Find a suitable free list, and in it find a block large enough */
999 ptr = &pEntry->arena.entry;
1000 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
1002 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
1003 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
1004 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1005 if (arena_size >= size)
1007 subheap = HEAP_FindSubHeap( heap, pArena );
1008 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
1009 *ppSubHeap = subheap;
1010 return pArena;
1014 /* If no block was found, attempt to grow the heap */
1016 if (!(heap->flags & HEAP_GROWABLE))
1018 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
1019 return NULL;
1021 /* make sure that we have a big enough size *committed* to fit another
1022 * last free arena in !
1023 * So just one heap struct, one first free arena which will eventually
1024 * get used, and a second free arena that might get assigned all remaining
1025 * free space in HEAP_ShrinkBlock() */
1026 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
1027 if (total_size < size) return NULL; /* overflow */
1029 if ((subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
1030 max( heap->grow_size, total_size ) )))
1032 if (heap->grow_size < 128 * 1024 * 1024) heap->grow_size *= 2;
1034 else while (!subheap) /* shrink the grow size again if we are running out of space */
1036 if (heap->grow_size <= total_size || heap->grow_size <= 4 * 1024 * 1024) return NULL;
1037 heap->grow_size /= 2;
1038 subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
1039 max( heap->grow_size, total_size ) );
1042 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
1043 subheap, subheap->size, heap );
1045 *ppSubHeap = subheap;
1046 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
1050 /***********************************************************************
1051 * HEAP_IsValidArenaPtr
1053 * Check that the pointer is inside the range possible for arenas.
1055 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
1057 unsigned int i;
1058 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
1059 if (!subheap) return FALSE;
1060 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
1061 if (subheap != &heap->subheap) return FALSE;
1062 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
1063 if (ptr == &heap->freeList[i].arena) return TRUE;
1064 return FALSE;
1068 /***********************************************************************
1069 * HEAP_ValidateFreeArena
1071 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
1073 DWORD flags = subheap->heap->flags;
1074 SIZE_T size;
1075 ARENA_FREE *prev, *next;
1076 char *heapEnd = (char *)subheap->base + subheap->size;
1078 /* Check for unaligned pointers */
1079 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1081 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1082 return FALSE;
1085 /* Check magic number */
1086 if (pArena->magic != ARENA_FREE_MAGIC)
1088 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1089 return FALSE;
1091 /* Check size flags */
1092 if (!(pArena->size & ARENA_FLAG_FREE) ||
1093 (pArena->size & ARENA_FLAG_PREV_FREE))
1095 ERR("Heap %p: bad flags %08x for free arena %p\n",
1096 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1097 return FALSE;
1099 /* Check arena size */
1100 size = pArena->size & ARENA_SIZE_MASK;
1101 if ((char *)(pArena + 1) + size > heapEnd)
1103 ERR("Heap %p: bad size %08lx for free arena %p\n", subheap->heap, size, pArena );
1104 return FALSE;
1106 /* Check that next pointer is valid */
1107 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
1108 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
1110 ERR("Heap %p: bad next ptr %p for arena %p\n",
1111 subheap->heap, next, pArena );
1112 return FALSE;
1114 /* Check that next arena is free */
1115 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1117 ERR("Heap %p: next arena %p invalid for %p\n",
1118 subheap->heap, next, pArena );
1119 return FALSE;
1121 /* Check that prev pointer is valid */
1122 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1123 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1125 ERR("Heap %p: bad prev ptr %p for arena %p\n",
1126 subheap->heap, prev, pArena );
1127 return FALSE;
1129 /* Check that prev arena is free */
1130 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1132 /* this often means that the prev arena got overwritten
1133 * by a memory write before that prev arena */
1134 ERR("Heap %p: prev arena %p invalid for %p\n",
1135 subheap->heap, prev, pArena );
1136 return FALSE;
1138 /* Check that next block has PREV_FREE flag */
1139 if ((char *)(pArena + 1) + size < heapEnd)
1141 if (!(*(DWORD *)((char *)(pArena + 1) + size) & ARENA_FLAG_PREV_FREE))
1143 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1144 subheap->heap, pArena );
1145 return FALSE;
1147 /* Check next block back pointer */
1148 if (*((ARENA_FREE **)((char *)(pArena + 1) + size) - 1) != pArena)
1150 ERR("Heap %p: arena %p has wrong back ptr %p\n",
1151 subheap->heap, pArena,
1152 *((ARENA_FREE **)((char *)(pArena+1) + size) - 1));
1153 return FALSE;
1156 if (flags & HEAP_FREE_CHECKING_ENABLED)
1158 DWORD *ptr = (DWORD *)(pArena + 1);
1159 char *end = (char *)(pArena + 1) + size;
1161 if (end >= heapEnd) end = (char *)subheap->base + subheap->commitSize;
1162 else end -= sizeof(ARENA_FREE *);
1163 while (ptr < (DWORD *)end)
1165 if (*ptr != ARENA_FREE_FILLER)
1167 ERR("Heap %p: free block %p overwritten at %p by %08x\n",
1168 subheap->heap, (ARENA_INUSE *)pArena + 1, ptr, *ptr );
1169 return FALSE;
1171 ptr++;
1174 return TRUE;
1178 /***********************************************************************
1179 * HEAP_ValidateInUseArena
1181 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1183 SIZE_T size;
1184 DWORD i, flags = subheap->heap->flags;
1185 const char *heapEnd = (const char *)subheap->base + subheap->size;
1187 /* Check for unaligned pointers */
1188 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1190 if ( quiet == NOISY )
1192 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1193 if ( TRACE_ON(heap) )
1194 HEAP_Dump( subheap->heap );
1196 else if ( WARN_ON(heap) )
1198 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1199 if ( TRACE_ON(heap) )
1200 HEAP_Dump( subheap->heap );
1202 return FALSE;
1205 /* Check magic number */
1206 if (pArena->magic != ARENA_INUSE_MAGIC && pArena->magic != ARENA_PENDING_MAGIC)
1208 if (quiet == NOISY) {
1209 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1210 if (TRACE_ON(heap))
1211 HEAP_Dump( subheap->heap );
1212 } else if (WARN_ON(heap)) {
1213 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1214 if (TRACE_ON(heap))
1215 HEAP_Dump( subheap->heap );
1217 return FALSE;
1219 /* Check size flags */
1220 if (pArena->size & ARENA_FLAG_FREE)
1222 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1223 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1224 return FALSE;
1226 /* Check arena size */
1227 size = pArena->size & ARENA_SIZE_MASK;
1228 if ((const char *)(pArena + 1) + size > heapEnd ||
1229 (const char *)(pArena + 1) + size < (const char *)(pArena + 1))
1231 ERR("Heap %p: bad size %08lx for in-use arena %p\n", subheap->heap, size, pArena );
1232 return FALSE;
1234 /* Check next arena PREV_FREE flag */
1235 if (((const char *)(pArena + 1) + size < heapEnd) &&
1236 (*(const DWORD *)((const char *)(pArena + 1) + size) & ARENA_FLAG_PREV_FREE))
1238 ERR("Heap %p: in-use arena %p next block %p has PREV_FREE flag %x\n",
1239 subheap->heap, pArena, (const char *)(pArena + 1) + size,*(const DWORD *)((const char *)(pArena + 1) + size) );
1240 return FALSE;
1242 /* Check prev free arena */
1243 if (pArena->size & ARENA_FLAG_PREV_FREE)
1245 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1246 /* Check prev pointer */
1247 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1249 ERR("Heap %p: bad back ptr %p for arena %p\n",
1250 subheap->heap, pPrev, pArena );
1251 return FALSE;
1253 /* Check that prev arena is free */
1254 if (!(pPrev->size & ARENA_FLAG_FREE) ||
1255 (pPrev->magic != ARENA_FREE_MAGIC))
1257 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1258 subheap->heap, pPrev, pArena );
1259 return FALSE;
1261 /* Check that prev arena is really the previous block */
1262 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1264 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1265 subheap->heap, pPrev, pArena );
1266 return FALSE;
1269 /* Check unused size */
1270 if (pArena->unused_bytes > size)
1272 ERR("Heap %p: invalid unused size %08x/%08lx\n", subheap->heap, pArena->unused_bytes, size );
1273 return FALSE;
1275 /* Check unused bytes */
1276 if (pArena->magic == ARENA_PENDING_MAGIC)
1278 const DWORD *ptr = (const DWORD *)(pArena + 1);
1279 const DWORD *end = (const DWORD *)((const char *)ptr + size);
1281 while (ptr < end)
1283 if (*ptr != ARENA_FREE_FILLER)
1285 ERR("Heap %p: free block %p overwritten at %p by %08x\n",
1286 subheap->heap, (const ARENA_INUSE *)pArena + 1, ptr, *ptr );
1287 if (!*ptr) { HEAP_Dump( subheap->heap ); DbgBreakPoint(); }
1288 return FALSE;
1290 ptr++;
1293 else if (flags & HEAP_TAIL_CHECKING_ENABLED)
1295 const unsigned char *data = (const unsigned char *)(pArena + 1) + size - pArena->unused_bytes;
1297 for (i = 0; i < pArena->unused_bytes; i++)
1299 if (data[i] == ARENA_TAIL_FILLER) continue;
1300 ERR("Heap %p: block %p tail overwritten at %p (byte %u/%u == 0x%02x)\n",
1301 subheap->heap, pArena + 1, data + i, i, pArena->unused_bytes, data[i] );
1302 return FALSE;
1305 return TRUE;
1309 /***********************************************************************
1310 * HEAP_IsRealArena [Internal]
1311 * Validates a block is a valid arena.
1313 * RETURNS
1314 * TRUE: Success
1315 * FALSE: Failure
1317 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1318 DWORD flags, /* [in] Bit flags that control access during operation */
1319 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1320 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1321 * does not complain */
1323 SUBHEAP *subheap;
1324 BOOL ret = TRUE;
1325 const ARENA_LARGE *large_arena;
1327 flags &= HEAP_NO_SERIALIZE;
1328 flags |= heapPtr->flags;
1329 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1330 if (!(flags & HEAP_NO_SERIALIZE))
1331 RtlEnterCriticalSection( &heapPtr->critSection );
1333 if (block) /* only check this single memory block */
1335 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1337 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1338 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1340 if (!(large_arena = find_large_block( heapPtr, block )))
1342 if (quiet == NOISY)
1343 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1344 else if (WARN_ON(heap))
1345 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1346 ret = FALSE;
1348 else
1349 ret = validate_large_arena( heapPtr, large_arena, quiet );
1350 } else
1351 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1353 if (!(flags & HEAP_NO_SERIALIZE))
1354 RtlLeaveCriticalSection( &heapPtr->critSection );
1355 return ret;
1358 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1360 char *ptr = (char *)subheap->base + subheap->headerSize;
1361 while (ptr < (char *)subheap->base + subheap->size)
1363 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1365 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1366 ret = FALSE;
1367 break;
1369 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1371 else
1373 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1374 ret = FALSE;
1375 break;
1377 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1380 if (!ret) break;
1383 LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1384 if (!(ret = validate_large_arena( heapPtr, large_arena, quiet ))) break;
1386 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1387 return ret;
1391 /***********************************************************************
1392 * validate_block_pointer
1394 * Minimum validation needed to catch bad parameters in heap functions.
1396 static BOOL validate_block_pointer( HEAP *heap, SUBHEAP **ret_subheap, const ARENA_INUSE *arena )
1398 SUBHEAP *subheap;
1399 BOOL ret = FALSE;
1401 if (!(*ret_subheap = subheap = HEAP_FindSubHeap( heap, arena )))
1403 ARENA_LARGE *large_arena = find_large_block( heap, arena + 1 );
1405 if (!large_arena)
1407 WARN( "Heap %p: pointer %p is not inside heap\n", heap, arena + 1 );
1408 return FALSE;
1410 if ((heap->flags & HEAP_VALIDATE) && !validate_large_arena( heap, large_arena, QUIET ))
1411 return FALSE;
1412 return TRUE;
1415 if ((const char *)arena < (char *)subheap->base + subheap->headerSize)
1416 WARN( "Heap %p: pointer %p is inside subheap %p header\n", subheap->heap, arena + 1, subheap );
1417 else if (subheap->heap->flags & HEAP_VALIDATE) /* do the full validation */
1418 ret = HEAP_ValidateInUseArena( subheap, arena, QUIET );
1419 else if ((ULONG_PTR)arena % ALIGNMENT != ARENA_OFFSET)
1420 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, arena );
1421 else if (arena->magic == ARENA_PENDING_MAGIC)
1422 WARN( "Heap %p: block %p used after free\n", subheap->heap, arena + 1 );
1423 else if (arena->magic != ARENA_INUSE_MAGIC)
1424 WARN( "Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, arena->magic, arena );
1425 else if (arena->size & ARENA_FLAG_FREE)
1426 ERR( "Heap %p: bad flags %08x for in-use arena %p\n",
1427 subheap->heap, arena->size & ~ARENA_SIZE_MASK, arena );
1428 else if ((const char *)(arena + 1) + (arena->size & ARENA_SIZE_MASK) > (const char *)subheap->base + subheap->size ||
1429 (const char *)(arena + 1) + (arena->size & ARENA_SIZE_MASK) < (const char *)(arena + 1))
1430 ERR( "Heap %p: bad size %08x for in-use arena %p\n",
1431 subheap->heap, arena->size & ARENA_SIZE_MASK, arena );
1432 else
1433 ret = TRUE;
1435 return ret;
1439 /***********************************************************************
1440 * heap_set_debug_flags
1442 void heap_set_debug_flags( HANDLE handle )
1444 HEAP *heap = HEAP_GetPtr( handle );
1445 ULONG global_flags = RtlGetNtGlobalFlags();
1446 ULONG flags = 0;
1448 if (TRACE_ON(heap)) global_flags |= FLG_HEAP_VALIDATE_ALL;
1449 if (WARN_ON(heap)) global_flags |= FLG_HEAP_VALIDATE_PARAMETERS;
1451 if (global_flags & FLG_HEAP_ENABLE_TAIL_CHECK) flags |= HEAP_TAIL_CHECKING_ENABLED;
1452 if (global_flags & FLG_HEAP_ENABLE_FREE_CHECK) flags |= HEAP_FREE_CHECKING_ENABLED;
1453 if (global_flags & FLG_HEAP_DISABLE_COALESCING) flags |= HEAP_DISABLE_COALESCE_ON_FREE;
1454 if (global_flags & FLG_HEAP_PAGE_ALLOCS) flags |= HEAP_PAGE_ALLOCS | HEAP_GROWABLE;
1456 if (global_flags & FLG_HEAP_VALIDATE_PARAMETERS)
1457 flags |= HEAP_VALIDATE | HEAP_VALIDATE_PARAMS |
1458 HEAP_TAIL_CHECKING_ENABLED | HEAP_FREE_CHECKING_ENABLED;
1459 if (global_flags & FLG_HEAP_VALIDATE_ALL)
1460 flags |= HEAP_VALIDATE | HEAP_VALIDATE_ALL |
1461 HEAP_TAIL_CHECKING_ENABLED | HEAP_FREE_CHECKING_ENABLED;
1463 if (RUNNING_ON_VALGRIND) flags = 0; /* no sense in validating since Valgrind catches accesses */
1465 heap->flags |= flags;
1466 heap->force_flags |= flags & ~(HEAP_VALIDATE | HEAP_DISABLE_COALESCE_ON_FREE);
1468 if (flags & (HEAP_FREE_CHECKING_ENABLED | HEAP_TAIL_CHECKING_ENABLED)) /* fix existing blocks */
1470 SUBHEAP *subheap;
1471 ARENA_LARGE *large;
1473 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
1475 char *ptr = (char *)subheap->base + subheap->headerSize;
1476 char *end = (char *)subheap->base + subheap->commitSize;
1477 while (ptr < end)
1479 ARENA_INUSE *arena = (ARENA_INUSE *)ptr;
1480 SIZE_T size = arena->size & ARENA_SIZE_MASK;
1481 if (arena->size & ARENA_FLAG_FREE)
1483 SIZE_T count = size;
1485 ptr += sizeof(ARENA_FREE) + size;
1486 if (ptr >= end) count = end - (char *)((ARENA_FREE *)arena + 1);
1487 else count -= sizeof(ARENA_FREE *);
1488 mark_block_free( (ARENA_FREE *)arena + 1, count, flags );
1490 else
1492 if (arena->magic == ARENA_PENDING_MAGIC)
1493 mark_block_free( arena + 1, size, flags );
1494 else
1495 mark_block_tail( (char *)(arena + 1) + size - arena->unused_bytes,
1496 arena->unused_bytes, flags );
1497 ptr += sizeof(ARENA_INUSE) + size;
1502 LIST_FOR_EACH_ENTRY( large, &heap->large_list, ARENA_LARGE, entry )
1503 mark_block_tail( (char *)(large + 1) + large->data_size,
1504 large->block_size - sizeof(*large) - large->data_size, flags );
1507 if ((heap->flags & HEAP_GROWABLE) && !heap->pending_free &&
1508 ((flags & HEAP_FREE_CHECKING_ENABLED) || RUNNING_ON_VALGRIND))
1510 void *ptr = NULL;
1511 SIZE_T size = MAX_FREE_PENDING * sizeof(*heap->pending_free);
1513 if (!NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 4, &size, MEM_COMMIT, PAGE_READWRITE ))
1515 heap->pending_free = ptr;
1516 heap->pending_pos = 0;
1522 /***********************************************************************
1523 * RtlCreateHeap (NTDLL.@)
1525 * Create a new Heap.
1527 * PARAMS
1528 * flags [I] HEAP_ flags from "winnt.h"
1529 * addr [I] Desired base address
1530 * totalSize [I] Total size of the heap, or 0 for a growable heap
1531 * commitSize [I] Amount of heap space to commit
1532 * unknown [I] Not yet understood
1533 * definition [I] Heap definition
1535 * RETURNS
1536 * Success: A HANDLE to the newly created heap.
1537 * Failure: a NULL HANDLE.
1539 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1540 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1542 SUBHEAP *subheap;
1544 /* Allocate the heap block */
1546 if (!totalSize)
1548 totalSize = HEAP_DEF_SIZE;
1549 flags |= HEAP_GROWABLE;
1552 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1554 heap_set_debug_flags( subheap->heap );
1556 /* link it into the per-process heap list */
1557 if (processHeap)
1559 HEAP *heapPtr = subheap->heap;
1560 RtlEnterCriticalSection( &processHeap->critSection );
1561 list_add_head( &processHeap->entry, &heapPtr->entry );
1562 RtlLeaveCriticalSection( &processHeap->critSection );
1564 else if (!addr)
1566 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1567 list_init( &processHeap->entry );
1570 return subheap->heap;
1574 /***********************************************************************
1575 * RtlDestroyHeap (NTDLL.@)
1577 * Destroy a Heap created with RtlCreateHeap().
1579 * PARAMS
1580 * heap [I] Heap to destroy.
1582 * RETURNS
1583 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1584 * Failure: The Heap handle, if heap is the process heap.
1586 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1588 HEAP *heapPtr = HEAP_GetPtr( heap );
1589 SUBHEAP *subheap, *next;
1590 ARENA_LARGE *arena, *arena_next;
1591 SIZE_T size;
1592 void *addr;
1594 TRACE("%p\n", heap );
1595 if (!heapPtr) return heap;
1597 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1599 /* remove it from the per-process list */
1600 RtlEnterCriticalSection( &processHeap->critSection );
1601 list_remove( &heapPtr->entry );
1602 RtlLeaveCriticalSection( &processHeap->critSection );
1604 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1605 RtlDeleteCriticalSection( &heapPtr->critSection );
1607 LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1609 list_remove( &arena->entry );
1610 size = 0;
1611 addr = arena;
1612 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1614 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1616 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1617 subheap_notify_free_all(subheap);
1618 list_remove( &subheap->entry );
1619 size = 0;
1620 addr = subheap->base;
1621 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1623 subheap_notify_free_all(&heapPtr->subheap);
1624 if (heapPtr->pending_free)
1626 size = 0;
1627 addr = heapPtr->pending_free;
1628 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1630 size = 0;
1631 addr = heapPtr->subheap.base;
1632 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1633 return 0;
1637 /***********************************************************************
1638 * RtlAllocateHeap (NTDLL.@)
1640 * Allocate a memory block from a Heap.
1642 * PARAMS
1643 * heap [I] Heap to allocate block from
1644 * flags [I] HEAP_ flags from "winnt.h"
1645 * size [I] Size of the memory block to allocate
1647 * RETURNS
1648 * Success: A pointer to the newly allocated block
1649 * Failure: NULL.
1651 * NOTES
1652 * This call does not SetLastError().
1654 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1656 ARENA_FREE *pArena;
1657 ARENA_INUSE *pInUse;
1658 SUBHEAP *subheap;
1659 HEAP *heapPtr = HEAP_GetPtr( heap );
1660 SIZE_T rounded_size;
1662 /* Validate the parameters */
1664 if (!heapPtr) return NULL;
1665 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1666 flags |= heapPtr->flags;
1667 rounded_size = ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE( flags );
1668 if (rounded_size < size) /* overflow */
1670 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1671 return NULL;
1673 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1675 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1677 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1679 void *ret = allocate_large_block( heap, flags, size );
1680 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1681 if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1682 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1683 return ret;
1686 /* Locate a suitable free block */
1688 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1690 TRACE("(%p,%08x,%08lx): returning NULL\n",
1691 heap, flags, size );
1692 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1693 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1694 return NULL;
1697 /* Remove the arena from the free list */
1699 list_remove( &pArena->entry );
1701 /* Build the in-use arena */
1703 pInUse = (ARENA_INUSE *)pArena;
1705 /* in-use arena is smaller than free arena,
1706 * so we have to add the difference to the size */
1707 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1708 pInUse->magic = ARENA_INUSE_MAGIC;
1710 /* Shrink the block */
1712 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1713 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1715 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1716 initialize_block( pInUse + 1, size, pInUse->unused_bytes, flags );
1718 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1720 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1721 return pInUse + 1;
1725 /***********************************************************************
1726 * RtlFreeHeap (NTDLL.@)
1728 * Free a memory block allocated with RtlAllocateHeap().
1730 * PARAMS
1731 * heap [I] Heap that block was allocated from
1732 * flags [I] HEAP_ flags from "winnt.h"
1733 * ptr [I] Block to free
1735 * RETURNS
1736 * Success: TRUE, if ptr is NULL or was freed successfully.
1737 * Failure: FALSE.
1739 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1741 ARENA_INUSE *pInUse;
1742 SUBHEAP *subheap;
1743 HEAP *heapPtr;
1745 /* Validate the parameters */
1747 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1749 heapPtr = HEAP_GetPtr( heap );
1750 if (!heapPtr)
1752 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1753 return FALSE;
1756 flags &= HEAP_NO_SERIALIZE;
1757 flags |= heapPtr->flags;
1758 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1760 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1761 notify_free( ptr );
1763 /* Some sanity checks */
1764 pInUse = (ARENA_INUSE *)ptr - 1;
1765 if (!validate_block_pointer( heapPtr, &subheap, pInUse )) goto error;
1767 if (!subheap)
1768 free_large_block( heapPtr, flags, ptr );
1769 else
1770 HEAP_MakeInUseBlockFree( subheap, pInUse );
1772 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1773 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1774 return TRUE;
1776 error:
1777 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1778 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1779 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1780 return FALSE;
1784 /***********************************************************************
1785 * RtlReAllocateHeap (NTDLL.@)
1787 * Change the size of a memory block allocated with RtlAllocateHeap().
1789 * PARAMS
1790 * heap [I] Heap that block was allocated from
1791 * flags [I] HEAP_ flags from "winnt.h"
1792 * ptr [I] Block to resize
1793 * size [I] Size of the memory block to allocate
1795 * RETURNS
1796 * Success: A pointer to the resized block (which may be different).
1797 * Failure: NULL.
1799 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1801 ARENA_INUSE *pArena;
1802 HEAP *heapPtr;
1803 SUBHEAP *subheap;
1804 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1805 void *ret;
1807 if (!ptr) return NULL;
1808 if (!(heapPtr = HEAP_GetPtr( heap )))
1810 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1811 return NULL;
1814 /* Validate the parameters */
1816 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1817 HEAP_REALLOC_IN_PLACE_ONLY;
1818 flags |= heapPtr->flags;
1819 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1821 rounded_size = ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE(flags);
1822 if (rounded_size < size) goto oom; /* overflow */
1823 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1825 pArena = (ARENA_INUSE *)ptr - 1;
1826 if (!validate_block_pointer( heapPtr, &subheap, pArena )) goto error;
1827 if (!subheap)
1829 if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1830 goto done;
1833 /* Check if we need to grow the block */
1835 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1836 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1837 if (rounded_size > oldBlockSize)
1839 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1841 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1843 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) goto oom;
1844 if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1845 memcpy( ret, pArena + 1, oldActualSize );
1846 notify_free( pArena + 1 );
1847 HEAP_MakeInUseBlockFree( subheap, pArena );
1848 goto done;
1850 if ((pNext < (char *)subheap->base + subheap->size) &&
1851 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1852 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1854 /* The next block is free and large enough */
1855 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1856 list_remove( &pFree->entry );
1857 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1858 if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1859 notify_realloc( pArena + 1, oldActualSize, size );
1860 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1862 else /* Do it the hard way */
1864 ARENA_FREE *pNew;
1865 ARENA_INUSE *pInUse;
1866 SUBHEAP *newsubheap;
1868 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1869 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1870 goto oom;
1872 /* Build the in-use arena */
1874 list_remove( &pNew->entry );
1875 pInUse = (ARENA_INUSE *)pNew;
1876 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1877 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1878 pInUse->magic = ARENA_INUSE_MAGIC;
1879 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1881 mark_block_initialized( pInUse + 1, oldActualSize );
1882 notify_alloc( pInUse + 1, size, FALSE );
1883 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1885 /* Free the previous block */
1887 notify_free( pArena + 1 );
1888 HEAP_MakeInUseBlockFree( subheap, pArena );
1889 subheap = newsubheap;
1890 pArena = pInUse;
1893 else
1895 notify_realloc( pArena + 1, oldActualSize, size );
1896 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1899 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1901 /* Clear the extra bytes if needed */
1903 if (size > oldActualSize)
1904 initialize_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize,
1905 pArena->unused_bytes, flags );
1906 else
1907 mark_block_tail( (char *)(pArena + 1) + size, pArena->unused_bytes, flags );
1909 /* Return the new arena */
1911 ret = pArena + 1;
1912 done:
1913 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1914 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1915 return ret;
1917 oom:
1918 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1919 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1920 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1921 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1922 return NULL;
1924 error:
1925 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1926 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1927 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1928 return NULL;
1932 /***********************************************************************
1933 * RtlCompactHeap (NTDLL.@)
1935 * Compact the free space in a Heap.
1937 * PARAMS
1938 * heap [I] Heap that block was allocated from
1939 * flags [I] HEAP_ flags from "winnt.h"
1941 * RETURNS
1942 * The number of bytes compacted.
1944 * NOTES
1945 * This function is a harmless stub.
1947 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1949 static BOOL reported;
1950 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1951 return 0;
1955 /***********************************************************************
1956 * RtlLockHeap (NTDLL.@)
1958 * Lock a Heap.
1960 * PARAMS
1961 * heap [I] Heap to lock
1963 * RETURNS
1964 * Success: TRUE. The Heap is locked.
1965 * Failure: FALSE, if heap is invalid.
1967 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1969 HEAP *heapPtr = HEAP_GetPtr( heap );
1970 if (!heapPtr) return FALSE;
1971 RtlEnterCriticalSection( &heapPtr->critSection );
1972 return TRUE;
1976 /***********************************************************************
1977 * RtlUnlockHeap (NTDLL.@)
1979 * Unlock a Heap.
1981 * PARAMS
1982 * heap [I] Heap to unlock
1984 * RETURNS
1985 * Success: TRUE. The Heap is unlocked.
1986 * Failure: FALSE, if heap is invalid.
1988 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1990 HEAP *heapPtr = HEAP_GetPtr( heap );
1991 if (!heapPtr) return FALSE;
1992 RtlLeaveCriticalSection( &heapPtr->critSection );
1993 return TRUE;
1997 /***********************************************************************
1998 * RtlSizeHeap (NTDLL.@)
2000 * Get the actual size of a memory block allocated from a Heap.
2002 * PARAMS
2003 * heap [I] Heap that block was allocated from
2004 * flags [I] HEAP_ flags from "winnt.h"
2005 * ptr [I] Block to get the size of
2007 * RETURNS
2008 * Success: The size of the block.
2009 * Failure: -1, heap or ptr are invalid.
2011 * NOTES
2012 * The size may be bigger than what was passed to RtlAllocateHeap().
2014 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
2016 SIZE_T ret;
2017 const ARENA_INUSE *pArena;
2018 SUBHEAP *subheap;
2019 HEAP *heapPtr = HEAP_GetPtr( heap );
2021 if (!heapPtr)
2023 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
2024 return ~0UL;
2026 flags &= HEAP_NO_SERIALIZE;
2027 flags |= heapPtr->flags;
2028 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
2030 pArena = (const ARENA_INUSE *)ptr - 1;
2031 if (!validate_block_pointer( heapPtr, &subheap, pArena ))
2033 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
2034 ret = ~0UL;
2036 else if (!subheap)
2038 const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
2039 ret = large_arena->data_size;
2041 else
2043 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
2045 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
2047 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
2048 return ret;
2052 /***********************************************************************
2053 * RtlValidateHeap (NTDLL.@)
2055 * Determine if a block is a valid allocation from a heap.
2057 * PARAMS
2058 * heap [I] Heap that block was allocated from
2059 * flags [I] HEAP_ flags from "winnt.h"
2060 * ptr [I] Block to check
2062 * RETURNS
2063 * Success: TRUE. The block was allocated from heap.
2064 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
2066 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
2068 HEAP *heapPtr = HEAP_GetPtr( heap );
2069 if (!heapPtr) return FALSE;
2070 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
2074 /***********************************************************************
2075 * RtlWalkHeap (NTDLL.@)
2077 * FIXME
2078 * The PROCESS_HEAP_ENTRY flag values seem different between this
2079 * function and HeapWalk(). To be checked.
2081 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
2083 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
2084 HEAP *heapPtr = HEAP_GetPtr(heap);
2085 SUBHEAP *sub, *currentheap = NULL;
2086 NTSTATUS ret;
2087 char *ptr;
2088 int region_index = 0;
2090 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
2092 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
2094 /* FIXME: enumerate large blocks too */
2096 /* set ptr to the next arena to be examined */
2098 if (!entry->lpData) /* first call (init) ? */
2100 TRACE("begin walking of heap %p.\n", heap);
2101 currentheap = &heapPtr->subheap;
2102 ptr = (char*)currentheap->base + currentheap->headerSize;
2104 else
2106 ptr = entry->lpData;
2107 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
2109 if ((ptr >= (char *)sub->base) &&
2110 (ptr < (char *)sub->base + sub->size))
2112 currentheap = sub;
2113 break;
2115 region_index++;
2117 if (currentheap == NULL)
2119 ERR("no matching subheap found, shouldn't happen !\n");
2120 ret = STATUS_NO_MORE_ENTRIES;
2121 goto HW_end;
2124 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC ||
2125 ((ARENA_INUSE *)ptr - 1)->magic == ARENA_PENDING_MAGIC)
2127 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
2128 ptr += pArena->size & ARENA_SIZE_MASK;
2130 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
2132 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
2133 ptr += pArena->size & ARENA_SIZE_MASK;
2135 else
2136 ptr += entry->cbData; /* point to next arena */
2138 if (ptr > (char *)currentheap->base + currentheap->size - 1)
2139 { /* proceed with next subheap */
2140 struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
2141 if (!next)
2142 { /* successfully finished */
2143 TRACE("end reached.\n");
2144 ret = STATUS_NO_MORE_ENTRIES;
2145 goto HW_end;
2147 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
2148 ptr = (char *)currentheap->base + currentheap->headerSize;
2152 entry->wFlags = 0;
2153 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2155 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2157 /*TRACE("free, magic: %04x\n", pArena->magic);*/
2159 entry->lpData = pArena + 1;
2160 entry->cbData = pArena->size & ARENA_SIZE_MASK;
2161 entry->cbOverhead = sizeof(ARENA_FREE);
2162 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
2164 else
2166 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2168 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
2170 entry->lpData = pArena + 1;
2171 entry->cbData = pArena->size & ARENA_SIZE_MASK;
2172 entry->cbOverhead = sizeof(ARENA_INUSE);
2173 entry->wFlags = (pArena->magic == ARENA_PENDING_MAGIC) ?
2174 PROCESS_HEAP_UNCOMMITTED_RANGE : PROCESS_HEAP_ENTRY_BUSY;
2175 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
2176 and PROCESS_HEAP_ENTRY_DDESHARE yet */
2179 entry->iRegionIndex = region_index;
2181 /* first element of heap ? */
2182 if (ptr == (char *)currentheap->base + currentheap->headerSize)
2184 entry->wFlags |= PROCESS_HEAP_REGION;
2185 entry->u.Region.dwCommittedSize = currentheap->commitSize;
2186 entry->u.Region.dwUnCommittedSize =
2187 currentheap->size - currentheap->commitSize;
2188 entry->u.Region.lpFirstBlock = /* first valid block */
2189 (char *)currentheap->base + currentheap->headerSize;
2190 entry->u.Region.lpLastBlock = /* first invalid block */
2191 (char *)currentheap->base + currentheap->size;
2193 ret = STATUS_SUCCESS;
2194 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
2196 HW_end:
2197 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
2198 return ret;
2202 /***********************************************************************
2203 * RtlGetProcessHeaps (NTDLL.@)
2205 * Get the Heaps belonging to the current process.
2207 * PARAMS
2208 * count [I] size of heaps
2209 * heaps [O] Destination array for heap HANDLE's
2211 * RETURNS
2212 * Success: The number of Heaps allocated by the process.
2213 * Failure: 0.
2215 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
2217 ULONG total = 1; /* main heap */
2218 struct list *ptr;
2220 RtlEnterCriticalSection( &processHeap->critSection );
2221 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
2222 if (total <= count)
2224 *heaps++ = processHeap;
2225 LIST_FOR_EACH( ptr, &processHeap->entry )
2226 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
2228 RtlLeaveCriticalSection( &processHeap->critSection );
2229 return total;
2232 /***********************************************************************
2233 * RtlQueryHeapInformation (NTDLL.@)
2235 NTSTATUS WINAPI RtlQueryHeapInformation( HANDLE heap, HEAP_INFORMATION_CLASS info_class,
2236 PVOID info, SIZE_T size_in, PSIZE_T size_out)
2238 switch (info_class)
2240 case HeapCompatibilityInformation:
2241 if (size_out) *size_out = sizeof(ULONG);
2243 if (size_in < sizeof(ULONG))
2244 return STATUS_BUFFER_TOO_SMALL;
2246 *(ULONG *)info = 0; /* standard heap */
2247 return STATUS_SUCCESS;
2249 default:
2250 FIXME("Unknown heap information class %u\n", info_class);
2251 return STATUS_INVALID_INFO_CLASS;