ddraw/tests: Properly release no longer used interfaces.
[wine/multimedia.git] / dlls / ntdll / heap.c
blob2e945e96c5c82d5b53a0b5b22ee2c73533d7ecde
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 void subheap_notify_free_all(SUBHEAP const *subheap)
268 #ifdef VALGRIND_FREELIKE_BLOCK
269 char const *ptr = (char const *)subheap->base + subheap->headerSize;
271 if (!RUNNING_ON_VALGRIND) return;
273 while (ptr < (char const *)subheap->base + subheap->size)
275 if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
277 ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
278 if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
279 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
281 else
283 ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
284 if (pArena->magic == ARENA_INUSE_MAGIC) notify_free(pArena + 1);
285 else if (pArena->magic != ARENA_PENDING_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
286 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
289 #endif
292 /* locate a free list entry of the appropriate size */
293 /* size is the size of the whole block including the arena header */
294 static inline unsigned int get_freelist_index( SIZE_T size )
296 unsigned int i;
298 size -= sizeof(ARENA_FREE);
299 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
300 return i;
303 /* get the memory protection type to use for a given heap */
304 static inline ULONG get_protection_type( DWORD flags )
306 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
309 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
311 0, 0, NULL, /* will be set later */
312 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
313 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
317 /***********************************************************************
318 * HEAP_Dump
320 static void HEAP_Dump( HEAP *heap )
322 unsigned int i;
323 SUBHEAP *subheap;
324 char *ptr;
326 DPRINTF( "Heap: %p\n", heap );
327 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
328 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
330 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
331 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
332 DPRINTF( "%p free %08lx prev=%p next=%p\n",
333 &heap->freeList[i].arena, HEAP_freeListSizes[i],
334 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
335 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
337 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
339 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
340 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
341 subheap, subheap->base, subheap->size, subheap->commitSize );
343 DPRINTF( "\n Block Arena Stat Size Id\n" );
344 ptr = (char *)subheap->base + subheap->headerSize;
345 while (ptr < (char *)subheap->base + subheap->size)
347 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
349 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
350 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
351 pArena, pArena->magic,
352 pArena->size & ARENA_SIZE_MASK,
353 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
354 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
355 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
356 arenaSize += sizeof(ARENA_FREE);
357 freeSize += pArena->size & ARENA_SIZE_MASK;
359 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
361 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
362 DPRINTF( "%p %08x Used %08x back=%p\n",
363 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
364 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
365 arenaSize += sizeof(ARENA_INUSE);
366 usedSize += pArena->size & ARENA_SIZE_MASK;
368 else
370 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
371 DPRINTF( "%p %08x %s %08x\n",
372 pArena, pArena->magic, pArena->magic == ARENA_INUSE_MAGIC ? "used" : "pend",
373 pArena->size & ARENA_SIZE_MASK );
374 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
375 arenaSize += sizeof(ARENA_INUSE);
376 usedSize += pArena->size & ARENA_SIZE_MASK;
379 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
380 subheap->size, subheap->commitSize, freeSize, usedSize,
381 arenaSize, (arenaSize * 100) / subheap->size );
386 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
388 WORD rem_flags;
389 TRACE( "Dumping entry %p\n", entry );
390 TRACE( "lpData\t\t: %p\n", entry->lpData );
391 TRACE( "cbData\t\t: %08x\n", entry->cbData);
392 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
393 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
394 TRACE( "WFlags\t\t: ");
395 if (entry->wFlags & PROCESS_HEAP_REGION)
396 TRACE( "PROCESS_HEAP_REGION ");
397 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
398 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
399 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
400 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
401 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
402 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
403 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
404 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
405 rem_flags = entry->wFlags &
406 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
407 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
408 PROCESS_HEAP_ENTRY_DDESHARE);
409 if (rem_flags)
410 TRACE( "Unknown %08x", rem_flags);
411 TRACE( "\n");
412 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
413 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
415 /* Treat as block */
416 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
418 if (entry->wFlags & PROCESS_HEAP_REGION)
420 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
421 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
422 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
423 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
427 /***********************************************************************
428 * HEAP_GetPtr
429 * RETURNS
430 * Pointer to the heap
431 * NULL: Failure
433 static HEAP *HEAP_GetPtr(
434 HANDLE heap /* [in] Handle to the heap */
436 HEAP *heapPtr = heap;
437 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
439 ERR("Invalid heap %p!\n", heap );
440 return NULL;
442 if ((heapPtr->flags & HEAP_VALIDATE_ALL) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
444 if (TRACE_ON(heap))
446 HEAP_Dump( heapPtr );
447 assert( FALSE );
449 return NULL;
451 return heapPtr;
455 /***********************************************************************
456 * HEAP_InsertFreeBlock
458 * Insert a free block into the free list.
460 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
462 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
463 if (last)
465 /* insert at end of free list, i.e. before the next free list entry */
466 pEntry++;
467 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
468 list_add_before( &pEntry->arena.entry, &pArena->entry );
470 else
472 /* insert at head of free list */
473 list_add_after( &pEntry->arena.entry, &pArena->entry );
475 pArena->size |= ARENA_FLAG_FREE;
479 /***********************************************************************
480 * HEAP_FindSubHeap
481 * Find the sub-heap containing a given address.
483 * RETURNS
484 * Pointer: Success
485 * NULL: Failure
487 static SUBHEAP *HEAP_FindSubHeap(
488 const HEAP *heap, /* [in] Heap pointer */
489 LPCVOID ptr ) /* [in] Address */
491 SUBHEAP *sub;
492 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
493 if ((ptr >= sub->base) &&
494 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
495 return sub;
496 return NULL;
500 /***********************************************************************
501 * HEAP_Commit
503 * Make sure the heap storage is committed for a given size in the specified arena.
505 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
507 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
508 SIZE_T size = (char *)ptr - (char *)subheap->base;
509 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
510 if (size > subheap->size) size = subheap->size;
511 if (size <= subheap->commitSize) return TRUE;
512 size -= subheap->commitSize;
513 ptr = (char *)subheap->base + subheap->commitSize;
514 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
515 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
517 WARN("Could not commit %08lx bytes at %p for heap %p\n",
518 size, ptr, subheap->heap );
519 return FALSE;
521 subheap->commitSize += size;
522 return TRUE;
526 /***********************************************************************
527 * HEAP_Decommit
529 * If possible, decommit the heap storage from (including) 'ptr'.
531 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
533 void *addr;
534 SIZE_T decommit_size;
535 SIZE_T size = (char *)ptr - (char *)subheap->base;
537 /* round to next block and add one full block */
538 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
539 size = max( size, subheap->min_commit );
540 if (size >= subheap->commitSize) return TRUE;
541 decommit_size = subheap->commitSize - size;
542 addr = (char *)subheap->base + size;
544 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
546 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
547 decommit_size, (char *)subheap->base + size, subheap->heap );
548 return FALSE;
550 subheap->commitSize -= decommit_size;
551 return TRUE;
555 /***********************************************************************
556 * HEAP_CreateFreeBlock
558 * Create a free block at a specified address. 'size' is the size of the
559 * whole block, including the new arena.
561 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
563 ARENA_FREE *pFree;
564 char *pEnd;
565 BOOL last;
566 DWORD flags = subheap->heap->flags;
568 /* Create a free arena */
569 mark_block_uninitialized( ptr, sizeof(ARENA_FREE) );
570 pFree = ptr;
571 pFree->magic = ARENA_FREE_MAGIC;
573 /* If debugging, erase the freed block content */
575 pEnd = (char *)ptr + size;
576 if (pEnd > (char *)subheap->base + subheap->commitSize)
577 pEnd = (char *)subheap->base + subheap->commitSize;
578 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1), flags );
580 /* Check if next block is free also */
582 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
583 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
585 /* Remove the next arena from the free list */
586 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
587 list_remove( &pNext->entry );
588 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
589 mark_block_free( pNext, sizeof(ARENA_FREE), flags );
592 /* Set the next block PREV_FREE flag and pointer */
594 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
595 if (!last)
597 DWORD *pNext = (DWORD *)((char *)ptr + size);
598 *pNext |= ARENA_FLAG_PREV_FREE;
599 mark_block_initialized( (ARENA_FREE **)pNext - 1, sizeof( ARENA_FREE * ) );
600 *((ARENA_FREE **)pNext - 1) = pFree;
603 /* Last, insert the new block into the free list */
605 pFree->size = size - sizeof(*pFree);
606 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
610 /***********************************************************************
611 * HEAP_MakeInUseBlockFree
613 * Turn an in-use block into a free block. Can also decommit the end of
614 * the heap, and possibly even free the sub-heap altogether.
616 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
618 HEAP *heap = subheap->heap;
619 ARENA_FREE *pFree;
620 SIZE_T size;
622 if (heap->pending_free)
624 ARENA_INUSE *prev = heap->pending_free[heap->pending_pos];
625 heap->pending_free[heap->pending_pos] = pArena;
626 heap->pending_pos = (heap->pending_pos + 1) % MAX_FREE_PENDING;
627 pArena->magic = ARENA_PENDING_MAGIC;
628 mark_block_free( pArena + 1, pArena->size & ARENA_SIZE_MASK, heap->flags );
629 if (!prev) return;
630 pArena = prev;
631 subheap = HEAP_FindSubHeap( heap, pArena );
634 /* Check if we can merge with previous block */
636 size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
637 if (pArena->size & ARENA_FLAG_PREV_FREE)
639 pFree = *((ARENA_FREE **)pArena - 1);
640 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
641 /* Remove it from the free list */
642 list_remove( &pFree->entry );
644 else pFree = (ARENA_FREE *)pArena;
646 /* Create a free block */
648 HEAP_CreateFreeBlock( subheap, pFree, size );
649 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
650 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
651 return; /* Not the last block, so nothing more to do */
653 /* Free the whole sub-heap if it's empty and not the original one */
655 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
656 (subheap != &subheap->heap->subheap))
658 SIZE_T size = 0;
659 void *addr = subheap->base;
660 /* Remove the free block from the list */
661 list_remove( &pFree->entry );
662 /* Remove the subheap from the list */
663 list_remove( &subheap->entry );
664 /* Free the memory */
665 subheap->magic = 0;
666 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
667 return;
670 /* Decommit the end of the heap */
672 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
676 /***********************************************************************
677 * HEAP_ShrinkBlock
679 * Shrink an in-use block.
681 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
683 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
685 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
686 (pArena->size & ARENA_SIZE_MASK) - size );
687 /* assign size plus previous arena flags */
688 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
690 else
692 /* Turn off PREV_FREE flag in next block */
693 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
694 if (pNext < (char *)subheap->base + subheap->size)
695 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
700 /***********************************************************************
701 * allocate_large_block
703 static void *allocate_large_block( HEAP *heap, DWORD flags, SIZE_T size )
705 ARENA_LARGE *arena;
706 SIZE_T block_size = sizeof(*arena) + ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE(flags);
707 LPVOID address = NULL;
709 if (block_size < size) return NULL; /* overflow */
710 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 5,
711 &block_size, MEM_COMMIT, get_protection_type( flags ) ))
713 WARN("Could not allocate block for %08lx bytes\n", size );
714 return NULL;
716 arena = address;
717 arena->data_size = size;
718 arena->block_size = block_size;
719 arena->size = ARENA_LARGE_SIZE;
720 arena->magic = ARENA_LARGE_MAGIC;
721 mark_block_tail( (char *)(arena + 1) + size, block_size - sizeof(*arena) - size, flags );
722 list_add_tail( &heap->large_list, &arena->entry );
723 notify_alloc( arena + 1, size, flags & HEAP_ZERO_MEMORY );
724 return arena + 1;
728 /***********************************************************************
729 * free_large_block
731 static void free_large_block( HEAP *heap, DWORD flags, void *ptr )
733 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
734 LPVOID address = arena;
735 SIZE_T size = 0;
737 list_remove( &arena->entry );
738 NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
742 /***********************************************************************
743 * realloc_large_block
745 static void *realloc_large_block( HEAP *heap, DWORD flags, void *ptr, SIZE_T size )
747 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
748 void *new_ptr;
750 if (arena->block_size - sizeof(*arena) >= size)
752 SIZE_T unused = arena->block_size - sizeof(*arena) - size;
754 /* FIXME: we could remap zero-pages instead */
755 if (size > arena->data_size)
756 initialize_block( (char *)ptr + arena->data_size, size - arena->data_size, unused, flags );
757 else
758 mark_block_tail( (char *)ptr + size, unused, flags );
759 arena->data_size = size;
760 return ptr;
762 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) return NULL;
763 if (!(new_ptr = allocate_large_block( heap, flags, size )))
765 WARN("Could not allocate block for %08lx bytes\n", size );
766 return NULL;
768 memcpy( new_ptr, ptr, arena->data_size );
769 free_large_block( heap, flags, ptr );
770 notify_free( ptr );
771 return new_ptr;
775 /***********************************************************************
776 * find_large_block
778 static ARENA_LARGE *find_large_block( HEAP *heap, const void *ptr )
780 ARENA_LARGE *arena;
782 LIST_FOR_EACH_ENTRY( arena, &heap->large_list, ARENA_LARGE, entry )
783 if (ptr == arena + 1) return arena;
785 return NULL;
789 /***********************************************************************
790 * validate_large_arena
792 static BOOL validate_large_arena( HEAP *heap, const ARENA_LARGE *arena, BOOL quiet )
794 DWORD flags = heap->flags;
796 if ((ULONG_PTR)arena % getpagesize())
798 if (quiet == NOISY)
800 ERR( "Heap %p: invalid large arena pointer %p\n", heap, arena );
801 if (TRACE_ON(heap)) HEAP_Dump( heap );
803 else if (WARN_ON(heap))
805 WARN( "Heap %p: unaligned arena pointer %p\n", heap, arena );
806 if (TRACE_ON(heap)) HEAP_Dump( heap );
808 return FALSE;
810 if (arena->size != ARENA_LARGE_SIZE || arena->magic != ARENA_LARGE_MAGIC)
812 if (quiet == NOISY)
814 ERR( "Heap %p: invalid large arena %p values %x/%x\n",
815 heap, arena, arena->size, arena->magic );
816 if (TRACE_ON(heap)) HEAP_Dump( heap );
818 else if (WARN_ON(heap))
820 WARN( "Heap %p: invalid large arena %p values %x/%x\n",
821 heap, arena, arena->size, arena->magic );
822 if (TRACE_ON(heap)) HEAP_Dump( heap );
824 return FALSE;
826 if (arena->data_size > arena->block_size - sizeof(*arena))
828 ERR( "Heap %p: invalid large arena %p size %lx/%lx\n",
829 heap, arena, arena->data_size, arena->block_size );
830 return FALSE;
832 if (flags & HEAP_TAIL_CHECKING_ENABLED)
834 SIZE_T i, unused = arena->block_size - sizeof(*arena) - arena->data_size;
835 const unsigned char *data = (const unsigned char *)(arena + 1) + arena->data_size;
837 for (i = 0; i < unused; i++)
839 if (data[i] == ARENA_TAIL_FILLER) continue;
840 ERR("Heap %p: block %p tail overwritten at %p (byte %lu/%lu == 0x%02x)\n",
841 heap, arena + 1, data + i, i, unused, data[i] );
842 return FALSE;
845 return TRUE;
849 /***********************************************************************
850 * HEAP_CreateSubHeap
852 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, LPVOID address, DWORD flags,
853 SIZE_T commitSize, SIZE_T totalSize )
855 SUBHEAP *subheap;
856 FREE_LIST_ENTRY *pEntry;
857 unsigned int i;
859 if (!address)
861 if (!commitSize) commitSize = COMMIT_MASK + 1;
862 totalSize = min( totalSize, 0xffff0000 ); /* don't allow a heap larger than 4Gb */
863 if (totalSize < commitSize) totalSize = commitSize;
864 if (flags & HEAP_SHARED) commitSize = totalSize; /* always commit everything in a shared heap */
865 commitSize = min( totalSize, (commitSize + COMMIT_MASK) & ~COMMIT_MASK );
867 /* allocate the memory block */
868 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 5, &totalSize,
869 MEM_RESERVE, get_protection_type( flags ) ))
871 WARN("Could not allocate %08lx bytes\n", totalSize );
872 return NULL;
874 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
875 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
877 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
878 return NULL;
882 if (heap)
884 /* If this is a secondary subheap, insert it into list */
886 subheap = address;
887 subheap->base = address;
888 subheap->heap = heap;
889 subheap->size = totalSize;
890 subheap->min_commit = 0x10000;
891 subheap->commitSize = commitSize;
892 subheap->magic = SUBHEAP_MAGIC;
893 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
894 list_add_head( &heap->subheap_list, &subheap->entry );
896 else
898 /* If this is a primary subheap, initialize main heap */
900 heap = address;
901 heap->flags = flags;
902 heap->magic = HEAP_MAGIC;
903 heap->grow_size = max( HEAP_DEF_SIZE, totalSize );
904 list_init( &heap->subheap_list );
905 list_init( &heap->large_list );
907 subheap = &heap->subheap;
908 subheap->base = address;
909 subheap->heap = heap;
910 subheap->size = totalSize;
911 subheap->min_commit = commitSize;
912 subheap->commitSize = commitSize;
913 subheap->magic = SUBHEAP_MAGIC;
914 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
915 list_add_head( &heap->subheap_list, &subheap->entry );
917 /* Build the free lists */
919 heap->freeList = (FREE_LIST_ENTRY *)((char *)heap + subheap->headerSize);
920 subheap->headerSize += HEAP_NB_FREE_LISTS * sizeof(FREE_LIST_ENTRY);
921 list_init( &heap->freeList[0].arena.entry );
922 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
924 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
925 pEntry->arena.magic = ARENA_FREE_MAGIC;
926 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
929 /* Initialize critical section */
931 if (!processHeap) /* do it by hand to avoid memory allocations */
933 heap->critSection.DebugInfo = &process_heap_critsect_debug;
934 heap->critSection.LockCount = -1;
935 heap->critSection.RecursionCount = 0;
936 heap->critSection.OwningThread = 0;
937 heap->critSection.LockSemaphore = 0;
938 heap->critSection.SpinCount = 0;
939 process_heap_critsect_debug.CriticalSection = &heap->critSection;
941 else
943 RtlInitializeCriticalSection( &heap->critSection );
944 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
947 if (flags & HEAP_SHARED)
949 /* let's assume that only one thread at a time will try to do this */
950 HANDLE sem = heap->critSection.LockSemaphore;
951 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
953 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
954 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
955 heap->critSection.LockSemaphore = sem;
956 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
957 heap->critSection.DebugInfo = NULL;
961 /* Create the first free block */
963 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
964 subheap->size - subheap->headerSize );
966 return subheap;
970 /***********************************************************************
971 * HEAP_FindFreeBlock
973 * Find a free block at least as large as the requested size, and make sure
974 * the requested size is committed.
976 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
977 SUBHEAP **ppSubHeap )
979 SUBHEAP *subheap;
980 struct list *ptr;
981 SIZE_T total_size;
982 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
984 /* Find a suitable free list, and in it find a block large enough */
986 ptr = &pEntry->arena.entry;
987 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
989 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
990 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
991 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
992 if (arena_size >= size)
994 subheap = HEAP_FindSubHeap( heap, pArena );
995 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
996 *ppSubHeap = subheap;
997 return pArena;
1001 /* If no block was found, attempt to grow the heap */
1003 if (!(heap->flags & HEAP_GROWABLE))
1005 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
1006 return NULL;
1008 /* make sure that we have a big enough size *committed* to fit another
1009 * last free arena in !
1010 * So just one heap struct, one first free arena which will eventually
1011 * get used, and a second free arena that might get assigned all remaining
1012 * free space in HEAP_ShrinkBlock() */
1013 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
1014 if (total_size < size) return NULL; /* overflow */
1016 if ((subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
1017 max( heap->grow_size, total_size ) )))
1019 if (heap->grow_size < 128 * 1024 * 1024) heap->grow_size *= 2;
1021 else while (!subheap) /* shrink the grow size again if we are running out of space */
1023 if (heap->grow_size <= total_size || heap->grow_size <= 4 * 1024 * 1024) return NULL;
1024 heap->grow_size /= 2;
1025 subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
1026 max( heap->grow_size, total_size ) );
1029 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
1030 subheap, subheap->size, heap );
1032 *ppSubHeap = subheap;
1033 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
1037 /***********************************************************************
1038 * HEAP_IsValidArenaPtr
1040 * Check that the pointer is inside the range possible for arenas.
1042 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
1044 unsigned int i;
1045 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
1046 if (!subheap) return FALSE;
1047 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
1048 if (subheap != &heap->subheap) return FALSE;
1049 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
1050 if (ptr == &heap->freeList[i].arena) return TRUE;
1051 return FALSE;
1055 /***********************************************************************
1056 * HEAP_ValidateFreeArena
1058 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
1060 DWORD flags = subheap->heap->flags;
1061 SIZE_T size;
1062 ARENA_FREE *prev, *next;
1063 char *heapEnd = (char *)subheap->base + subheap->size;
1065 /* Check for unaligned pointers */
1066 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1068 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1069 return FALSE;
1072 /* Check magic number */
1073 if (pArena->magic != ARENA_FREE_MAGIC)
1075 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1076 return FALSE;
1078 /* Check size flags */
1079 if (!(pArena->size & ARENA_FLAG_FREE) ||
1080 (pArena->size & ARENA_FLAG_PREV_FREE))
1082 ERR("Heap %p: bad flags %08x for free arena %p\n",
1083 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1084 return FALSE;
1086 /* Check arena size */
1087 size = pArena->size & ARENA_SIZE_MASK;
1088 if ((char *)(pArena + 1) + size > heapEnd)
1090 ERR("Heap %p: bad size %08lx for free arena %p\n", subheap->heap, size, pArena );
1091 return FALSE;
1093 /* Check that next pointer is valid */
1094 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
1095 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
1097 ERR("Heap %p: bad next ptr %p for arena %p\n",
1098 subheap->heap, next, pArena );
1099 return FALSE;
1101 /* Check that next arena is free */
1102 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1104 ERR("Heap %p: next arena %p invalid for %p\n",
1105 subheap->heap, next, pArena );
1106 return FALSE;
1108 /* Check that prev pointer is valid */
1109 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1110 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1112 ERR("Heap %p: bad prev ptr %p for arena %p\n",
1113 subheap->heap, prev, pArena );
1114 return FALSE;
1116 /* Check that prev arena is free */
1117 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1119 /* this often means that the prev arena got overwritten
1120 * by a memory write before that prev arena */
1121 ERR("Heap %p: prev arena %p invalid for %p\n",
1122 subheap->heap, prev, pArena );
1123 return FALSE;
1125 /* Check that next block has PREV_FREE flag */
1126 if ((char *)(pArena + 1) + size < heapEnd)
1128 if (!(*(DWORD *)((char *)(pArena + 1) + size) & ARENA_FLAG_PREV_FREE))
1130 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1131 subheap->heap, pArena );
1132 return FALSE;
1134 /* Check next block back pointer */
1135 if (*((ARENA_FREE **)((char *)(pArena + 1) + size) - 1) != pArena)
1137 ERR("Heap %p: arena %p has wrong back ptr %p\n",
1138 subheap->heap, pArena,
1139 *((ARENA_FREE **)((char *)(pArena+1) + size) - 1));
1140 return FALSE;
1143 if (flags & HEAP_FREE_CHECKING_ENABLED)
1145 DWORD *ptr = (DWORD *)(pArena + 1);
1146 char *end = (char *)(pArena + 1) + size;
1148 if (end >= heapEnd) end = (char *)subheap->base + subheap->commitSize;
1149 else end -= sizeof(ARENA_FREE *);
1150 while (ptr < (DWORD *)end)
1152 if (*ptr != ARENA_FREE_FILLER)
1154 ERR("Heap %p: free block %p overwritten at %p by %08x\n",
1155 subheap->heap, (ARENA_INUSE *)pArena + 1, ptr, *ptr );
1156 return FALSE;
1158 ptr++;
1161 return TRUE;
1165 /***********************************************************************
1166 * HEAP_ValidateInUseArena
1168 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1170 SIZE_T size;
1171 DWORD i, flags = subheap->heap->flags;
1172 const char *heapEnd = (const char *)subheap->base + subheap->size;
1174 /* Check for unaligned pointers */
1175 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1177 if ( quiet == NOISY )
1179 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1180 if ( TRACE_ON(heap) )
1181 HEAP_Dump( subheap->heap );
1183 else if ( WARN_ON(heap) )
1185 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1186 if ( TRACE_ON(heap) )
1187 HEAP_Dump( subheap->heap );
1189 return FALSE;
1192 /* Check magic number */
1193 if (pArena->magic != ARENA_INUSE_MAGIC && pArena->magic != ARENA_PENDING_MAGIC)
1195 if (quiet == NOISY) {
1196 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1197 if (TRACE_ON(heap))
1198 HEAP_Dump( subheap->heap );
1199 } else if (WARN_ON(heap)) {
1200 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1201 if (TRACE_ON(heap))
1202 HEAP_Dump( subheap->heap );
1204 return FALSE;
1206 /* Check size flags */
1207 if (pArena->size & ARENA_FLAG_FREE)
1209 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1210 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1211 return FALSE;
1213 /* Check arena size */
1214 size = pArena->size & ARENA_SIZE_MASK;
1215 if ((const char *)(pArena + 1) + size > heapEnd ||
1216 (const char *)(pArena + 1) + size < (const char *)(pArena + 1))
1218 ERR("Heap %p: bad size %08lx for in-use arena %p\n", subheap->heap, size, pArena );
1219 return FALSE;
1221 /* Check next arena PREV_FREE flag */
1222 if (((const char *)(pArena + 1) + size < heapEnd) &&
1223 (*(const DWORD *)((const char *)(pArena + 1) + size) & ARENA_FLAG_PREV_FREE))
1225 ERR("Heap %p: in-use arena %p next block %p has PREV_FREE flag %x\n",
1226 subheap->heap, pArena, (const char *)(pArena + 1) + size,*(const DWORD *)((const char *)(pArena + 1) + size) );
1227 return FALSE;
1229 /* Check prev free arena */
1230 if (pArena->size & ARENA_FLAG_PREV_FREE)
1232 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1233 /* Check prev pointer */
1234 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1236 ERR("Heap %p: bad back ptr %p for arena %p\n",
1237 subheap->heap, pPrev, pArena );
1238 return FALSE;
1240 /* Check that prev arena is free */
1241 if (!(pPrev->size & ARENA_FLAG_FREE) ||
1242 (pPrev->magic != ARENA_FREE_MAGIC))
1244 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1245 subheap->heap, pPrev, pArena );
1246 return FALSE;
1248 /* Check that prev arena is really the previous block */
1249 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1251 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1252 subheap->heap, pPrev, pArena );
1253 return FALSE;
1256 /* Check unused size */
1257 if (pArena->unused_bytes > size)
1259 ERR("Heap %p: invalid unused size %08x/%08lx\n", subheap->heap, pArena->unused_bytes, size );
1260 return FALSE;
1262 /* Check unused bytes */
1263 if (pArena->magic == ARENA_PENDING_MAGIC)
1265 const DWORD *ptr = (const DWORD *)(pArena + 1);
1266 const DWORD *end = (const DWORD *)((const char *)ptr + size);
1268 while (ptr < end)
1270 if (*ptr != ARENA_FREE_FILLER)
1272 ERR("Heap %p: free block %p overwritten at %p by %08x\n",
1273 subheap->heap, (const ARENA_INUSE *)pArena + 1, ptr, *ptr );
1274 if (!*ptr) { HEAP_Dump( subheap->heap ); DbgBreakPoint(); }
1275 return FALSE;
1277 ptr++;
1280 else if (flags & HEAP_TAIL_CHECKING_ENABLED)
1282 const unsigned char *data = (const unsigned char *)(pArena + 1) + size - pArena->unused_bytes;
1284 for (i = 0; i < pArena->unused_bytes; i++)
1286 if (data[i] == ARENA_TAIL_FILLER) continue;
1287 ERR("Heap %p: block %p tail overwritten at %p (byte %u/%u == 0x%02x)\n",
1288 subheap->heap, pArena + 1, data + i, i, pArena->unused_bytes, data[i] );
1289 return FALSE;
1292 return TRUE;
1296 /***********************************************************************
1297 * HEAP_IsRealArena [Internal]
1298 * Validates a block is a valid arena.
1300 * RETURNS
1301 * TRUE: Success
1302 * FALSE: Failure
1304 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1305 DWORD flags, /* [in] Bit flags that control access during operation */
1306 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1307 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1308 * does not complain */
1310 SUBHEAP *subheap;
1311 BOOL ret = TRUE;
1312 const ARENA_LARGE *large_arena;
1314 flags &= HEAP_NO_SERIALIZE;
1315 flags |= heapPtr->flags;
1316 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1317 if (!(flags & HEAP_NO_SERIALIZE))
1318 RtlEnterCriticalSection( &heapPtr->critSection );
1320 if (block) /* only check this single memory block */
1322 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1324 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1325 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1327 if (!(large_arena = find_large_block( heapPtr, block )))
1329 if (quiet == NOISY)
1330 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1331 else if (WARN_ON(heap))
1332 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1333 ret = FALSE;
1335 else
1336 ret = validate_large_arena( heapPtr, large_arena, quiet );
1337 } else
1338 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1340 if (!(flags & HEAP_NO_SERIALIZE))
1341 RtlLeaveCriticalSection( &heapPtr->critSection );
1342 return ret;
1345 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1347 char *ptr = (char *)subheap->base + subheap->headerSize;
1348 while (ptr < (char *)subheap->base + subheap->size)
1350 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1352 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1353 ret = FALSE;
1354 break;
1356 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1358 else
1360 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1361 ret = FALSE;
1362 break;
1364 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1367 if (!ret) break;
1370 LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1371 if (!(ret = validate_large_arena( heapPtr, large_arena, quiet ))) break;
1373 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1374 return ret;
1378 /***********************************************************************
1379 * validate_block_pointer
1381 * Minimum validation needed to catch bad parameters in heap functions.
1383 static BOOL validate_block_pointer( HEAP *heap, SUBHEAP **ret_subheap, const ARENA_INUSE *arena )
1385 SUBHEAP *subheap;
1386 BOOL ret = FALSE;
1388 if (!(*ret_subheap = subheap = HEAP_FindSubHeap( heap, arena )))
1390 ARENA_LARGE *large_arena = find_large_block( heap, arena + 1 );
1392 if (!large_arena)
1394 WARN( "Heap %p: pointer %p is not inside heap\n", heap, arena + 1 );
1395 return FALSE;
1397 if ((heap->flags & HEAP_VALIDATE) && !validate_large_arena( heap, large_arena, QUIET ))
1398 return FALSE;
1399 return TRUE;
1402 if ((const char *)arena < (char *)subheap->base + subheap->headerSize)
1403 WARN( "Heap %p: pointer %p is inside subheap %p header\n", subheap->heap, arena + 1, subheap );
1404 else if (subheap->heap->flags & HEAP_VALIDATE) /* do the full validation */
1405 ret = HEAP_ValidateInUseArena( subheap, arena, QUIET );
1406 else if ((ULONG_PTR)arena % ALIGNMENT != ARENA_OFFSET)
1407 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, arena );
1408 else if (arena->magic == ARENA_PENDING_MAGIC)
1409 WARN( "Heap %p: block %p used after free\n", subheap->heap, arena + 1 );
1410 else if (arena->magic != ARENA_INUSE_MAGIC)
1411 WARN( "Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, arena->magic, arena );
1412 else if (arena->size & ARENA_FLAG_FREE)
1413 ERR( "Heap %p: bad flags %08x for in-use arena %p\n",
1414 subheap->heap, arena->size & ~ARENA_SIZE_MASK, arena );
1415 else if ((const char *)(arena + 1) + (arena->size & ARENA_SIZE_MASK) > (const char *)subheap->base + subheap->size ||
1416 (const char *)(arena + 1) + (arena->size & ARENA_SIZE_MASK) < (const char *)(arena + 1))
1417 ERR( "Heap %p: bad size %08x for in-use arena %p\n",
1418 subheap->heap, arena->size & ARENA_SIZE_MASK, arena );
1419 else
1420 ret = TRUE;
1422 return ret;
1426 /***********************************************************************
1427 * heap_set_debug_flags
1429 void heap_set_debug_flags( HANDLE handle )
1431 HEAP *heap = HEAP_GetPtr( handle );
1432 ULONG global_flags = RtlGetNtGlobalFlags();
1433 ULONG flags = 0;
1435 if (TRACE_ON(heap)) global_flags |= FLG_HEAP_VALIDATE_ALL;
1436 if (WARN_ON(heap)) global_flags |= FLG_HEAP_VALIDATE_PARAMETERS;
1438 if (global_flags & FLG_HEAP_ENABLE_TAIL_CHECK) flags |= HEAP_TAIL_CHECKING_ENABLED;
1439 if (global_flags & FLG_HEAP_ENABLE_FREE_CHECK) flags |= HEAP_FREE_CHECKING_ENABLED;
1440 if (global_flags & FLG_HEAP_DISABLE_COALESCING) flags |= HEAP_DISABLE_COALESCE_ON_FREE;
1441 if (global_flags & FLG_HEAP_PAGE_ALLOCS) flags |= HEAP_PAGE_ALLOCS | HEAP_GROWABLE;
1443 if (global_flags & FLG_HEAP_VALIDATE_PARAMETERS)
1444 flags |= HEAP_VALIDATE | HEAP_VALIDATE_PARAMS |
1445 HEAP_TAIL_CHECKING_ENABLED | HEAP_FREE_CHECKING_ENABLED;
1446 if (global_flags & FLG_HEAP_VALIDATE_ALL)
1447 flags |= HEAP_VALIDATE | HEAP_VALIDATE_ALL |
1448 HEAP_TAIL_CHECKING_ENABLED | HEAP_FREE_CHECKING_ENABLED;
1450 if (RUNNING_ON_VALGRIND) flags = 0; /* no sense in validating since Valgrind catches accesses */
1452 heap->flags |= flags;
1453 heap->force_flags |= flags & ~(HEAP_VALIDATE | HEAP_DISABLE_COALESCE_ON_FREE);
1455 if (flags & (HEAP_FREE_CHECKING_ENABLED | HEAP_TAIL_CHECKING_ENABLED)) /* fix existing blocks */
1457 SUBHEAP *subheap;
1458 ARENA_LARGE *large;
1460 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
1462 char *ptr = (char *)subheap->base + subheap->headerSize;
1463 char *end = (char *)subheap->base + subheap->commitSize;
1464 while (ptr < end)
1466 ARENA_INUSE *arena = (ARENA_INUSE *)ptr;
1467 SIZE_T size = arena->size & ARENA_SIZE_MASK;
1468 if (arena->size & ARENA_FLAG_FREE)
1470 SIZE_T count = size;
1472 ptr += sizeof(ARENA_FREE) + size;
1473 if (ptr >= end) count = end - (char *)((ARENA_FREE *)arena + 1);
1474 else count -= sizeof(ARENA_FREE *);
1475 mark_block_free( (ARENA_FREE *)arena + 1, count, flags );
1477 else
1479 if (arena->magic == ARENA_PENDING_MAGIC)
1480 mark_block_free( arena + 1, size, flags );
1481 else
1482 mark_block_tail( (char *)(arena + 1) + size - arena->unused_bytes,
1483 arena->unused_bytes, flags );
1484 ptr += sizeof(ARENA_INUSE) + size;
1489 LIST_FOR_EACH_ENTRY( large, &heap->large_list, ARENA_LARGE, entry )
1490 mark_block_tail( (char *)(large + 1) + large->data_size,
1491 large->block_size - sizeof(*large) - large->data_size, flags );
1494 if ((heap->flags & HEAP_GROWABLE) && !heap->pending_free &&
1495 ((flags & HEAP_FREE_CHECKING_ENABLED) || RUNNING_ON_VALGRIND))
1497 void *ptr = NULL;
1498 SIZE_T size = MAX_FREE_PENDING * sizeof(*heap->pending_free);
1500 if (!NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 4, &size, MEM_COMMIT, PAGE_READWRITE ))
1502 heap->pending_free = ptr;
1503 heap->pending_pos = 0;
1509 /***********************************************************************
1510 * RtlCreateHeap (NTDLL.@)
1512 * Create a new Heap.
1514 * PARAMS
1515 * flags [I] HEAP_ flags from "winnt.h"
1516 * addr [I] Desired base address
1517 * totalSize [I] Total size of the heap, or 0 for a growable heap
1518 * commitSize [I] Amount of heap space to commit
1519 * unknown [I] Not yet understood
1520 * definition [I] Heap definition
1522 * RETURNS
1523 * Success: A HANDLE to the newly created heap.
1524 * Failure: a NULL HANDLE.
1526 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1527 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1529 SUBHEAP *subheap;
1531 /* Allocate the heap block */
1533 if (!totalSize)
1535 totalSize = HEAP_DEF_SIZE;
1536 flags |= HEAP_GROWABLE;
1539 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1541 heap_set_debug_flags( subheap->heap );
1543 /* link it into the per-process heap list */
1544 if (processHeap)
1546 HEAP *heapPtr = subheap->heap;
1547 RtlEnterCriticalSection( &processHeap->critSection );
1548 list_add_head( &processHeap->entry, &heapPtr->entry );
1549 RtlLeaveCriticalSection( &processHeap->critSection );
1551 else if (!addr)
1553 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1554 list_init( &processHeap->entry );
1557 return subheap->heap;
1561 /***********************************************************************
1562 * RtlDestroyHeap (NTDLL.@)
1564 * Destroy a Heap created with RtlCreateHeap().
1566 * PARAMS
1567 * heap [I] Heap to destroy.
1569 * RETURNS
1570 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1571 * Failure: The Heap handle, if heap is the process heap.
1573 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1575 HEAP *heapPtr = HEAP_GetPtr( heap );
1576 SUBHEAP *subheap, *next;
1577 ARENA_LARGE *arena, *arena_next;
1578 SIZE_T size;
1579 void *addr;
1581 TRACE("%p\n", heap );
1582 if (!heapPtr) return heap;
1584 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1586 /* remove it from the per-process list */
1587 RtlEnterCriticalSection( &processHeap->critSection );
1588 list_remove( &heapPtr->entry );
1589 RtlLeaveCriticalSection( &processHeap->critSection );
1591 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1592 RtlDeleteCriticalSection( &heapPtr->critSection );
1594 LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1596 list_remove( &arena->entry );
1597 size = 0;
1598 addr = arena;
1599 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1601 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1603 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1604 subheap_notify_free_all(subheap);
1605 list_remove( &subheap->entry );
1606 size = 0;
1607 addr = subheap->base;
1608 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1610 subheap_notify_free_all(&heapPtr->subheap);
1611 if (heapPtr->pending_free)
1613 size = 0;
1614 addr = heapPtr->pending_free;
1615 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1617 size = 0;
1618 addr = heapPtr->subheap.base;
1619 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1620 return 0;
1624 /***********************************************************************
1625 * RtlAllocateHeap (NTDLL.@)
1627 * Allocate a memory block from a Heap.
1629 * PARAMS
1630 * heap [I] Heap to allocate block from
1631 * flags [I] HEAP_ flags from "winnt.h"
1632 * size [I] Size of the memory block to allocate
1634 * RETURNS
1635 * Success: A pointer to the newly allocated block
1636 * Failure: NULL.
1638 * NOTES
1639 * This call does not SetLastError().
1641 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1643 ARENA_FREE *pArena;
1644 ARENA_INUSE *pInUse;
1645 SUBHEAP *subheap;
1646 HEAP *heapPtr = HEAP_GetPtr( heap );
1647 SIZE_T rounded_size;
1649 /* Validate the parameters */
1651 if (!heapPtr) return NULL;
1652 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1653 flags |= heapPtr->flags;
1654 rounded_size = ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE( flags );
1655 if (rounded_size < size) /* overflow */
1657 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1658 return NULL;
1660 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1662 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1664 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1666 void *ret = allocate_large_block( heap, flags, size );
1667 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1668 if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1669 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1670 return ret;
1673 /* Locate a suitable free block */
1675 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1677 TRACE("(%p,%08x,%08lx): returning NULL\n",
1678 heap, flags, size );
1679 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1680 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1681 return NULL;
1684 /* Remove the arena from the free list */
1686 list_remove( &pArena->entry );
1688 /* Build the in-use arena */
1690 pInUse = (ARENA_INUSE *)pArena;
1692 /* in-use arena is smaller than free arena,
1693 * so we have to add the difference to the size */
1694 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1695 pInUse->magic = ARENA_INUSE_MAGIC;
1697 /* Shrink the block */
1699 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1700 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1702 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1703 initialize_block( pInUse + 1, size, pInUse->unused_bytes, flags );
1705 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1707 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1708 return pInUse + 1;
1712 /***********************************************************************
1713 * RtlFreeHeap (NTDLL.@)
1715 * Free a memory block allocated with RtlAllocateHeap().
1717 * PARAMS
1718 * heap [I] Heap that block was allocated from
1719 * flags [I] HEAP_ flags from "winnt.h"
1720 * ptr [I] Block to free
1722 * RETURNS
1723 * Success: TRUE, if ptr is NULL or was freed successfully.
1724 * Failure: FALSE.
1726 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1728 ARENA_INUSE *pInUse;
1729 SUBHEAP *subheap;
1730 HEAP *heapPtr;
1732 /* Validate the parameters */
1734 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1736 heapPtr = HEAP_GetPtr( heap );
1737 if (!heapPtr)
1739 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1740 return FALSE;
1743 flags &= HEAP_NO_SERIALIZE;
1744 flags |= heapPtr->flags;
1745 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1747 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1748 notify_free( ptr );
1750 /* Some sanity checks */
1751 pInUse = (ARENA_INUSE *)ptr - 1;
1752 if (!validate_block_pointer( heapPtr, &subheap, pInUse )) goto error;
1754 if (!subheap)
1755 free_large_block( heapPtr, flags, ptr );
1756 else
1757 HEAP_MakeInUseBlockFree( subheap, pInUse );
1759 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1760 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1761 return TRUE;
1763 error:
1764 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1765 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1766 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1767 return FALSE;
1771 /***********************************************************************
1772 * RtlReAllocateHeap (NTDLL.@)
1774 * Change the size of a memory block allocated with RtlAllocateHeap().
1776 * PARAMS
1777 * heap [I] Heap that block was allocated from
1778 * flags [I] HEAP_ flags from "winnt.h"
1779 * ptr [I] Block to resize
1780 * size [I] Size of the memory block to allocate
1782 * RETURNS
1783 * Success: A pointer to the resized block (which may be different).
1784 * Failure: NULL.
1786 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1788 ARENA_INUSE *pArena;
1789 HEAP *heapPtr;
1790 SUBHEAP *subheap;
1791 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1792 void *ret;
1794 if (!ptr) return NULL;
1795 if (!(heapPtr = HEAP_GetPtr( heap )))
1797 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1798 return NULL;
1801 /* Validate the parameters */
1803 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1804 HEAP_REALLOC_IN_PLACE_ONLY;
1805 flags |= heapPtr->flags;
1806 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1808 rounded_size = ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE(flags);
1809 if (rounded_size < size) goto oom; /* overflow */
1810 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1812 pArena = (ARENA_INUSE *)ptr - 1;
1813 if (!validate_block_pointer( heapPtr, &subheap, pArena )) goto error;
1814 if (!subheap)
1816 if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1817 goto done;
1820 /* Check if we need to grow the block */
1822 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1823 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1824 if (rounded_size > oldBlockSize)
1826 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1828 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1830 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) goto oom;
1831 if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1832 memcpy( ret, pArena + 1, oldActualSize );
1833 notify_free( pArena + 1 );
1834 HEAP_MakeInUseBlockFree( subheap, pArena );
1835 goto done;
1837 if ((pNext < (char *)subheap->base + subheap->size) &&
1838 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1839 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1841 /* The next block is free and large enough */
1842 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1843 list_remove( &pFree->entry );
1844 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1845 if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1846 notify_free( pArena + 1 );
1847 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1848 notify_alloc( pArena + 1, size, FALSE );
1849 /* FIXME: this is wrong as we may lose old VBits settings */
1850 mark_block_initialized( pArena + 1, oldActualSize );
1852 else /* Do it the hard way */
1854 ARENA_FREE *pNew;
1855 ARENA_INUSE *pInUse;
1856 SUBHEAP *newsubheap;
1858 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1859 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1860 goto oom;
1862 /* Build the in-use arena */
1864 list_remove( &pNew->entry );
1865 pInUse = (ARENA_INUSE *)pNew;
1866 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1867 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1868 pInUse->magic = ARENA_INUSE_MAGIC;
1869 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1871 mark_block_initialized( pInUse + 1, oldActualSize );
1872 notify_alloc( pInUse + 1, size, FALSE );
1873 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1875 /* Free the previous block */
1877 notify_free( pArena + 1 );
1878 HEAP_MakeInUseBlockFree( subheap, pArena );
1879 subheap = newsubheap;
1880 pArena = pInUse;
1883 else
1885 /* Shrink the block */
1886 notify_free( pArena + 1 );
1887 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1888 notify_alloc( pArena + 1, size, FALSE );
1889 /* FIXME: this is wrong as we may lose old VBits settings */
1890 mark_block_initialized( pArena + 1, size );
1893 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1895 /* Clear the extra bytes if needed */
1897 if (size > oldActualSize)
1898 initialize_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize,
1899 pArena->unused_bytes, flags );
1900 else
1901 mark_block_tail( (char *)(pArena + 1) + size, pArena->unused_bytes, flags );
1903 /* Return the new arena */
1905 ret = pArena + 1;
1906 done:
1907 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1908 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1909 return ret;
1911 oom:
1912 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1913 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1914 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1915 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1916 return NULL;
1918 error:
1919 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1920 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1921 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1922 return NULL;
1926 /***********************************************************************
1927 * RtlCompactHeap (NTDLL.@)
1929 * Compact the free space in a Heap.
1931 * PARAMS
1932 * heap [I] Heap that block was allocated from
1933 * flags [I] HEAP_ flags from "winnt.h"
1935 * RETURNS
1936 * The number of bytes compacted.
1938 * NOTES
1939 * This function is a harmless stub.
1941 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1943 static BOOL reported;
1944 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1945 return 0;
1949 /***********************************************************************
1950 * RtlLockHeap (NTDLL.@)
1952 * Lock a Heap.
1954 * PARAMS
1955 * heap [I] Heap to lock
1957 * RETURNS
1958 * Success: TRUE. The Heap is locked.
1959 * Failure: FALSE, if heap is invalid.
1961 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1963 HEAP *heapPtr = HEAP_GetPtr( heap );
1964 if (!heapPtr) return FALSE;
1965 RtlEnterCriticalSection( &heapPtr->critSection );
1966 return TRUE;
1970 /***********************************************************************
1971 * RtlUnlockHeap (NTDLL.@)
1973 * Unlock a Heap.
1975 * PARAMS
1976 * heap [I] Heap to unlock
1978 * RETURNS
1979 * Success: TRUE. The Heap is unlocked.
1980 * Failure: FALSE, if heap is invalid.
1982 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1984 HEAP *heapPtr = HEAP_GetPtr( heap );
1985 if (!heapPtr) return FALSE;
1986 RtlLeaveCriticalSection( &heapPtr->critSection );
1987 return TRUE;
1991 /***********************************************************************
1992 * RtlSizeHeap (NTDLL.@)
1994 * Get the actual size of a memory block allocated from a Heap.
1996 * PARAMS
1997 * heap [I] Heap that block was allocated from
1998 * flags [I] HEAP_ flags from "winnt.h"
1999 * ptr [I] Block to get the size of
2001 * RETURNS
2002 * Success: The size of the block.
2003 * Failure: -1, heap or ptr are invalid.
2005 * NOTES
2006 * The size may be bigger than what was passed to RtlAllocateHeap().
2008 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
2010 SIZE_T ret;
2011 const ARENA_INUSE *pArena;
2012 SUBHEAP *subheap;
2013 HEAP *heapPtr = HEAP_GetPtr( heap );
2015 if (!heapPtr)
2017 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
2018 return ~0UL;
2020 flags &= HEAP_NO_SERIALIZE;
2021 flags |= heapPtr->flags;
2022 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
2024 pArena = (const ARENA_INUSE *)ptr - 1;
2025 if (!validate_block_pointer( heapPtr, &subheap, pArena ))
2027 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
2028 ret = ~0UL;
2030 else if (!subheap)
2032 const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
2033 ret = large_arena->data_size;
2035 else
2037 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
2039 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
2041 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
2042 return ret;
2046 /***********************************************************************
2047 * RtlValidateHeap (NTDLL.@)
2049 * Determine if a block is a valid allocation from a heap.
2051 * PARAMS
2052 * heap [I] Heap that block was allocated from
2053 * flags [I] HEAP_ flags from "winnt.h"
2054 * ptr [I] Block to check
2056 * RETURNS
2057 * Success: TRUE. The block was allocated from heap.
2058 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
2060 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
2062 HEAP *heapPtr = HEAP_GetPtr( heap );
2063 if (!heapPtr) return FALSE;
2064 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
2068 /***********************************************************************
2069 * RtlWalkHeap (NTDLL.@)
2071 * FIXME
2072 * The PROCESS_HEAP_ENTRY flag values seem different between this
2073 * function and HeapWalk(). To be checked.
2075 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
2077 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
2078 HEAP *heapPtr = HEAP_GetPtr(heap);
2079 SUBHEAP *sub, *currentheap = NULL;
2080 NTSTATUS ret;
2081 char *ptr;
2082 int region_index = 0;
2084 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
2086 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
2088 /* FIXME: enumerate large blocks too */
2090 /* set ptr to the next arena to be examined */
2092 if (!entry->lpData) /* first call (init) ? */
2094 TRACE("begin walking of heap %p.\n", heap);
2095 currentheap = &heapPtr->subheap;
2096 ptr = (char*)currentheap->base + currentheap->headerSize;
2098 else
2100 ptr = entry->lpData;
2101 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
2103 if ((ptr >= (char *)sub->base) &&
2104 (ptr < (char *)sub->base + sub->size))
2106 currentheap = sub;
2107 break;
2109 region_index++;
2111 if (currentheap == NULL)
2113 ERR("no matching subheap found, shouldn't happen !\n");
2114 ret = STATUS_NO_MORE_ENTRIES;
2115 goto HW_end;
2118 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC ||
2119 ((ARENA_INUSE *)ptr - 1)->magic == ARENA_PENDING_MAGIC)
2121 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
2122 ptr += pArena->size & ARENA_SIZE_MASK;
2124 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
2126 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
2127 ptr += pArena->size & ARENA_SIZE_MASK;
2129 else
2130 ptr += entry->cbData; /* point to next arena */
2132 if (ptr > (char *)currentheap->base + currentheap->size - 1)
2133 { /* proceed with next subheap */
2134 struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
2135 if (!next)
2136 { /* successfully finished */
2137 TRACE("end reached.\n");
2138 ret = STATUS_NO_MORE_ENTRIES;
2139 goto HW_end;
2141 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
2142 ptr = (char *)currentheap->base + currentheap->headerSize;
2146 entry->wFlags = 0;
2147 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2149 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2151 /*TRACE("free, magic: %04x\n", pArena->magic);*/
2153 entry->lpData = pArena + 1;
2154 entry->cbData = pArena->size & ARENA_SIZE_MASK;
2155 entry->cbOverhead = sizeof(ARENA_FREE);
2156 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
2158 else
2160 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2162 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
2164 entry->lpData = pArena + 1;
2165 entry->cbData = pArena->size & ARENA_SIZE_MASK;
2166 entry->cbOverhead = sizeof(ARENA_INUSE);
2167 entry->wFlags = (pArena->magic == ARENA_PENDING_MAGIC) ?
2168 PROCESS_HEAP_UNCOMMITTED_RANGE : PROCESS_HEAP_ENTRY_BUSY;
2169 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
2170 and PROCESS_HEAP_ENTRY_DDESHARE yet */
2173 entry->iRegionIndex = region_index;
2175 /* first element of heap ? */
2176 if (ptr == (char *)currentheap->base + currentheap->headerSize)
2178 entry->wFlags |= PROCESS_HEAP_REGION;
2179 entry->u.Region.dwCommittedSize = currentheap->commitSize;
2180 entry->u.Region.dwUnCommittedSize =
2181 currentheap->size - currentheap->commitSize;
2182 entry->u.Region.lpFirstBlock = /* first valid block */
2183 (char *)currentheap->base + currentheap->headerSize;
2184 entry->u.Region.lpLastBlock = /* first invalid block */
2185 (char *)currentheap->base + currentheap->size;
2187 ret = STATUS_SUCCESS;
2188 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
2190 HW_end:
2191 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
2192 return ret;
2196 /***********************************************************************
2197 * RtlGetProcessHeaps (NTDLL.@)
2199 * Get the Heaps belonging to the current process.
2201 * PARAMS
2202 * count [I] size of heaps
2203 * heaps [O] Destination array for heap HANDLE's
2205 * RETURNS
2206 * Success: The number of Heaps allocated by the process.
2207 * Failure: 0.
2209 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
2211 ULONG total = 1; /* main heap */
2212 struct list *ptr;
2214 RtlEnterCriticalSection( &processHeap->critSection );
2215 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
2216 if (total <= count)
2218 *heaps++ = processHeap;
2219 LIST_FOR_EACH( ptr, &processHeap->entry )
2220 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
2222 RtlLeaveCriticalSection( &processHeap->critSection );
2223 return total;
2226 /***********************************************************************
2227 * RtlQueryHeapInformation (NTDLL.@)
2229 NTSTATUS WINAPI RtlQueryHeapInformation( HANDLE heap, HEAP_INFORMATION_CLASS info_class,
2230 PVOID info, SIZE_T size_in, PSIZE_T size_out)
2232 switch (info_class)
2234 case HeapCompatibilityInformation:
2235 if (size_out) *size_out = sizeof(ULONG);
2237 if (size_in < sizeof(ULONG))
2238 return STATUS_BUFFER_TOO_SMALL;
2240 *(ULONG *)info = 0; /* standard heap */
2241 return STATUS_SUCCESS;
2243 default:
2244 FIXME("Unknown heap information class %u\n", info_class);
2245 return STATUS_INVALID_INFO_CLASS;