ddraw: Use wined3d_bit_scan() in compute_sphere_visibility().
[wine.git] / dlls / ntdll / heap.c
blob346bcf3c10cd686e49b13cdff3a2f8d363d1a052
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 <assert.h>
23 #include <stdlib.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <string.h>
28 #define RUNNING_ON_VALGRIND 0 /* FIXME */
30 #include "ntstatus.h"
31 #define WIN32_NO_STATUS
32 #define NONAMELESSUNION
33 #include "windef.h"
34 #include "winnt.h"
35 #include "winternl.h"
36 #include "ntdll_misc.h"
37 #include "wine/list.h"
38 #include "wine/debug.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(heap);
42 /* Note: the heap data structures are loosely based on what Pietrek describes in his
43 * book 'Windows 95 System Programming Secrets', with some adaptations for
44 * better compatibility with NT.
47 typedef struct tagARENA_INUSE
49 DWORD size; /* Block size; must be the first field */
50 DWORD magic : 24; /* Magic number */
51 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) */
52 } ARENA_INUSE;
54 typedef struct tagARENA_FREE
56 DWORD size; /* Block size; must be the first field */
57 DWORD magic; /* Magic number */
58 struct list entry; /* Entry in free list */
59 } ARENA_FREE;
61 typedef struct
63 struct list entry; /* entry in heap large blocks list */
64 SIZE_T data_size; /* size of user data */
65 SIZE_T block_size; /* total size of virtual memory block */
66 DWORD pad[2]; /* padding to ensure 16-byte alignment of data */
67 DWORD size; /* fields for compatibility with normal arenas */
68 DWORD magic; /* these must remain at the end of the structure */
69 } ARENA_LARGE;
71 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
72 #define ARENA_FLAG_PREV_FREE 0x00000002
73 #define ARENA_SIZE_MASK (~3)
74 #define ARENA_LARGE_SIZE 0xfedcba90 /* magic value for 'size' field in large blocks */
76 /* Value for arena 'magic' field */
77 #define ARENA_INUSE_MAGIC 0x455355
78 #define ARENA_PENDING_MAGIC 0xbedead
79 #define ARENA_FREE_MAGIC 0x45455246
80 #define ARENA_LARGE_MAGIC 0x6752614c
82 #define ARENA_INUSE_FILLER 0x55
83 #define ARENA_TAIL_FILLER 0xab
84 #define ARENA_FREE_FILLER 0xfeeefeee
86 /* everything is aligned on 8 byte boundaries (16 for Win64) */
87 #define ALIGNMENT (2*sizeof(void*))
88 #define LARGE_ALIGNMENT 16 /* large blocks have stricter alignment */
89 #define ARENA_OFFSET (ALIGNMENT - sizeof(ARENA_INUSE))
91 C_ASSERT( sizeof(ARENA_LARGE) % LARGE_ALIGNMENT == 0 );
93 #define ROUND_SIZE(size) ((((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1)) + ARENA_OFFSET)
95 #define QUIET 1 /* Suppress messages */
96 #define NOISY 0 /* Report all errors */
98 /* minimum data size (without arenas) of an allocated block */
99 /* make sure that it's larger than a free list entry */
100 #define HEAP_MIN_DATA_SIZE ROUND_SIZE(2 * sizeof(struct list))
101 #define HEAP_MIN_ARENA_SIZE (HEAP_MIN_DATA_SIZE + sizeof(ARENA_INUSE))
102 /* minimum size that must remain to shrink an allocated block */
103 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
104 /* minimum size to start allocating large blocks */
105 #define HEAP_MIN_LARGE_BLOCK_SIZE 0x7f000
106 /* extra size to add at the end of block for tail checking */
107 #define HEAP_TAIL_EXTRA_SIZE(flags) \
108 ((flags & HEAP_TAIL_CHECKING_ENABLED) || RUNNING_ON_VALGRIND ? ALIGNMENT : 0)
110 /* There will be a free list bucket for every arena size up to and including this value */
111 #define HEAP_MAX_SMALL_FREE_LIST 0x100
112 C_ASSERT( HEAP_MAX_SMALL_FREE_LIST % ALIGNMENT == 0 );
113 #define HEAP_NB_SMALL_FREE_LISTS (((HEAP_MAX_SMALL_FREE_LIST - HEAP_MIN_ARENA_SIZE) / ALIGNMENT) + 1)
115 /* Max size of the blocks on the free lists above HEAP_MAX_SMALL_FREE_LIST */
116 static const SIZE_T HEAP_freeListSizes[] =
118 0x200, 0x400, 0x1000, ~(SIZE_T)0
120 #define HEAP_NB_FREE_LISTS (ARRAY_SIZE( HEAP_freeListSizes ) + HEAP_NB_SMALL_FREE_LISTS)
122 typedef union
124 ARENA_FREE arena;
125 void *alignment[4];
126 } FREE_LIST_ENTRY;
128 struct tagHEAP;
130 typedef struct tagSUBHEAP
132 void *base; /* Base address of the sub-heap memory block */
133 SIZE_T size; /* Size of the whole sub-heap */
134 SIZE_T min_commit; /* Minimum committed size */
135 SIZE_T commitSize; /* Committed size of the sub-heap */
136 struct list entry; /* Entry in sub-heap list */
137 struct tagHEAP *heap; /* Main heap structure */
138 DWORD headerSize; /* Size of the heap header */
139 DWORD magic; /* Magic number */
140 } SUBHEAP;
142 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
144 typedef struct tagHEAP
146 DWORD_PTR unknown1[2];
147 DWORD unknown2[2];
148 DWORD_PTR unknown3[4];
149 DWORD unknown4;
150 DWORD_PTR unknown5[2];
151 DWORD unknown6[3];
152 DWORD_PTR unknown7[2];
153 /* For Vista through 10, 'flags' is at offset 0x40 (x86) / 0x70 (x64) */
154 DWORD flags; /* Heap flags */
155 DWORD force_flags; /* Forced heap flags for debugging */
156 SUBHEAP subheap; /* First sub-heap */
157 struct list entry; /* Entry in process heap list */
158 struct list subheap_list; /* Sub-heap list */
159 struct list large_list; /* Large blocks list */
160 SIZE_T grow_size; /* Size of next subheap for growing heap */
161 DWORD magic; /* Magic number */
162 DWORD pending_pos; /* Position in pending free requests ring */
163 ARENA_INUSE **pending_free; /* Ring buffer for pending free requests */
164 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
165 FREE_LIST_ENTRY *freeList; /* Free lists */
166 } HEAP;
168 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
170 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
171 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
172 #define MAX_FREE_PENDING 1024 /* max number of free requests to delay */
174 /* some undocumented flags (names are made up) */
175 #define HEAP_PAGE_ALLOCS 0x01000000
176 #define HEAP_VALIDATE 0x10000000
177 #define HEAP_VALIDATE_ALL 0x20000000
178 #define HEAP_VALIDATE_PARAMS 0x40000000
180 static HEAP *processHeap; /* main process heap */
182 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
184 /* mark a block of memory as free for debugging purposes */
185 static inline void mark_block_free( void *ptr, SIZE_T size, DWORD flags )
187 if (flags & HEAP_FREE_CHECKING_ENABLED)
189 SIZE_T i;
190 for (i = 0; i < size / sizeof(DWORD); i++) ((DWORD *)ptr)[i] = ARENA_FREE_FILLER;
192 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
193 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
194 #elif defined( VALGRIND_MAKE_NOACCESS)
195 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
196 #endif
199 /* mark a block of memory as initialized for debugging purposes */
200 static inline void mark_block_initialized( void *ptr, SIZE_T size )
202 #if defined(VALGRIND_MAKE_MEM_DEFINED)
203 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
204 #elif defined(VALGRIND_MAKE_READABLE)
205 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
206 #endif
209 /* mark a block of memory as uninitialized for debugging purposes */
210 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
212 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
213 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
214 #elif defined(VALGRIND_MAKE_WRITABLE)
215 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
216 #endif
219 /* mark a block of memory as a tail block */
220 static inline void mark_block_tail( void *ptr, SIZE_T size, DWORD flags )
222 if (flags & HEAP_TAIL_CHECKING_ENABLED)
224 mark_block_uninitialized( ptr, size );
225 memset( ptr, ARENA_TAIL_FILLER, size );
227 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
228 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
229 #elif defined( VALGRIND_MAKE_NOACCESS)
230 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
231 #endif
234 /* initialize contents of a newly created block of memory */
235 static inline void initialize_block( void *ptr, SIZE_T size, SIZE_T unused, DWORD flags )
237 if (flags & HEAP_ZERO_MEMORY)
239 mark_block_initialized( ptr, size );
240 memset( ptr, 0, size );
242 else
244 mark_block_uninitialized( ptr, size );
245 if (flags & HEAP_FREE_CHECKING_ENABLED)
247 memset( ptr, ARENA_INUSE_FILLER, size );
248 mark_block_uninitialized( ptr, size );
252 mark_block_tail( (char *)ptr + size, unused, flags );
255 /* notify that a new block of memory has been allocated for debugging purposes */
256 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
258 #ifdef VALGRIND_MALLOCLIKE_BLOCK
259 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
260 #endif
263 /* notify that a block of memory has been freed for debugging purposes */
264 static inline void notify_free( void const *ptr )
266 #ifdef VALGRIND_FREELIKE_BLOCK
267 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
268 #endif
271 static inline void notify_realloc( void const *ptr, SIZE_T size_old, SIZE_T size_new )
273 #ifdef VALGRIND_RESIZEINPLACE_BLOCK
274 /* zero is not a valid size */
275 VALGRIND_RESIZEINPLACE_BLOCK( ptr, size_old ? size_old : 1, size_new ? size_new : 1, 0 );
276 #endif
279 static void subheap_notify_free_all(SUBHEAP const *subheap)
281 #ifdef VALGRIND_FREELIKE_BLOCK
282 char const *ptr = (char const *)subheap->base + subheap->headerSize;
284 if (!RUNNING_ON_VALGRIND) return;
286 while (ptr < (char const *)subheap->base + subheap->size)
288 if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
290 ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
291 if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
292 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
294 else
296 ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
297 if (pArena->magic == ARENA_INUSE_MAGIC) notify_free(pArena + 1);
298 else if (pArena->magic != ARENA_PENDING_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
299 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
302 #endif
305 /* locate a free list entry of the appropriate size */
306 /* size is the size of the whole block including the arena header */
307 static inline unsigned int get_freelist_index( SIZE_T size )
309 unsigned int i;
311 if (size <= HEAP_MAX_SMALL_FREE_LIST)
312 return (size - HEAP_MIN_ARENA_SIZE) / ALIGNMENT;
314 for (i = HEAP_NB_SMALL_FREE_LISTS; i < HEAP_NB_FREE_LISTS - 1; i++)
315 if (size <= HEAP_freeListSizes[i - HEAP_NB_SMALL_FREE_LISTS]) break;
316 return i;
319 /* get the memory protection type to use for a given heap */
320 static inline ULONG get_protection_type( DWORD flags )
322 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
325 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
327 0, 0, NULL, /* will be set later */
328 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
329 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
333 /***********************************************************************
334 * HEAP_Dump
336 static void HEAP_Dump( HEAP *heap )
338 unsigned int i;
339 SUBHEAP *subheap;
340 char *ptr;
342 TRACE( "Heap: %p\n", heap );
343 TRACE( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
344 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) TRACE( " %p", subheap );
346 TRACE( "\nFree lists:\n Block Stat Size Id\n" );
347 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
348 TRACE( "%p free %08lx prev=%p next=%p\n",
349 &heap->freeList[i].arena, i < HEAP_NB_SMALL_FREE_LISTS ?
350 HEAP_MIN_ARENA_SIZE + i * ALIGNMENT : HEAP_freeListSizes[i - HEAP_NB_SMALL_FREE_LISTS],
351 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
352 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
354 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
356 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
357 TRACE( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
358 subheap, subheap->base, subheap->size, subheap->commitSize );
360 TRACE( "\n Block Arena Stat Size Id\n" );
361 ptr = (char *)subheap->base + subheap->headerSize;
362 while (ptr < (char *)subheap->base + subheap->size)
364 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
366 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
367 TRACE( "%p %08x free %08x prev=%p next=%p\n",
368 pArena, pArena->magic,
369 pArena->size & ARENA_SIZE_MASK,
370 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
371 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
372 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
373 arenaSize += sizeof(ARENA_FREE);
374 freeSize += pArena->size & ARENA_SIZE_MASK;
376 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
378 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
379 TRACE( "%p %08x Used %08x back=%p\n",
380 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
381 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
382 arenaSize += sizeof(ARENA_INUSE);
383 usedSize += pArena->size & ARENA_SIZE_MASK;
385 else
387 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
388 TRACE( "%p %08x %s %08x\n",
389 pArena, pArena->magic, pArena->magic == ARENA_INUSE_MAGIC ? "used" : "pend",
390 pArena->size & ARENA_SIZE_MASK );
391 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
392 arenaSize += sizeof(ARENA_INUSE);
393 usedSize += pArena->size & ARENA_SIZE_MASK;
396 TRACE( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
397 subheap->size, subheap->commitSize, freeSize, usedSize,
398 arenaSize, (arenaSize * 100) / subheap->size );
403 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
405 WORD rem_flags;
406 TRACE( "Dumping entry %p\n", entry );
407 TRACE( "lpData\t\t: %p\n", entry->lpData );
408 TRACE( "cbData\t\t: %08x\n", entry->cbData);
409 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
410 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
411 TRACE( "WFlags\t\t: ");
412 if (entry->wFlags & PROCESS_HEAP_REGION)
413 TRACE( "PROCESS_HEAP_REGION ");
414 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
415 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
416 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
417 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
418 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
419 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
420 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
421 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
422 rem_flags = entry->wFlags &
423 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
424 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
425 PROCESS_HEAP_ENTRY_DDESHARE);
426 if (rem_flags)
427 TRACE( "Unknown %08x", rem_flags);
428 TRACE( "\n");
429 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
430 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
432 /* Treat as block */
433 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
435 if (entry->wFlags & PROCESS_HEAP_REGION)
437 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
438 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
439 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
440 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
444 /***********************************************************************
445 * HEAP_GetPtr
446 * RETURNS
447 * Pointer to the heap
448 * NULL: Failure
450 static HEAP *HEAP_GetPtr(
451 HANDLE heap /* [in] Handle to the heap */
453 HEAP *heapPtr = heap;
454 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
456 ERR("Invalid heap %p!\n", heap );
457 return NULL;
459 if ((heapPtr->flags & HEAP_VALIDATE_ALL) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
461 if (TRACE_ON(heap))
463 HEAP_Dump( heapPtr );
464 assert( FALSE );
466 return NULL;
468 return heapPtr;
472 /***********************************************************************
473 * HEAP_InsertFreeBlock
475 * Insert a free block into the free list.
477 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
479 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
480 if (last)
482 /* insert at end of free list, i.e. before the next free list entry */
483 pEntry++;
484 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
485 list_add_before( &pEntry->arena.entry, &pArena->entry );
487 else
489 /* insert at head of free list */
490 list_add_after( &pEntry->arena.entry, &pArena->entry );
492 pArena->size |= ARENA_FLAG_FREE;
496 /***********************************************************************
497 * HEAP_FindSubHeap
498 * Find the sub-heap containing a given address.
500 * RETURNS
501 * Pointer: Success
502 * NULL: Failure
504 static SUBHEAP *HEAP_FindSubHeap(
505 const HEAP *heap, /* [in] Heap pointer */
506 LPCVOID ptr ) /* [in] Address */
508 SUBHEAP *sub;
509 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
510 if ((ptr >= sub->base) &&
511 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
512 return sub;
513 return NULL;
517 /***********************************************************************
518 * HEAP_Commit
520 * Make sure the heap storage is committed for a given size in the specified arena.
522 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
524 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
525 SIZE_T size = (char *)ptr - (char *)subheap->base;
526 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
527 if (size > subheap->size) size = subheap->size;
528 if (size <= subheap->commitSize) return TRUE;
529 size -= subheap->commitSize;
530 ptr = (char *)subheap->base + subheap->commitSize;
531 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
532 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
534 WARN("Could not commit %08lx bytes at %p for heap %p\n",
535 size, ptr, subheap->heap );
536 return FALSE;
538 subheap->commitSize += size;
539 return TRUE;
543 /***********************************************************************
544 * HEAP_Decommit
546 * If possible, decommit the heap storage from (including) 'ptr'.
548 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
550 void *addr;
551 SIZE_T decommit_size;
552 SIZE_T size = (char *)ptr - (char *)subheap->base;
554 /* round to next block and add one full block */
555 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
556 size = max( size, subheap->min_commit );
557 if (size >= subheap->commitSize) return TRUE;
558 decommit_size = subheap->commitSize - size;
559 addr = (char *)subheap->base + size;
561 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
563 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
564 decommit_size, (char *)subheap->base + size, subheap->heap );
565 return FALSE;
567 subheap->commitSize -= decommit_size;
568 return TRUE;
572 /***********************************************************************
573 * HEAP_CreateFreeBlock
575 * Create a free block at a specified address. 'size' is the size of the
576 * whole block, including the new arena.
578 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
580 ARENA_FREE *pFree;
581 char *pEnd;
582 BOOL last;
583 DWORD flags = subheap->heap->flags;
585 /* Create a free arena */
586 mark_block_uninitialized( ptr, sizeof(ARENA_FREE) );
587 pFree = ptr;
588 pFree->magic = ARENA_FREE_MAGIC;
590 /* If debugging, erase the freed block content */
592 pEnd = (char *)ptr + size;
593 if (pEnd > (char *)subheap->base + subheap->commitSize)
594 pEnd = (char *)subheap->base + subheap->commitSize;
595 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1), flags );
597 /* Check if next block is free also */
599 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
600 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
602 /* Remove the next arena from the free list */
603 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
604 list_remove( &pNext->entry );
605 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
606 mark_block_free( pNext, sizeof(ARENA_FREE), flags );
609 /* Set the next block PREV_FREE flag and pointer */
611 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
612 if (!last)
614 DWORD *pNext = (DWORD *)((char *)ptr + size);
615 *pNext |= ARENA_FLAG_PREV_FREE;
616 mark_block_initialized( (ARENA_FREE **)pNext - 1, sizeof( ARENA_FREE * ) );
617 *((ARENA_FREE **)pNext - 1) = pFree;
620 /* Last, insert the new block into the free list */
622 pFree->size = size - sizeof(*pFree);
623 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
627 /***********************************************************************
628 * HEAP_MakeInUseBlockFree
630 * Turn an in-use block into a free block. Can also decommit the end of
631 * the heap, and possibly even free the sub-heap altogether.
633 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
635 HEAP *heap = subheap->heap;
636 ARENA_FREE *pFree;
637 SIZE_T size;
639 if (heap->pending_free)
641 ARENA_INUSE *prev = heap->pending_free[heap->pending_pos];
642 heap->pending_free[heap->pending_pos] = pArena;
643 heap->pending_pos = (heap->pending_pos + 1) % MAX_FREE_PENDING;
644 pArena->magic = ARENA_PENDING_MAGIC;
645 mark_block_free( pArena + 1, pArena->size & ARENA_SIZE_MASK, heap->flags );
646 if (!prev) return;
647 pArena = prev;
648 subheap = HEAP_FindSubHeap( heap, pArena );
651 /* Check if we can merge with previous block */
653 size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
654 if (pArena->size & ARENA_FLAG_PREV_FREE)
656 pFree = *((ARENA_FREE **)pArena - 1);
657 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
658 /* Remove it from the free list */
659 list_remove( &pFree->entry );
661 else pFree = (ARENA_FREE *)pArena;
663 /* Create a free block */
665 HEAP_CreateFreeBlock( subheap, pFree, size );
666 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
667 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
668 return; /* Not the last block, so nothing more to do */
670 /* Free the whole sub-heap if it's empty and not the original one */
672 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
673 (subheap != &subheap->heap->subheap))
675 void *addr = subheap->base;
677 size = 0;
678 /* Remove the free block from the list */
679 list_remove( &pFree->entry );
680 /* Remove the subheap from the list */
681 list_remove( &subheap->entry );
682 /* Free the memory */
683 subheap->magic = 0;
684 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
685 return;
688 /* Decommit the end of the heap */
690 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
694 /***********************************************************************
695 * HEAP_ShrinkBlock
697 * Shrink an in-use block.
699 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
701 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
703 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
704 (pArena->size & ARENA_SIZE_MASK) - size );
705 /* assign size plus previous arena flags */
706 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
708 else
710 /* Turn off PREV_FREE flag in next block */
711 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
712 if (pNext < (char *)subheap->base + subheap->size)
713 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
718 /***********************************************************************
719 * allocate_large_block
721 static void *allocate_large_block( HEAP *heap, DWORD flags, SIZE_T size )
723 ARENA_LARGE *arena;
724 SIZE_T block_size = sizeof(*arena) + ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE(flags);
725 LPVOID address = NULL;
727 if (block_size < size) return NULL; /* overflow */
728 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &block_size,
729 MEM_COMMIT, get_protection_type( flags )))
731 WARN("Could not allocate block for %08lx bytes\n", size );
732 return NULL;
734 arena = address;
735 arena->data_size = size;
736 arena->block_size = block_size;
737 arena->size = ARENA_LARGE_SIZE;
738 arena->magic = ARENA_LARGE_MAGIC;
739 mark_block_tail( (char *)(arena + 1) + size, block_size - sizeof(*arena) - size, flags );
740 list_add_tail( &heap->large_list, &arena->entry );
741 notify_alloc( arena + 1, size, flags & HEAP_ZERO_MEMORY );
742 return arena + 1;
746 /***********************************************************************
747 * free_large_block
749 static void free_large_block( HEAP *heap, DWORD flags, void *ptr )
751 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
752 LPVOID address = arena;
753 SIZE_T size = 0;
755 list_remove( &arena->entry );
756 NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
760 /***********************************************************************
761 * realloc_large_block
763 static void *realloc_large_block( HEAP *heap, DWORD flags, void *ptr, SIZE_T size )
765 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
766 void *new_ptr;
768 if (arena->block_size - sizeof(*arena) >= size)
770 SIZE_T unused = arena->block_size - sizeof(*arena) - size;
772 /* FIXME: we could remap zero-pages instead */
773 #ifdef VALGRIND_RESIZEINPLACE_BLOCK
774 if (RUNNING_ON_VALGRIND)
775 notify_realloc( arena + 1, arena->data_size, size );
776 else
777 #endif
778 if (size > arena->data_size)
779 initialize_block( (char *)ptr + arena->data_size, size - arena->data_size, unused, flags );
780 else
781 mark_block_tail( (char *)ptr + size, unused, flags );
782 arena->data_size = size;
783 return ptr;
785 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) return NULL;
786 if (!(new_ptr = allocate_large_block( heap, flags, size )))
788 WARN("Could not allocate block for %08lx bytes\n", size );
789 return NULL;
791 memcpy( new_ptr, ptr, arena->data_size );
792 free_large_block( heap, flags, ptr );
793 notify_free( ptr );
794 return new_ptr;
798 /***********************************************************************
799 * find_large_block
801 static ARENA_LARGE *find_large_block( HEAP *heap, const void *ptr )
803 ARENA_LARGE *arena;
805 LIST_FOR_EACH_ENTRY( arena, &heap->large_list, ARENA_LARGE, entry )
806 if (ptr == arena + 1) return arena;
808 return NULL;
812 /***********************************************************************
813 * validate_large_arena
815 static BOOL validate_large_arena( HEAP *heap, const ARENA_LARGE *arena, BOOL quiet )
817 DWORD flags = heap->flags;
819 if ((ULONG_PTR)arena % page_size)
821 if (quiet == NOISY)
823 ERR( "Heap %p: invalid large arena pointer %p\n", heap, arena );
824 if (TRACE_ON(heap)) HEAP_Dump( heap );
826 else if (WARN_ON(heap))
828 WARN( "Heap %p: unaligned arena pointer %p\n", heap, arena );
829 if (TRACE_ON(heap)) HEAP_Dump( heap );
831 return FALSE;
833 if (arena->size != ARENA_LARGE_SIZE || arena->magic != ARENA_LARGE_MAGIC)
835 if (quiet == NOISY)
837 ERR( "Heap %p: invalid large arena %p values %x/%x\n",
838 heap, arena, arena->size, arena->magic );
839 if (TRACE_ON(heap)) HEAP_Dump( heap );
841 else if (WARN_ON(heap))
843 WARN( "Heap %p: invalid large arena %p values %x/%x\n",
844 heap, arena, arena->size, arena->magic );
845 if (TRACE_ON(heap)) HEAP_Dump( heap );
847 return FALSE;
849 if (arena->data_size > arena->block_size - sizeof(*arena))
851 ERR( "Heap %p: invalid large arena %p size %lx/%lx\n",
852 heap, arena, arena->data_size, arena->block_size );
853 return FALSE;
855 if (flags & HEAP_TAIL_CHECKING_ENABLED)
857 SIZE_T i, unused = arena->block_size - sizeof(*arena) - arena->data_size;
858 const unsigned char *data = (const unsigned char *)(arena + 1) + arena->data_size;
860 for (i = 0; i < unused; i++)
862 if (data[i] == ARENA_TAIL_FILLER) continue;
863 ERR("Heap %p: block %p tail overwritten at %p (byte %lu/%lu == 0x%02x)\n",
864 heap, arena + 1, data + i, i, unused, data[i] );
865 return FALSE;
868 return TRUE;
872 /***********************************************************************
873 * HEAP_CreateSubHeap
875 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, LPVOID address, DWORD flags,
876 SIZE_T commitSize, SIZE_T totalSize )
878 SUBHEAP *subheap;
879 FREE_LIST_ENTRY *pEntry;
880 unsigned int i;
882 if (!address)
884 if (!commitSize) commitSize = COMMIT_MASK + 1;
885 totalSize = min( totalSize, 0xffff0000 ); /* don't allow a heap larger than 4GB */
886 if (totalSize < commitSize) totalSize = commitSize;
887 if (flags & HEAP_SHARED) commitSize = totalSize; /* always commit everything in a shared heap */
888 commitSize = min( totalSize, (commitSize + COMMIT_MASK) & ~COMMIT_MASK );
890 /* allocate the memory block */
891 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
892 MEM_RESERVE, get_protection_type( flags ) ))
894 WARN("Could not allocate %08lx bytes\n", totalSize );
895 return NULL;
897 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
898 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
900 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
901 return NULL;
905 if (heap)
907 /* If this is a secondary subheap, insert it into list */
909 subheap = address;
910 subheap->base = address;
911 subheap->heap = heap;
912 subheap->size = totalSize;
913 subheap->min_commit = 0x10000;
914 subheap->commitSize = commitSize;
915 subheap->magic = SUBHEAP_MAGIC;
916 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
917 list_add_head( &heap->subheap_list, &subheap->entry );
919 else
921 /* If this is a primary subheap, initialize main heap */
923 heap = address;
924 heap->flags = flags;
925 heap->magic = HEAP_MAGIC;
926 heap->grow_size = max( HEAP_DEF_SIZE, totalSize );
927 list_init( &heap->subheap_list );
928 list_init( &heap->large_list );
930 subheap = &heap->subheap;
931 subheap->base = address;
932 subheap->heap = heap;
933 subheap->size = totalSize;
934 subheap->min_commit = commitSize;
935 subheap->commitSize = commitSize;
936 subheap->magic = SUBHEAP_MAGIC;
937 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
938 list_add_head( &heap->subheap_list, &subheap->entry );
940 /* Build the free lists */
942 heap->freeList = (FREE_LIST_ENTRY *)((char *)heap + subheap->headerSize);
943 subheap->headerSize += HEAP_NB_FREE_LISTS * sizeof(FREE_LIST_ENTRY);
944 list_init( &heap->freeList[0].arena.entry );
945 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
947 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
948 pEntry->arena.magic = ARENA_FREE_MAGIC;
949 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
952 /* Initialize critical section */
954 if (!processHeap) /* do it by hand to avoid memory allocations */
956 heap->critSection.DebugInfo = &process_heap_critsect_debug;
957 heap->critSection.LockCount = -1;
958 heap->critSection.RecursionCount = 0;
959 heap->critSection.OwningThread = 0;
960 heap->critSection.LockSemaphore = 0;
961 heap->critSection.SpinCount = 0;
962 process_heap_critsect_debug.CriticalSection = &heap->critSection;
964 else
966 RtlInitializeCriticalSection( &heap->critSection );
967 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
970 if (flags & HEAP_SHARED)
972 /* let's assume that only one thread at a time will try to do this */
973 HANDLE sem = heap->critSection.LockSemaphore;
974 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
976 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
977 DUPLICATE_MAKE_GLOBAL | DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE );
978 heap->critSection.LockSemaphore = sem;
979 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
980 heap->critSection.DebugInfo = NULL;
984 /* Create the first free block */
986 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
987 subheap->size - subheap->headerSize );
989 return subheap;
993 /***********************************************************************
994 * HEAP_FindFreeBlock
996 * Find a free block at least as large as the requested size, and make sure
997 * the requested size is committed.
999 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
1000 SUBHEAP **ppSubHeap )
1002 SUBHEAP *subheap;
1003 struct list *ptr;
1004 SIZE_T total_size;
1005 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
1007 /* Find a suitable free list, and in it find a block large enough */
1009 ptr = &pEntry->arena.entry;
1010 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
1012 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
1013 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
1014 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1015 if (arena_size >= size)
1017 subheap = HEAP_FindSubHeap( heap, pArena );
1018 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
1019 *ppSubHeap = subheap;
1020 return pArena;
1024 /* If no block was found, attempt to grow the heap */
1026 if (!(heap->flags & HEAP_GROWABLE))
1028 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
1029 return NULL;
1031 /* make sure that we have a big enough size *committed* to fit another
1032 * last free arena in !
1033 * So just one heap struct, one first free arena which will eventually
1034 * get used, and a second free arena that might get assigned all remaining
1035 * free space in HEAP_ShrinkBlock() */
1036 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
1037 if (total_size < size) return NULL; /* overflow */
1039 if ((subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
1040 max( heap->grow_size, total_size ) )))
1042 if (heap->grow_size < 128 * 1024 * 1024) heap->grow_size *= 2;
1044 else while (!subheap) /* shrink the grow size again if we are running out of space */
1046 if (heap->grow_size <= total_size || heap->grow_size <= 4 * 1024 * 1024) return NULL;
1047 heap->grow_size /= 2;
1048 subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
1049 max( heap->grow_size, total_size ) );
1052 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
1053 subheap, subheap->size, heap );
1055 *ppSubHeap = subheap;
1056 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
1060 /***********************************************************************
1061 * HEAP_IsValidArenaPtr
1063 * Check that the pointer is inside the range possible for arenas.
1065 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
1067 unsigned int i;
1068 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
1069 if (!subheap) return FALSE;
1070 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
1071 if (subheap != &heap->subheap) return FALSE;
1072 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
1073 if (ptr == &heap->freeList[i].arena) return TRUE;
1074 return FALSE;
1078 /***********************************************************************
1079 * HEAP_ValidateFreeArena
1081 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
1083 DWORD flags = subheap->heap->flags;
1084 SIZE_T size;
1085 ARENA_FREE *prev, *next;
1086 char *heapEnd = (char *)subheap->base + subheap->size;
1088 /* Check for unaligned pointers */
1089 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1091 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1092 return FALSE;
1095 /* Check magic number */
1096 if (pArena->magic != ARENA_FREE_MAGIC)
1098 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1099 return FALSE;
1101 /* Check size flags */
1102 if (!(pArena->size & ARENA_FLAG_FREE) ||
1103 (pArena->size & ARENA_FLAG_PREV_FREE))
1105 ERR("Heap %p: bad flags %08x for free arena %p\n",
1106 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1107 return FALSE;
1109 /* Check arena size */
1110 size = pArena->size & ARENA_SIZE_MASK;
1111 if ((char *)(pArena + 1) + size > heapEnd)
1113 ERR("Heap %p: bad size %08lx for free arena %p\n", subheap->heap, size, pArena );
1114 return FALSE;
1116 /* Check that next pointer is valid */
1117 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
1118 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
1120 ERR("Heap %p: bad next ptr %p for arena %p\n",
1121 subheap->heap, next, pArena );
1122 return FALSE;
1124 /* Check that next arena is free */
1125 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1127 ERR("Heap %p: next arena %p invalid for %p\n",
1128 subheap->heap, next, pArena );
1129 return FALSE;
1131 /* Check that prev pointer is valid */
1132 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1133 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1135 ERR("Heap %p: bad prev ptr %p for arena %p\n",
1136 subheap->heap, prev, pArena );
1137 return FALSE;
1139 /* Check that prev arena is free */
1140 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1142 /* this often means that the prev arena got overwritten
1143 * by a memory write before that prev arena */
1144 ERR("Heap %p: prev arena %p invalid for %p\n",
1145 subheap->heap, prev, pArena );
1146 return FALSE;
1148 /* Check that next block has PREV_FREE flag */
1149 if ((char *)(pArena + 1) + size < heapEnd)
1151 if (!(*(DWORD *)((char *)(pArena + 1) + size) & ARENA_FLAG_PREV_FREE))
1153 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1154 subheap->heap, pArena );
1155 return FALSE;
1157 /* Check next block back pointer */
1158 if (*((ARENA_FREE **)((char *)(pArena + 1) + size) - 1) != pArena)
1160 ERR("Heap %p: arena %p has wrong back ptr %p\n",
1161 subheap->heap, pArena,
1162 *((ARENA_FREE **)((char *)(pArena+1) + size) - 1));
1163 return FALSE;
1166 if (flags & HEAP_FREE_CHECKING_ENABLED)
1168 DWORD *ptr = (DWORD *)(pArena + 1);
1169 char *end = (char *)(pArena + 1) + size;
1171 if (end >= heapEnd) end = (char *)subheap->base + subheap->commitSize;
1172 else end -= sizeof(ARENA_FREE *);
1173 while (ptr < (DWORD *)end)
1175 if (*ptr != ARENA_FREE_FILLER)
1177 ERR("Heap %p: free block %p overwritten at %p by %08x\n",
1178 subheap->heap, (ARENA_INUSE *)pArena + 1, ptr, *ptr );
1179 return FALSE;
1181 ptr++;
1184 return TRUE;
1188 /***********************************************************************
1189 * HEAP_ValidateInUseArena
1191 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1193 SIZE_T size;
1194 DWORD i, flags = subheap->heap->flags;
1195 const char *heapEnd = (const char *)subheap->base + subheap->size;
1197 /* Check for unaligned pointers */
1198 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1200 if ( quiet == NOISY )
1202 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1203 if ( TRACE_ON(heap) )
1204 HEAP_Dump( subheap->heap );
1206 else if ( WARN_ON(heap) )
1208 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1209 if ( TRACE_ON(heap) )
1210 HEAP_Dump( subheap->heap );
1212 return FALSE;
1215 /* Check magic number */
1216 if (pArena->magic != ARENA_INUSE_MAGIC && pArena->magic != ARENA_PENDING_MAGIC)
1218 if (quiet == NOISY) {
1219 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1220 if (TRACE_ON(heap))
1221 HEAP_Dump( subheap->heap );
1222 } else if (WARN_ON(heap)) {
1223 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1224 if (TRACE_ON(heap))
1225 HEAP_Dump( subheap->heap );
1227 return FALSE;
1229 /* Check size flags */
1230 if (pArena->size & ARENA_FLAG_FREE)
1232 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1233 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1234 return FALSE;
1236 /* Check arena size */
1237 size = pArena->size & ARENA_SIZE_MASK;
1238 if ((const char *)(pArena + 1) + size > heapEnd ||
1239 (const char *)(pArena + 1) + size < (const char *)(pArena + 1))
1241 ERR("Heap %p: bad size %08lx for in-use arena %p\n", subheap->heap, size, pArena );
1242 return FALSE;
1244 /* Check next arena PREV_FREE flag */
1245 if (((const char *)(pArena + 1) + size < heapEnd) &&
1246 (*(const DWORD *)((const char *)(pArena + 1) + size) & ARENA_FLAG_PREV_FREE))
1248 ERR("Heap %p: in-use arena %p next block %p has PREV_FREE flag %x\n",
1249 subheap->heap, pArena, (const char *)(pArena + 1) + size,*(const DWORD *)((const char *)(pArena + 1) + size) );
1250 return FALSE;
1252 /* Check prev free arena */
1253 if (pArena->size & ARENA_FLAG_PREV_FREE)
1255 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1256 /* Check prev pointer */
1257 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1259 ERR("Heap %p: bad back ptr %p for arena %p\n",
1260 subheap->heap, pPrev, pArena );
1261 return FALSE;
1263 /* Check that prev arena is free */
1264 if (!(pPrev->size & ARENA_FLAG_FREE) ||
1265 (pPrev->magic != ARENA_FREE_MAGIC))
1267 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1268 subheap->heap, pPrev, pArena );
1269 return FALSE;
1271 /* Check that prev arena is really the previous block */
1272 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1274 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1275 subheap->heap, pPrev, pArena );
1276 return FALSE;
1279 /* Check unused size */
1280 if (pArena->unused_bytes > size)
1282 ERR("Heap %p: invalid unused size %08x/%08lx\n", subheap->heap, pArena->unused_bytes, size );
1283 return FALSE;
1285 /* Check unused bytes */
1286 if (pArena->magic == ARENA_PENDING_MAGIC)
1288 const DWORD *ptr = (const DWORD *)(pArena + 1);
1289 const DWORD *end = (const DWORD *)((const char *)ptr + size);
1291 while (ptr < end)
1293 if (*ptr != ARENA_FREE_FILLER)
1295 ERR("Heap %p: free block %p overwritten at %p by %08x\n",
1296 subheap->heap, pArena + 1, ptr, *ptr );
1297 if (!*ptr) { HEAP_Dump( subheap->heap ); DbgBreakPoint(); }
1298 return FALSE;
1300 ptr++;
1303 else if (flags & HEAP_TAIL_CHECKING_ENABLED)
1305 const unsigned char *data = (const unsigned char *)(pArena + 1) + size - pArena->unused_bytes;
1307 for (i = 0; i < pArena->unused_bytes; i++)
1309 if (data[i] == ARENA_TAIL_FILLER) continue;
1310 ERR("Heap %p: block %p tail overwritten at %p (byte %u/%u == 0x%02x)\n",
1311 subheap->heap, pArena + 1, data + i, i, pArena->unused_bytes, data[i] );
1312 return FALSE;
1315 return TRUE;
1319 /***********************************************************************
1320 * HEAP_IsRealArena [Internal]
1321 * Validates a block is a valid arena.
1323 * RETURNS
1324 * TRUE: Success
1325 * FALSE: Failure
1327 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1328 DWORD flags, /* [in] Bit flags that control access during operation */
1329 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1330 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1331 * does not complain */
1333 SUBHEAP *subheap;
1334 BOOL ret = FALSE;
1335 const ARENA_LARGE *large_arena;
1337 flags &= HEAP_NO_SERIALIZE;
1338 flags |= heapPtr->flags;
1339 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1340 if (!(flags & HEAP_NO_SERIALIZE))
1341 RtlEnterCriticalSection( &heapPtr->critSection );
1343 if (block) /* only check this single memory block */
1345 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1347 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1348 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1350 if (!(large_arena = find_large_block( heapPtr, block )))
1352 if (quiet == NOISY)
1353 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1354 else if (WARN_ON(heap))
1355 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1357 else ret = validate_large_arena( heapPtr, large_arena, quiet );
1359 else ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1360 goto done;
1363 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1365 char *ptr = (char *)subheap->base + subheap->headerSize;
1366 while (ptr < (char *)subheap->base + subheap->size)
1368 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1370 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) goto done;
1371 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1373 else
1375 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) goto done;
1376 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1381 LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1382 if (!validate_large_arena( heapPtr, large_arena, quiet )) goto done;
1384 ret = TRUE;
1386 done:
1387 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1388 return ret;
1392 /***********************************************************************
1393 * validate_block_pointer
1395 * Minimum validation needed to catch bad parameters in heap functions.
1397 static BOOL validate_block_pointer( HEAP *heap, SUBHEAP **ret_subheap, const ARENA_INUSE *arena )
1399 SUBHEAP *subheap;
1400 BOOL ret = FALSE;
1402 if (!(*ret_subheap = subheap = HEAP_FindSubHeap( heap, arena )))
1404 ARENA_LARGE *large_arena = find_large_block( heap, arena + 1 );
1406 if (!large_arena)
1408 WARN( "Heap %p: pointer %p is not inside heap\n", heap, arena + 1 );
1409 return FALSE;
1411 if ((heap->flags & HEAP_VALIDATE) && !validate_large_arena( heap, large_arena, QUIET ))
1412 return FALSE;
1413 return TRUE;
1416 if ((const char *)arena < (char *)subheap->base + subheap->headerSize)
1417 WARN( "Heap %p: pointer %p is inside subheap %p header\n", subheap->heap, arena + 1, subheap );
1418 else if (subheap->heap->flags & HEAP_VALIDATE) /* do the full validation */
1419 ret = HEAP_ValidateInUseArena( subheap, arena, QUIET );
1420 else if ((ULONG_PTR)arena % ALIGNMENT != ARENA_OFFSET)
1421 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, arena );
1422 else if (arena->magic == ARENA_PENDING_MAGIC)
1423 WARN( "Heap %p: block %p used after free\n", subheap->heap, arena + 1 );
1424 else if (arena->magic != ARENA_INUSE_MAGIC)
1425 WARN( "Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, arena->magic, arena );
1426 else if (arena->size & ARENA_FLAG_FREE)
1427 ERR( "Heap %p: bad flags %08x for in-use arena %p\n",
1428 subheap->heap, arena->size & ~ARENA_SIZE_MASK, arena );
1429 else if ((const char *)(arena + 1) + (arena->size & ARENA_SIZE_MASK) > (const char *)subheap->base + subheap->size ||
1430 (const char *)(arena + 1) + (arena->size & ARENA_SIZE_MASK) < (const char *)(arena + 1))
1431 ERR( "Heap %p: bad size %08x for in-use arena %p\n",
1432 subheap->heap, arena->size & ARENA_SIZE_MASK, arena );
1433 else
1434 ret = TRUE;
1436 return ret;
1440 /***********************************************************************
1441 * heap_set_debug_flags
1443 static void heap_set_debug_flags( HANDLE handle )
1445 HEAP *heap = HEAP_GetPtr( handle );
1446 ULONG global_flags = RtlGetNtGlobalFlags();
1447 ULONG flags = 0;
1449 if (TRACE_ON(heap)) global_flags |= FLG_HEAP_VALIDATE_ALL;
1450 if (WARN_ON(heap)) global_flags |= FLG_HEAP_VALIDATE_PARAMETERS;
1452 if (global_flags & FLG_HEAP_ENABLE_TAIL_CHECK) flags |= HEAP_TAIL_CHECKING_ENABLED;
1453 if (global_flags & FLG_HEAP_ENABLE_FREE_CHECK) flags |= HEAP_FREE_CHECKING_ENABLED;
1454 if (global_flags & FLG_HEAP_DISABLE_COALESCING) flags |= HEAP_DISABLE_COALESCE_ON_FREE;
1455 if (global_flags & FLG_HEAP_PAGE_ALLOCS) flags |= HEAP_PAGE_ALLOCS | HEAP_GROWABLE;
1457 if (global_flags & FLG_HEAP_VALIDATE_PARAMETERS)
1458 flags |= HEAP_VALIDATE | HEAP_VALIDATE_PARAMS |
1459 HEAP_TAIL_CHECKING_ENABLED | HEAP_FREE_CHECKING_ENABLED;
1460 if (global_flags & FLG_HEAP_VALIDATE_ALL)
1461 flags |= HEAP_VALIDATE | HEAP_VALIDATE_ALL |
1462 HEAP_TAIL_CHECKING_ENABLED | HEAP_FREE_CHECKING_ENABLED;
1464 if (RUNNING_ON_VALGRIND) flags = 0; /* no sense in validating since Valgrind catches accesses */
1466 heap->flags |= flags;
1467 heap->force_flags |= flags & ~(HEAP_VALIDATE | HEAP_DISABLE_COALESCE_ON_FREE);
1469 if (flags & (HEAP_FREE_CHECKING_ENABLED | HEAP_TAIL_CHECKING_ENABLED)) /* fix existing blocks */
1471 SUBHEAP *subheap;
1472 ARENA_LARGE *large;
1474 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
1476 char *ptr = (char *)subheap->base + subheap->headerSize;
1477 char *end = (char *)subheap->base + subheap->commitSize;
1478 while (ptr < end)
1480 ARENA_INUSE *arena = (ARENA_INUSE *)ptr;
1481 SIZE_T size = arena->size & ARENA_SIZE_MASK;
1482 if (arena->size & ARENA_FLAG_FREE)
1484 SIZE_T count = size;
1486 ptr += sizeof(ARENA_FREE) + size;
1487 if (ptr >= end) count = end - (char *)((ARENA_FREE *)arena + 1);
1488 else count -= sizeof(ARENA_FREE *);
1489 mark_block_free( (ARENA_FREE *)arena + 1, count, flags );
1491 else
1493 if (arena->magic == ARENA_PENDING_MAGIC)
1494 mark_block_free( arena + 1, size, flags );
1495 else
1496 mark_block_tail( (char *)(arena + 1) + size - arena->unused_bytes,
1497 arena->unused_bytes, flags );
1498 ptr += sizeof(ARENA_INUSE) + size;
1503 LIST_FOR_EACH_ENTRY( large, &heap->large_list, ARENA_LARGE, entry )
1504 mark_block_tail( (char *)(large + 1) + large->data_size,
1505 large->block_size - sizeof(*large) - large->data_size, flags );
1508 if ((heap->flags & HEAP_GROWABLE) && !heap->pending_free &&
1509 ((flags & HEAP_FREE_CHECKING_ENABLED) || RUNNING_ON_VALGRIND))
1511 heap->pending_free = RtlAllocateHeap( handle, HEAP_ZERO_MEMORY,
1512 MAX_FREE_PENDING * sizeof(*heap->pending_free) );
1513 heap->pending_pos = 0;
1518 /***********************************************************************
1519 * RtlCreateHeap (NTDLL.@)
1521 * Create a new Heap.
1523 * PARAMS
1524 * flags [I] HEAP_ flags from "winnt.h"
1525 * addr [I] Desired base address
1526 * totalSize [I] Total size of the heap, or 0 for a growable heap
1527 * commitSize [I] Amount of heap space to commit
1528 * unknown [I] Not yet understood
1529 * definition [I] Heap definition
1531 * RETURNS
1532 * Success: A HANDLE to the newly created heap.
1533 * Failure: a NULL HANDLE.
1535 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1536 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1538 SUBHEAP *subheap;
1540 /* Allocate the heap block */
1542 if (!totalSize)
1544 totalSize = HEAP_DEF_SIZE;
1545 flags |= HEAP_GROWABLE;
1548 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1550 heap_set_debug_flags( subheap->heap );
1552 /* link it into the per-process heap list */
1553 if (processHeap)
1555 HEAP *heapPtr = subheap->heap;
1556 RtlEnterCriticalSection( &processHeap->critSection );
1557 list_add_head( &processHeap->entry, &heapPtr->entry );
1558 RtlLeaveCriticalSection( &processHeap->critSection );
1560 else if (!addr)
1562 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1563 list_init( &processHeap->entry );
1566 return subheap->heap;
1570 /***********************************************************************
1571 * RtlDestroyHeap (NTDLL.@)
1573 * Destroy a Heap created with RtlCreateHeap().
1575 * PARAMS
1576 * heap [I] Heap to destroy.
1578 * RETURNS
1579 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1580 * Failure: The Heap handle, if heap is the process heap.
1582 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1584 HEAP *heapPtr = HEAP_GetPtr( heap );
1585 SUBHEAP *subheap, *next;
1586 ARENA_LARGE *arena, *arena_next;
1587 SIZE_T size;
1588 void *addr;
1590 TRACE("%p\n", heap );
1591 if (!heapPtr && heap && (((HEAP *)heap)->flags & HEAP_VALIDATE_PARAMS) &&
1592 NtCurrentTeb()->Peb->BeingDebugged)
1594 DbgPrint( "Attempt to destroy an invalid heap\n" );
1595 DbgBreakPoint();
1597 if (!heapPtr) return heap;
1599 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1601 /* remove it from the per-process list */
1602 RtlEnterCriticalSection( &processHeap->critSection );
1603 list_remove( &heapPtr->entry );
1604 RtlLeaveCriticalSection( &processHeap->critSection );
1606 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1607 RtlDeleteCriticalSection( &heapPtr->critSection );
1609 LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1611 list_remove( &arena->entry );
1612 size = 0;
1613 addr = arena;
1614 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1616 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1618 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1619 subheap_notify_free_all(subheap);
1620 list_remove( &subheap->entry );
1621 size = 0;
1622 addr = subheap->base;
1623 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1625 subheap_notify_free_all(&heapPtr->subheap);
1626 RtlFreeHeap( GetProcessHeap(), 0, heapPtr->pending_free );
1627 size = 0;
1628 addr = heapPtr->subheap.base;
1629 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1630 return 0;
1634 /***********************************************************************
1635 * RtlAllocateHeap (NTDLL.@)
1637 * Allocate a memory block from a Heap.
1639 * PARAMS
1640 * heap [I] Heap to allocate block from
1641 * flags [I] HEAP_ flags from "winnt.h"
1642 * size [I] Size of the memory block to allocate
1644 * RETURNS
1645 * Success: A pointer to the newly allocated block
1646 * Failure: NULL.
1648 * NOTES
1649 * This call does not SetLastError().
1651 void * WINAPI DECLSPEC_HOTPATCH RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1653 ARENA_FREE *pArena;
1654 ARENA_INUSE *pInUse;
1655 SUBHEAP *subheap;
1656 HEAP *heapPtr = HEAP_GetPtr( heap );
1657 SIZE_T rounded_size;
1659 /* Validate the parameters */
1661 if (!heapPtr) return NULL;
1662 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1663 flags |= heapPtr->flags;
1664 rounded_size = ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE( flags );
1665 if (rounded_size < size) /* overflow */
1667 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1668 return NULL;
1670 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1672 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1674 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1676 void *ret = allocate_large_block( heap, flags, size );
1677 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1678 if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1679 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1680 return ret;
1683 /* Locate a suitable free block */
1685 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1687 TRACE("(%p,%08x,%08lx): returning NULL\n",
1688 heap, flags, size );
1689 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1690 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1691 return NULL;
1694 /* Remove the arena from the free list */
1696 list_remove( &pArena->entry );
1698 /* Build the in-use arena */
1700 pInUse = (ARENA_INUSE *)pArena;
1702 /* in-use arena is smaller than free arena,
1703 * so we have to add the difference to the size */
1704 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1705 pInUse->magic = ARENA_INUSE_MAGIC;
1707 /* Shrink the block */
1709 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1710 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1712 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1713 initialize_block( pInUse + 1, size, pInUse->unused_bytes, flags );
1715 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1717 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1718 return pInUse + 1;
1722 /***********************************************************************
1723 * RtlFreeHeap (NTDLL.@)
1725 * Free a memory block allocated with RtlAllocateHeap().
1727 * PARAMS
1728 * heap [I] Heap that block was allocated from
1729 * flags [I] HEAP_ flags from "winnt.h"
1730 * ptr [I] Block to free
1732 * RETURNS
1733 * Success: TRUE, if ptr is NULL or was freed successfully.
1734 * Failure: FALSE.
1736 BOOLEAN WINAPI DECLSPEC_HOTPATCH RtlFreeHeap( HANDLE heap, ULONG flags, void *ptr )
1738 ARENA_INUSE *pInUse;
1739 SUBHEAP *subheap;
1740 HEAP *heapPtr;
1742 /* Validate the parameters */
1744 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1746 heapPtr = HEAP_GetPtr( heap );
1747 if (!heapPtr)
1749 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1750 return FALSE;
1753 flags &= HEAP_NO_SERIALIZE;
1754 flags |= heapPtr->flags;
1755 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1757 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1758 notify_free( ptr );
1760 /* Some sanity checks */
1761 pInUse = (ARENA_INUSE *)ptr - 1;
1762 if (!validate_block_pointer( heapPtr, &subheap, pInUse )) goto error;
1764 if (!subheap)
1765 free_large_block( heapPtr, flags, ptr );
1766 else
1767 HEAP_MakeInUseBlockFree( subheap, pInUse );
1769 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1770 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1771 return TRUE;
1773 error:
1774 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1775 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1776 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1777 return FALSE;
1781 /***********************************************************************
1782 * RtlReAllocateHeap (NTDLL.@)
1784 * Change the size of a memory block allocated with RtlAllocateHeap().
1786 * PARAMS
1787 * heap [I] Heap that block was allocated from
1788 * flags [I] HEAP_ flags from "winnt.h"
1789 * ptr [I] Block to resize
1790 * size [I] Size of the memory block to allocate
1792 * RETURNS
1793 * Success: A pointer to the resized block (which may be different).
1794 * Failure: NULL.
1796 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1798 ARENA_INUSE *pArena;
1799 HEAP *heapPtr;
1800 SUBHEAP *subheap;
1801 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1802 void *ret;
1804 if (!ptr) return NULL;
1805 if (!(heapPtr = HEAP_GetPtr( heap )))
1807 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1808 return NULL;
1811 /* Validate the parameters */
1813 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1814 HEAP_REALLOC_IN_PLACE_ONLY;
1815 flags |= heapPtr->flags;
1816 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1818 rounded_size = ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE(flags);
1819 if (rounded_size < size) goto oom; /* overflow */
1820 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1822 pArena = (ARENA_INUSE *)ptr - 1;
1823 if (!validate_block_pointer( heapPtr, &subheap, pArena )) goto error;
1824 if (!subheap)
1826 if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1827 goto done;
1830 /* Check if we need to grow the block */
1832 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1833 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1834 if (rounded_size > oldBlockSize)
1836 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1838 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1840 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) goto oom;
1841 if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1842 memcpy( ret, pArena + 1, oldActualSize );
1843 notify_free( pArena + 1 );
1844 HEAP_MakeInUseBlockFree( subheap, pArena );
1845 goto done;
1847 if ((pNext < (char *)subheap->base + subheap->size) &&
1848 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1849 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1851 /* The next block is free and large enough */
1852 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1853 list_remove( &pFree->entry );
1854 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1855 if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1856 notify_realloc( pArena + 1, oldActualSize, size );
1857 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1859 else /* Do it the hard way */
1861 ARENA_FREE *pNew;
1862 ARENA_INUSE *pInUse;
1863 SUBHEAP *newsubheap;
1865 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1866 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1867 goto oom;
1869 /* Build the in-use arena */
1871 list_remove( &pNew->entry );
1872 pInUse = (ARENA_INUSE *)pNew;
1873 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1874 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1875 pInUse->magic = ARENA_INUSE_MAGIC;
1876 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1878 mark_block_initialized( pInUse + 1, oldActualSize );
1879 notify_alloc( pInUse + 1, size, FALSE );
1880 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1882 /* Free the previous block */
1884 notify_free( pArena + 1 );
1885 HEAP_MakeInUseBlockFree( subheap, pArena );
1886 subheap = newsubheap;
1887 pArena = pInUse;
1890 else
1892 notify_realloc( pArena + 1, oldActualSize, size );
1893 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1896 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1898 /* Clear the extra bytes if needed */
1900 if (size > oldActualSize)
1901 initialize_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize,
1902 pArena->unused_bytes, flags );
1903 else
1904 mark_block_tail( (char *)(pArena + 1) + size, pArena->unused_bytes, flags );
1906 /* Return the new arena */
1908 ret = pArena + 1;
1909 done:
1910 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1911 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1912 return ret;
1914 oom:
1915 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1916 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1917 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1918 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1919 return NULL;
1921 error:
1922 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1923 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1924 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1925 return NULL;
1929 /***********************************************************************
1930 * RtlCompactHeap (NTDLL.@)
1932 * Compact the free space in a Heap.
1934 * PARAMS
1935 * heap [I] Heap that block was allocated from
1936 * flags [I] HEAP_ flags from "winnt.h"
1938 * RETURNS
1939 * The number of bytes compacted.
1941 * NOTES
1942 * This function is a harmless stub.
1944 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1946 static BOOL reported;
1947 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1948 return 0;
1952 /***********************************************************************
1953 * RtlLockHeap (NTDLL.@)
1955 * Lock a Heap.
1957 * PARAMS
1958 * heap [I] Heap to lock
1960 * RETURNS
1961 * Success: TRUE. The Heap is locked.
1962 * Failure: FALSE, if heap is invalid.
1964 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1966 HEAP *heapPtr = HEAP_GetPtr( heap );
1967 if (!heapPtr) return FALSE;
1968 RtlEnterCriticalSection( &heapPtr->critSection );
1969 return TRUE;
1973 /***********************************************************************
1974 * RtlUnlockHeap (NTDLL.@)
1976 * Unlock a Heap.
1978 * PARAMS
1979 * heap [I] Heap to unlock
1981 * RETURNS
1982 * Success: TRUE. The Heap is unlocked.
1983 * Failure: FALSE, if heap is invalid.
1985 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1987 HEAP *heapPtr = HEAP_GetPtr( heap );
1988 if (!heapPtr) return FALSE;
1989 RtlLeaveCriticalSection( &heapPtr->critSection );
1990 return TRUE;
1994 /***********************************************************************
1995 * RtlSizeHeap (NTDLL.@)
1997 * Get the actual size of a memory block allocated from a Heap.
1999 * PARAMS
2000 * heap [I] Heap that block was allocated from
2001 * flags [I] HEAP_ flags from "winnt.h"
2002 * ptr [I] Block to get the size of
2004 * RETURNS
2005 * Success: The size of the block.
2006 * Failure: -1, heap or ptr are invalid.
2008 * NOTES
2009 * The size may be bigger than what was passed to RtlAllocateHeap().
2011 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
2013 SIZE_T ret;
2014 const ARENA_INUSE *pArena;
2015 SUBHEAP *subheap;
2016 HEAP *heapPtr = HEAP_GetPtr( heap );
2018 if (!heapPtr)
2020 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
2021 return ~(SIZE_T)0;
2023 flags &= HEAP_NO_SERIALIZE;
2024 flags |= heapPtr->flags;
2025 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
2027 pArena = (const ARENA_INUSE *)ptr - 1;
2028 if (!validate_block_pointer( heapPtr, &subheap, pArena ))
2030 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
2031 ret = ~(SIZE_T)0;
2033 else if (!subheap)
2035 const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
2036 ret = large_arena->data_size;
2038 else
2040 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
2042 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
2044 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
2045 return ret;
2049 /***********************************************************************
2050 * RtlValidateHeap (NTDLL.@)
2052 * Determine if a block is a valid allocation from a heap.
2054 * PARAMS
2055 * heap [I] Heap that block was allocated from
2056 * flags [I] HEAP_ flags from "winnt.h"
2057 * ptr [I] Block to check
2059 * RETURNS
2060 * Success: TRUE. The block was allocated from heap.
2061 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
2063 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
2065 HEAP *heapPtr = HEAP_GetPtr( heap );
2066 if (!heapPtr) return FALSE;
2067 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
2071 /***********************************************************************
2072 * RtlWalkHeap (NTDLL.@)
2074 * FIXME
2075 * The PROCESS_HEAP_ENTRY flag values seem different between this
2076 * function and HeapWalk(). To be checked.
2078 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
2080 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
2081 HEAP *heapPtr = HEAP_GetPtr(heap);
2082 SUBHEAP *sub, *currentheap = NULL;
2083 NTSTATUS ret;
2084 char *ptr;
2085 int region_index = 0;
2087 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
2089 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
2091 /* FIXME: enumerate large blocks too */
2093 /* set ptr to the next arena to be examined */
2095 if (!entry->lpData) /* first call (init) ? */
2097 TRACE("begin walking of heap %p.\n", heap);
2098 currentheap = &heapPtr->subheap;
2099 ptr = (char*)currentheap->base + currentheap->headerSize;
2101 else
2103 ptr = entry->lpData;
2104 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
2106 if ((ptr >= (char *)sub->base) &&
2107 (ptr < (char *)sub->base + sub->size))
2109 currentheap = sub;
2110 break;
2112 region_index++;
2114 if (currentheap == NULL)
2116 ERR("no matching subheap found, shouldn't happen !\n");
2117 ret = STATUS_NO_MORE_ENTRIES;
2118 goto HW_end;
2121 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC ||
2122 ((ARENA_INUSE *)ptr - 1)->magic == ARENA_PENDING_MAGIC)
2124 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
2125 ptr += pArena->size & ARENA_SIZE_MASK;
2127 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
2129 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
2130 ptr += pArena->size & ARENA_SIZE_MASK;
2132 else
2133 ptr += entry->cbData; /* point to next arena */
2135 if (ptr > (char *)currentheap->base + currentheap->size - 1)
2136 { /* proceed with next subheap */
2137 struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
2138 if (!next)
2139 { /* successfully finished */
2140 TRACE("end reached.\n");
2141 ret = STATUS_NO_MORE_ENTRIES;
2142 goto HW_end;
2144 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
2145 ptr = (char *)currentheap->base + currentheap->headerSize;
2149 entry->wFlags = 0;
2150 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2152 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2154 /*TRACE("free, magic: %04x\n", pArena->magic);*/
2156 entry->lpData = pArena + 1;
2157 entry->cbData = pArena->size & ARENA_SIZE_MASK;
2158 entry->cbOverhead = sizeof(ARENA_FREE);
2159 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
2161 else
2163 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2165 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
2167 entry->lpData = pArena + 1;
2168 entry->cbData = pArena->size & ARENA_SIZE_MASK;
2169 entry->cbOverhead = sizeof(ARENA_INUSE);
2170 entry->wFlags = (pArena->magic == ARENA_PENDING_MAGIC) ?
2171 PROCESS_HEAP_UNCOMMITTED_RANGE : PROCESS_HEAP_ENTRY_BUSY;
2172 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
2173 and PROCESS_HEAP_ENTRY_DDESHARE yet */
2176 entry->iRegionIndex = region_index;
2178 /* first element of heap ? */
2179 if (ptr == (char *)currentheap->base + currentheap->headerSize)
2181 entry->wFlags |= PROCESS_HEAP_REGION;
2182 entry->u.Region.dwCommittedSize = currentheap->commitSize;
2183 entry->u.Region.dwUnCommittedSize =
2184 currentheap->size - currentheap->commitSize;
2185 entry->u.Region.lpFirstBlock = /* first valid block */
2186 (char *)currentheap->base + currentheap->headerSize;
2187 entry->u.Region.lpLastBlock = /* first invalid block */
2188 (char *)currentheap->base + currentheap->size;
2190 ret = STATUS_SUCCESS;
2191 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
2193 HW_end:
2194 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
2195 return ret;
2199 /***********************************************************************
2200 * RtlGetProcessHeaps (NTDLL.@)
2202 * Get the Heaps belonging to the current process.
2204 * PARAMS
2205 * count [I] size of heaps
2206 * heaps [O] Destination array for heap HANDLE's
2208 * RETURNS
2209 * Success: The number of Heaps allocated by the process.
2210 * Failure: 0.
2212 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
2214 ULONG total = 1; /* main heap */
2215 struct list *ptr;
2217 RtlEnterCriticalSection( &processHeap->critSection );
2218 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
2219 if (total <= count)
2221 *heaps++ = processHeap;
2222 LIST_FOR_EACH( ptr, &processHeap->entry )
2223 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
2225 RtlLeaveCriticalSection( &processHeap->critSection );
2226 return total;
2229 /***********************************************************************
2230 * RtlQueryHeapInformation (NTDLL.@)
2232 NTSTATUS WINAPI RtlQueryHeapInformation( HANDLE heap, HEAP_INFORMATION_CLASS info_class,
2233 PVOID info, SIZE_T size_in, PSIZE_T size_out)
2235 switch (info_class)
2237 case HeapCompatibilityInformation:
2238 if (size_out) *size_out = sizeof(ULONG);
2240 if (size_in < sizeof(ULONG))
2241 return STATUS_BUFFER_TOO_SMALL;
2243 *(ULONG *)info = 0; /* standard heap */
2244 return STATUS_SUCCESS;
2246 default:
2247 FIXME("Unknown heap information class %u\n", info_class);
2248 return STATUS_INVALID_INFO_CLASS;
2252 /***********************************************************************
2253 * RtlSetHeapInformation (NTDLL.@)
2255 NTSTATUS WINAPI RtlSetHeapInformation( HANDLE heap, HEAP_INFORMATION_CLASS info_class, PVOID info, SIZE_T size)
2257 FIXME("%p %d %p %ld stub\n", heap, info_class, info, size);
2258 return STATUS_SUCCESS;