comctl32: Fix a typo in comment.
[wine.git] / dlls / ntdll / heap.c
blobca08f9d854f6dfeb025739adb6daff4a751d3afa
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 #include "ntstatus.h"
37 #define WIN32_NO_STATUS
38 #define NONAMELESSUNION
39 #include "windef.h"
40 #include "winnt.h"
41 #include "winternl.h"
42 #include "ntdll_misc.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 #define HEAP_MIN_ARENA_SIZE (HEAP_MIN_DATA_SIZE + sizeof(ARENA_INUSE))
109 /* minimum size that must remain to shrink an allocated block */
110 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
111 /* minimum size to start allocating large blocks */
112 #define HEAP_MIN_LARGE_BLOCK_SIZE 0x7f000
113 /* extra size to add at the end of block for tail checking */
114 #define HEAP_TAIL_EXTRA_SIZE(flags) \
115 ((flags & HEAP_TAIL_CHECKING_ENABLED) || RUNNING_ON_VALGRIND ? ALIGNMENT : 0)
117 /* There will be a free list bucket for every arena size up to and including this value */
118 #define HEAP_MAX_SMALL_FREE_LIST 0x100
119 C_ASSERT( HEAP_MAX_SMALL_FREE_LIST % ALIGNMENT == 0 );
120 #define HEAP_NB_SMALL_FREE_LISTS (((HEAP_MAX_SMALL_FREE_LIST - HEAP_MIN_ARENA_SIZE) / ALIGNMENT) + 1)
122 /* Max size of the blocks on the free lists above HEAP_MAX_SMALL_FREE_LIST */
123 static const SIZE_T HEAP_freeListSizes[] =
125 0x200, 0x400, 0x1000, ~0UL
127 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes) / sizeof(HEAP_freeListSizes[0]) + HEAP_NB_SMALL_FREE_LISTS)
129 typedef union
131 ARENA_FREE arena;
132 void *alignment[4];
133 } FREE_LIST_ENTRY;
135 struct tagHEAP;
137 typedef struct tagSUBHEAP
139 void *base; /* Base address of the sub-heap memory block */
140 SIZE_T size; /* Size of the whole sub-heap */
141 SIZE_T min_commit; /* Minimum committed size */
142 SIZE_T commitSize; /* Committed size of the sub-heap */
143 struct list entry; /* Entry in sub-heap list */
144 struct tagHEAP *heap; /* Main heap structure */
145 DWORD headerSize; /* Size of the heap header */
146 DWORD magic; /* Magic number */
147 } SUBHEAP;
149 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
151 typedef struct tagHEAP
153 DWORD_PTR unknown1[2];
154 DWORD unknown2;
155 DWORD flags; /* Heap flags */
156 DWORD force_flags; /* Forced heap flags for debugging */
157 SUBHEAP subheap; /* First sub-heap */
158 struct list entry; /* Entry in process heap list */
159 struct list subheap_list; /* Sub-heap list */
160 struct list large_list; /* Large blocks list */
161 SIZE_T grow_size; /* Size of next subheap for growing heap */
162 DWORD magic; /* Magic number */
163 DWORD pending_pos; /* Position in pending free requests ring */
164 ARENA_INUSE **pending_free; /* Ring buffer for pending free requests */
165 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
166 FREE_LIST_ENTRY *freeList; /* Free lists */
167 } HEAP;
169 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
171 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
172 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
173 #define MAX_FREE_PENDING 1024 /* max number of free requests to delay */
175 /* some undocumented flags (names are made up) */
176 #define HEAP_PAGE_ALLOCS 0x01000000
177 #define HEAP_VALIDATE 0x10000000
178 #define HEAP_VALIDATE_ALL 0x20000000
179 #define HEAP_VALIDATE_PARAMS 0x40000000
181 static HEAP *processHeap; /* main process heap */
183 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
185 /* mark a block of memory as free for debugging purposes */
186 static inline void mark_block_free( void *ptr, SIZE_T size, DWORD flags )
188 if (flags & HEAP_FREE_CHECKING_ENABLED)
190 SIZE_T i;
191 for (i = 0; i < size / sizeof(DWORD); i++) ((DWORD *)ptr)[i] = ARENA_FREE_FILLER;
193 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
194 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
195 #elif defined( VALGRIND_MAKE_NOACCESS)
196 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
197 #endif
200 /* mark a block of memory as initialized for debugging purposes */
201 static inline void mark_block_initialized( void *ptr, SIZE_T size )
203 #if defined(VALGRIND_MAKE_MEM_DEFINED)
204 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
205 #elif defined(VALGRIND_MAKE_READABLE)
206 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
207 #endif
210 /* mark a block of memory as uninitialized for debugging purposes */
211 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
213 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
214 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
215 #elif defined(VALGRIND_MAKE_WRITABLE)
216 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
217 #endif
220 /* mark a block of memory as a tail block */
221 static inline void mark_block_tail( void *ptr, SIZE_T size, DWORD flags )
223 if (flags & HEAP_TAIL_CHECKING_ENABLED)
225 mark_block_uninitialized( ptr, size );
226 memset( ptr, ARENA_TAIL_FILLER, size );
228 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
229 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
230 #elif defined( VALGRIND_MAKE_NOACCESS)
231 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
232 #endif
235 /* initialize contents of a newly created block of memory */
236 static inline void initialize_block( void *ptr, SIZE_T size, SIZE_T unused, DWORD flags )
238 if (flags & HEAP_ZERO_MEMORY)
240 mark_block_initialized( ptr, size );
241 memset( ptr, 0, size );
243 else
245 mark_block_uninitialized( ptr, size );
246 if (flags & HEAP_FREE_CHECKING_ENABLED)
248 memset( ptr, ARENA_INUSE_FILLER, size );
249 mark_block_uninitialized( ptr, size );
253 mark_block_tail( (char *)ptr + size, unused, flags );
256 /* notify that a new block of memory has been allocated for debugging purposes */
257 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
259 #ifdef VALGRIND_MALLOCLIKE_BLOCK
260 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
261 #endif
264 /* notify that a block of memory has been freed for debugging purposes */
265 static inline void notify_free( void const *ptr )
267 #ifdef VALGRIND_FREELIKE_BLOCK
268 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
269 #endif
272 static inline void notify_realloc( void const *ptr, SIZE_T size_old, SIZE_T size_new )
274 #ifdef VALGRIND_RESIZEINPLACE_BLOCK
275 /* zero is not a valid size */
276 VALGRIND_RESIZEINPLACE_BLOCK( ptr, size_old ? size_old : 1, size_new ? size_new : 1, 0 );
277 #endif
280 static void subheap_notify_free_all(SUBHEAP const *subheap)
282 #ifdef VALGRIND_FREELIKE_BLOCK
283 char const *ptr = (char const *)subheap->base + subheap->headerSize;
285 if (!RUNNING_ON_VALGRIND) return;
287 while (ptr < (char const *)subheap->base + subheap->size)
289 if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
291 ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
292 if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
293 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
295 else
297 ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
298 if (pArena->magic == ARENA_INUSE_MAGIC) notify_free(pArena + 1);
299 else if (pArena->magic != ARENA_PENDING_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
300 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
303 #endif
306 /* locate a free list entry of the appropriate size */
307 /* size is the size of the whole block including the arena header */
308 static inline unsigned int get_freelist_index( SIZE_T size )
310 unsigned int i;
312 if (size <= HEAP_MAX_SMALL_FREE_LIST)
313 return (size - HEAP_MIN_ARENA_SIZE) / ALIGNMENT;
315 for (i = HEAP_NB_SMALL_FREE_LISTS; i < HEAP_NB_FREE_LISTS - 1; i++)
316 if (size <= HEAP_freeListSizes[i - HEAP_NB_SMALL_FREE_LISTS]) break;
317 return i;
320 /* get the memory protection type to use for a given heap */
321 static inline ULONG get_protection_type( DWORD flags )
323 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
326 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
328 0, 0, NULL, /* will be set later */
329 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
330 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
334 /***********************************************************************
335 * HEAP_Dump
337 static void HEAP_Dump( HEAP *heap )
339 unsigned int i;
340 SUBHEAP *subheap;
341 char *ptr;
343 DPRINTF( "Heap: %p\n", heap );
344 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
345 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
347 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
348 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
349 DPRINTF( "%p free %08lx prev=%p next=%p\n",
350 &heap->freeList[i].arena, i < HEAP_NB_SMALL_FREE_LISTS ?
351 HEAP_MIN_ARENA_SIZE + i * ALIGNMENT : HEAP_freeListSizes[i - HEAP_NB_SMALL_FREE_LISTS],
352 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
353 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
355 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
357 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
358 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
359 subheap, subheap->base, subheap->size, subheap->commitSize );
361 DPRINTF( "\n Block Arena Stat Size Id\n" );
362 ptr = (char *)subheap->base + subheap->headerSize;
363 while (ptr < (char *)subheap->base + subheap->size)
365 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
367 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
368 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
369 pArena, pArena->magic,
370 pArena->size & ARENA_SIZE_MASK,
371 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
372 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
373 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
374 arenaSize += sizeof(ARENA_FREE);
375 freeSize += pArena->size & ARENA_SIZE_MASK;
377 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
379 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
380 DPRINTF( "%p %08x Used %08x back=%p\n",
381 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
382 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
383 arenaSize += sizeof(ARENA_INUSE);
384 usedSize += pArena->size & ARENA_SIZE_MASK;
386 else
388 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
389 DPRINTF( "%p %08x %s %08x\n",
390 pArena, pArena->magic, pArena->magic == ARENA_INUSE_MAGIC ? "used" : "pend",
391 pArena->size & ARENA_SIZE_MASK );
392 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
393 arenaSize += sizeof(ARENA_INUSE);
394 usedSize += pArena->size & ARENA_SIZE_MASK;
397 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
398 subheap->size, subheap->commitSize, freeSize, usedSize,
399 arenaSize, (arenaSize * 100) / subheap->size );
404 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
406 WORD rem_flags;
407 TRACE( "Dumping entry %p\n", entry );
408 TRACE( "lpData\t\t: %p\n", entry->lpData );
409 TRACE( "cbData\t\t: %08x\n", entry->cbData);
410 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
411 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
412 TRACE( "WFlags\t\t: ");
413 if (entry->wFlags & PROCESS_HEAP_REGION)
414 TRACE( "PROCESS_HEAP_REGION ");
415 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
416 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
417 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
418 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
419 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
420 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
421 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
422 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
423 rem_flags = entry->wFlags &
424 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
425 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
426 PROCESS_HEAP_ENTRY_DDESHARE);
427 if (rem_flags)
428 TRACE( "Unknown %08x", rem_flags);
429 TRACE( "\n");
430 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
431 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
433 /* Treat as block */
434 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
436 if (entry->wFlags & PROCESS_HEAP_REGION)
438 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
439 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
440 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
441 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
445 /***********************************************************************
446 * HEAP_GetPtr
447 * RETURNS
448 * Pointer to the heap
449 * NULL: Failure
451 static HEAP *HEAP_GetPtr(
452 HANDLE heap /* [in] Handle to the heap */
454 HEAP *heapPtr = heap;
455 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
457 ERR("Invalid heap %p!\n", heap );
458 return NULL;
460 if ((heapPtr->flags & HEAP_VALIDATE_ALL) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
462 if (TRACE_ON(heap))
464 HEAP_Dump( heapPtr );
465 assert( FALSE );
467 return NULL;
469 return heapPtr;
473 /***********************************************************************
474 * HEAP_InsertFreeBlock
476 * Insert a free block into the free list.
478 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
480 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
481 if (last)
483 /* insert at end of free list, i.e. before the next free list entry */
484 pEntry++;
485 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
486 list_add_before( &pEntry->arena.entry, &pArena->entry );
488 else
490 /* insert at head of free list */
491 list_add_after( &pEntry->arena.entry, &pArena->entry );
493 pArena->size |= ARENA_FLAG_FREE;
497 /***********************************************************************
498 * HEAP_FindSubHeap
499 * Find the sub-heap containing a given address.
501 * RETURNS
502 * Pointer: Success
503 * NULL: Failure
505 static SUBHEAP *HEAP_FindSubHeap(
506 const HEAP *heap, /* [in] Heap pointer */
507 LPCVOID ptr ) /* [in] Address */
509 SUBHEAP *sub;
510 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
511 if ((ptr >= sub->base) &&
512 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
513 return sub;
514 return NULL;
518 /***********************************************************************
519 * HEAP_Commit
521 * Make sure the heap storage is committed for a given size in the specified arena.
523 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
525 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
526 SIZE_T size = (char *)ptr - (char *)subheap->base;
527 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
528 if (size > subheap->size) size = subheap->size;
529 if (size <= subheap->commitSize) return TRUE;
530 size -= subheap->commitSize;
531 ptr = (char *)subheap->base + subheap->commitSize;
532 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
533 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
535 WARN("Could not commit %08lx bytes at %p for heap %p\n",
536 size, ptr, subheap->heap );
537 return FALSE;
539 subheap->commitSize += size;
540 return TRUE;
544 /***********************************************************************
545 * HEAP_Decommit
547 * If possible, decommit the heap storage from (including) 'ptr'.
549 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
551 void *addr;
552 SIZE_T decommit_size;
553 SIZE_T size = (char *)ptr - (char *)subheap->base;
555 /* round to next block and add one full block */
556 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
557 size = max( size, subheap->min_commit );
558 if (size >= subheap->commitSize) return TRUE;
559 decommit_size = subheap->commitSize - size;
560 addr = (char *)subheap->base + size;
562 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
564 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
565 decommit_size, (char *)subheap->base + size, subheap->heap );
566 return FALSE;
568 subheap->commitSize -= decommit_size;
569 return TRUE;
573 /***********************************************************************
574 * HEAP_CreateFreeBlock
576 * Create a free block at a specified address. 'size' is the size of the
577 * whole block, including the new arena.
579 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
581 ARENA_FREE *pFree;
582 char *pEnd;
583 BOOL last;
584 DWORD flags = subheap->heap->flags;
586 /* Create a free arena */
587 mark_block_uninitialized( ptr, sizeof(ARENA_FREE) );
588 pFree = ptr;
589 pFree->magic = ARENA_FREE_MAGIC;
591 /* If debugging, erase the freed block content */
593 pEnd = (char *)ptr + size;
594 if (pEnd > (char *)subheap->base + subheap->commitSize)
595 pEnd = (char *)subheap->base + subheap->commitSize;
596 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1), flags );
598 /* Check if next block is free also */
600 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
601 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
603 /* Remove the next arena from the free list */
604 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
605 list_remove( &pNext->entry );
606 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
607 mark_block_free( pNext, sizeof(ARENA_FREE), flags );
610 /* Set the next block PREV_FREE flag and pointer */
612 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
613 if (!last)
615 DWORD *pNext = (DWORD *)((char *)ptr + size);
616 *pNext |= ARENA_FLAG_PREV_FREE;
617 mark_block_initialized( (ARENA_FREE **)pNext - 1, sizeof( ARENA_FREE * ) );
618 *((ARENA_FREE **)pNext - 1) = pFree;
621 /* Last, insert the new block into the free list */
623 pFree->size = size - sizeof(*pFree);
624 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
628 /***********************************************************************
629 * HEAP_MakeInUseBlockFree
631 * Turn an in-use block into a free block. Can also decommit the end of
632 * the heap, and possibly even free the sub-heap altogether.
634 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
636 HEAP *heap = subheap->heap;
637 ARENA_FREE *pFree;
638 SIZE_T size;
640 if (heap->pending_free)
642 ARENA_INUSE *prev = heap->pending_free[heap->pending_pos];
643 heap->pending_free[heap->pending_pos] = pArena;
644 heap->pending_pos = (heap->pending_pos + 1) % MAX_FREE_PENDING;
645 pArena->magic = ARENA_PENDING_MAGIC;
646 mark_block_free( pArena + 1, pArena->size & ARENA_SIZE_MASK, heap->flags );
647 if (!prev) return;
648 pArena = prev;
649 subheap = HEAP_FindSubHeap( heap, pArena );
652 /* Check if we can merge with previous block */
654 size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
655 if (pArena->size & ARENA_FLAG_PREV_FREE)
657 pFree = *((ARENA_FREE **)pArena - 1);
658 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
659 /* Remove it from the free list */
660 list_remove( &pFree->entry );
662 else pFree = (ARENA_FREE *)pArena;
664 /* Create a free block */
666 HEAP_CreateFreeBlock( subheap, pFree, size );
667 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
668 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
669 return; /* Not the last block, so nothing more to do */
671 /* Free the whole sub-heap if it's empty and not the original one */
673 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
674 (subheap != &subheap->heap->subheap))
676 void *addr = subheap->base;
678 size = 0;
679 /* Remove the free block from the list */
680 list_remove( &pFree->entry );
681 /* Remove the subheap from the list */
682 list_remove( &subheap->entry );
683 /* Free the memory */
684 subheap->magic = 0;
685 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
686 return;
689 /* Decommit the end of the heap */
691 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
695 /***********************************************************************
696 * HEAP_ShrinkBlock
698 * Shrink an in-use block.
700 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
702 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
704 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
705 (pArena->size & ARENA_SIZE_MASK) - size );
706 /* assign size plus previous arena flags */
707 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
709 else
711 /* Turn off PREV_FREE flag in next block */
712 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
713 if (pNext < (char *)subheap->base + subheap->size)
714 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
719 /***********************************************************************
720 * allocate_large_block
722 static void *allocate_large_block( HEAP *heap, DWORD flags, SIZE_T size )
724 ARENA_LARGE *arena;
725 SIZE_T block_size = sizeof(*arena) + ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE(flags);
726 LPVOID address = NULL;
728 if (block_size < size) return NULL; /* overflow */
729 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 5,
730 &block_size, MEM_COMMIT, get_protection_type( flags ) ))
732 WARN("Could not allocate block for %08lx bytes\n", size );
733 return NULL;
735 arena = address;
736 arena->data_size = size;
737 arena->block_size = block_size;
738 arena->size = ARENA_LARGE_SIZE;
739 arena->magic = ARENA_LARGE_MAGIC;
740 mark_block_tail( (char *)(arena + 1) + size, block_size - sizeof(*arena) - size, flags );
741 list_add_tail( &heap->large_list, &arena->entry );
742 notify_alloc( arena + 1, size, flags & HEAP_ZERO_MEMORY );
743 return arena + 1;
747 /***********************************************************************
748 * free_large_block
750 static void free_large_block( HEAP *heap, DWORD flags, void *ptr )
752 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
753 LPVOID address = arena;
754 SIZE_T size = 0;
756 list_remove( &arena->entry );
757 NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
761 /***********************************************************************
762 * realloc_large_block
764 static void *realloc_large_block( HEAP *heap, DWORD flags, void *ptr, SIZE_T size )
766 ARENA_LARGE *arena = (ARENA_LARGE *)ptr - 1;
767 void *new_ptr;
769 if (arena->block_size - sizeof(*arena) >= size)
771 SIZE_T unused = arena->block_size - sizeof(*arena) - size;
773 /* FIXME: we could remap zero-pages instead */
774 #ifdef VALGRIND_RESIZEINPLACE_BLOCK
775 if (RUNNING_ON_VALGRIND)
776 notify_realloc( arena + 1, arena->data_size, size );
777 else
778 #endif
779 if (size > arena->data_size)
780 initialize_block( (char *)ptr + arena->data_size, size - arena->data_size, unused, flags );
781 else
782 mark_block_tail( (char *)ptr + size, unused, flags );
783 arena->data_size = size;
784 return ptr;
786 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) return NULL;
787 if (!(new_ptr = allocate_large_block( heap, flags, size )))
789 WARN("Could not allocate block for %08lx bytes\n", size );
790 return NULL;
792 memcpy( new_ptr, ptr, arena->data_size );
793 free_large_block( heap, flags, ptr );
794 notify_free( ptr );
795 return new_ptr;
799 /***********************************************************************
800 * find_large_block
802 static ARENA_LARGE *find_large_block( HEAP *heap, const void *ptr )
804 ARENA_LARGE *arena;
806 LIST_FOR_EACH_ENTRY( arena, &heap->large_list, ARENA_LARGE, entry )
807 if (ptr == arena + 1) return arena;
809 return NULL;
813 /***********************************************************************
814 * validate_large_arena
816 static BOOL validate_large_arena( HEAP *heap, const ARENA_LARGE *arena, BOOL quiet )
818 DWORD flags = heap->flags;
820 if ((ULONG_PTR)arena % page_size)
822 if (quiet == NOISY)
824 ERR( "Heap %p: invalid large arena pointer %p\n", heap, arena );
825 if (TRACE_ON(heap)) HEAP_Dump( heap );
827 else if (WARN_ON(heap))
829 WARN( "Heap %p: unaligned arena pointer %p\n", heap, arena );
830 if (TRACE_ON(heap)) HEAP_Dump( heap );
832 return FALSE;
834 if (arena->size != ARENA_LARGE_SIZE || arena->magic != ARENA_LARGE_MAGIC)
836 if (quiet == NOISY)
838 ERR( "Heap %p: invalid large arena %p values %x/%x\n",
839 heap, arena, arena->size, arena->magic );
840 if (TRACE_ON(heap)) HEAP_Dump( heap );
842 else if (WARN_ON(heap))
844 WARN( "Heap %p: invalid large arena %p values %x/%x\n",
845 heap, arena, arena->size, arena->magic );
846 if (TRACE_ON(heap)) HEAP_Dump( heap );
848 return FALSE;
850 if (arena->data_size > arena->block_size - sizeof(*arena))
852 ERR( "Heap %p: invalid large arena %p size %lx/%lx\n",
853 heap, arena, arena->data_size, arena->block_size );
854 return FALSE;
856 if (flags & HEAP_TAIL_CHECKING_ENABLED)
858 SIZE_T i, unused = arena->block_size - sizeof(*arena) - arena->data_size;
859 const unsigned char *data = (const unsigned char *)(arena + 1) + arena->data_size;
861 for (i = 0; i < unused; i++)
863 if (data[i] == ARENA_TAIL_FILLER) continue;
864 ERR("Heap %p: block %p tail overwritten at %p (byte %lu/%lu == 0x%02x)\n",
865 heap, arena + 1, data + i, i, unused, data[i] );
866 return FALSE;
869 return TRUE;
873 /***********************************************************************
874 * HEAP_CreateSubHeap
876 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, LPVOID address, DWORD flags,
877 SIZE_T commitSize, SIZE_T totalSize )
879 SUBHEAP *subheap;
880 FREE_LIST_ENTRY *pEntry;
881 unsigned int i;
883 if (!address)
885 if (!commitSize) commitSize = COMMIT_MASK + 1;
886 totalSize = min( totalSize, 0xffff0000 ); /* don't allow a heap larger than 4Gb */
887 if (totalSize < commitSize) totalSize = commitSize;
888 if (flags & HEAP_SHARED) commitSize = totalSize; /* always commit everything in a shared heap */
889 commitSize = min( totalSize, (commitSize + COMMIT_MASK) & ~COMMIT_MASK );
891 /* allocate the memory block */
892 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
893 MEM_RESERVE, get_protection_type( flags ) ))
895 WARN("Could not allocate %08lx bytes\n", totalSize );
896 return NULL;
898 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
899 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
901 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
902 return NULL;
906 if (heap)
908 /* If this is a secondary subheap, insert it into list */
910 subheap = address;
911 subheap->base = address;
912 subheap->heap = heap;
913 subheap->size = totalSize;
914 subheap->min_commit = 0x10000;
915 subheap->commitSize = commitSize;
916 subheap->magic = SUBHEAP_MAGIC;
917 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
918 list_add_head( &heap->subheap_list, &subheap->entry );
920 else
922 /* If this is a primary subheap, initialize main heap */
924 heap = address;
925 heap->flags = flags;
926 heap->magic = HEAP_MAGIC;
927 heap->grow_size = max( HEAP_DEF_SIZE, totalSize );
928 list_init( &heap->subheap_list );
929 list_init( &heap->large_list );
931 subheap = &heap->subheap;
932 subheap->base = address;
933 subheap->heap = heap;
934 subheap->size = totalSize;
935 subheap->min_commit = commitSize;
936 subheap->commitSize = commitSize;
937 subheap->magic = SUBHEAP_MAGIC;
938 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
939 list_add_head( &heap->subheap_list, &subheap->entry );
941 /* Build the free lists */
943 heap->freeList = (FREE_LIST_ENTRY *)((char *)heap + subheap->headerSize);
944 subheap->headerSize += HEAP_NB_FREE_LISTS * sizeof(FREE_LIST_ENTRY);
945 list_init( &heap->freeList[0].arena.entry );
946 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
948 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
949 pEntry->arena.magic = ARENA_FREE_MAGIC;
950 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
953 /* Initialize critical section */
955 if (!processHeap) /* do it by hand to avoid memory allocations */
957 heap->critSection.DebugInfo = &process_heap_critsect_debug;
958 heap->critSection.LockCount = -1;
959 heap->critSection.RecursionCount = 0;
960 heap->critSection.OwningThread = 0;
961 heap->critSection.LockSemaphore = 0;
962 heap->critSection.SpinCount = 0;
963 process_heap_critsect_debug.CriticalSection = &heap->critSection;
965 else
967 RtlInitializeCriticalSection( &heap->critSection );
968 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
971 if (flags & HEAP_SHARED)
973 /* let's assume that only one thread at a time will try to do this */
974 HANDLE sem = heap->critSection.LockSemaphore;
975 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
977 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
978 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
979 heap->critSection.LockSemaphore = sem;
980 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
981 heap->critSection.DebugInfo = NULL;
985 /* Create the first free block */
987 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
988 subheap->size - subheap->headerSize );
990 return subheap;
994 /***********************************************************************
995 * HEAP_FindFreeBlock
997 * Find a free block at least as large as the requested size, and make sure
998 * the requested size is committed.
1000 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
1001 SUBHEAP **ppSubHeap )
1003 SUBHEAP *subheap;
1004 struct list *ptr;
1005 SIZE_T total_size;
1006 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
1008 /* Find a suitable free list, and in it find a block large enough */
1010 ptr = &pEntry->arena.entry;
1011 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
1013 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
1014 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
1015 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1016 if (arena_size >= size)
1018 subheap = HEAP_FindSubHeap( heap, pArena );
1019 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
1020 *ppSubHeap = subheap;
1021 return pArena;
1025 /* If no block was found, attempt to grow the heap */
1027 if (!(heap->flags & HEAP_GROWABLE))
1029 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
1030 return NULL;
1032 /* make sure that we have a big enough size *committed* to fit another
1033 * last free arena in !
1034 * So just one heap struct, one first free arena which will eventually
1035 * get used, and a second free arena that might get assigned all remaining
1036 * free space in HEAP_ShrinkBlock() */
1037 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
1038 if (total_size < size) return NULL; /* overflow */
1040 if ((subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
1041 max( heap->grow_size, total_size ) )))
1043 if (heap->grow_size < 128 * 1024 * 1024) heap->grow_size *= 2;
1045 else while (!subheap) /* shrink the grow size again if we are running out of space */
1047 if (heap->grow_size <= total_size || heap->grow_size <= 4 * 1024 * 1024) return NULL;
1048 heap->grow_size /= 2;
1049 subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
1050 max( heap->grow_size, total_size ) );
1053 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
1054 subheap, subheap->size, heap );
1056 *ppSubHeap = subheap;
1057 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
1061 /***********************************************************************
1062 * HEAP_IsValidArenaPtr
1064 * Check that the pointer is inside the range possible for arenas.
1066 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
1068 unsigned int i;
1069 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
1070 if (!subheap) return FALSE;
1071 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
1072 if (subheap != &heap->subheap) return FALSE;
1073 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
1074 if (ptr == &heap->freeList[i].arena) return TRUE;
1075 return FALSE;
1079 /***********************************************************************
1080 * HEAP_ValidateFreeArena
1082 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
1084 DWORD flags = subheap->heap->flags;
1085 SIZE_T size;
1086 ARENA_FREE *prev, *next;
1087 char *heapEnd = (char *)subheap->base + subheap->size;
1089 /* Check for unaligned pointers */
1090 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1092 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1093 return FALSE;
1096 /* Check magic number */
1097 if (pArena->magic != ARENA_FREE_MAGIC)
1099 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1100 return FALSE;
1102 /* Check size flags */
1103 if (!(pArena->size & ARENA_FLAG_FREE) ||
1104 (pArena->size & ARENA_FLAG_PREV_FREE))
1106 ERR("Heap %p: bad flags %08x for free arena %p\n",
1107 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1108 return FALSE;
1110 /* Check arena size */
1111 size = pArena->size & ARENA_SIZE_MASK;
1112 if ((char *)(pArena + 1) + size > heapEnd)
1114 ERR("Heap %p: bad size %08lx for free arena %p\n", subheap->heap, size, pArena );
1115 return FALSE;
1117 /* Check that next pointer is valid */
1118 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
1119 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
1121 ERR("Heap %p: bad next ptr %p for arena %p\n",
1122 subheap->heap, next, pArena );
1123 return FALSE;
1125 /* Check that next arena is free */
1126 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
1128 ERR("Heap %p: next arena %p invalid for %p\n",
1129 subheap->heap, next, pArena );
1130 return FALSE;
1132 /* Check that prev pointer is valid */
1133 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
1134 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
1136 ERR("Heap %p: bad prev ptr %p for arena %p\n",
1137 subheap->heap, prev, pArena );
1138 return FALSE;
1140 /* Check that prev arena is free */
1141 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
1143 /* this often means that the prev arena got overwritten
1144 * by a memory write before that prev arena */
1145 ERR("Heap %p: prev arena %p invalid for %p\n",
1146 subheap->heap, prev, pArena );
1147 return FALSE;
1149 /* Check that next block has PREV_FREE flag */
1150 if ((char *)(pArena + 1) + size < heapEnd)
1152 if (!(*(DWORD *)((char *)(pArena + 1) + size) & ARENA_FLAG_PREV_FREE))
1154 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
1155 subheap->heap, pArena );
1156 return FALSE;
1158 /* Check next block back pointer */
1159 if (*((ARENA_FREE **)((char *)(pArena + 1) + size) - 1) != pArena)
1161 ERR("Heap %p: arena %p has wrong back ptr %p\n",
1162 subheap->heap, pArena,
1163 *((ARENA_FREE **)((char *)(pArena+1) + size) - 1));
1164 return FALSE;
1167 if (flags & HEAP_FREE_CHECKING_ENABLED)
1169 DWORD *ptr = (DWORD *)(pArena + 1);
1170 char *end = (char *)(pArena + 1) + size;
1172 if (end >= heapEnd) end = (char *)subheap->base + subheap->commitSize;
1173 else end -= sizeof(ARENA_FREE *);
1174 while (ptr < (DWORD *)end)
1176 if (*ptr != ARENA_FREE_FILLER)
1178 ERR("Heap %p: free block %p overwritten at %p by %08x\n",
1179 subheap->heap, (ARENA_INUSE *)pArena + 1, ptr, *ptr );
1180 return FALSE;
1182 ptr++;
1185 return TRUE;
1189 /***********************************************************************
1190 * HEAP_ValidateInUseArena
1192 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
1194 SIZE_T size;
1195 DWORD i, flags = subheap->heap->flags;
1196 const char *heapEnd = (const char *)subheap->base + subheap->size;
1198 /* Check for unaligned pointers */
1199 if ((ULONG_PTR)pArena % ALIGNMENT != ARENA_OFFSET)
1201 if ( quiet == NOISY )
1203 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1204 if ( TRACE_ON(heap) )
1205 HEAP_Dump( subheap->heap );
1207 else if ( WARN_ON(heap) )
1209 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
1210 if ( TRACE_ON(heap) )
1211 HEAP_Dump( subheap->heap );
1213 return FALSE;
1216 /* Check magic number */
1217 if (pArena->magic != ARENA_INUSE_MAGIC && pArena->magic != ARENA_PENDING_MAGIC)
1219 if (quiet == NOISY) {
1220 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1221 if (TRACE_ON(heap))
1222 HEAP_Dump( subheap->heap );
1223 } else if (WARN_ON(heap)) {
1224 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
1225 if (TRACE_ON(heap))
1226 HEAP_Dump( subheap->heap );
1228 return FALSE;
1230 /* Check size flags */
1231 if (pArena->size & ARENA_FLAG_FREE)
1233 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
1234 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
1235 return FALSE;
1237 /* Check arena size */
1238 size = pArena->size & ARENA_SIZE_MASK;
1239 if ((const char *)(pArena + 1) + size > heapEnd ||
1240 (const char *)(pArena + 1) + size < (const char *)(pArena + 1))
1242 ERR("Heap %p: bad size %08lx for in-use arena %p\n", subheap->heap, size, pArena );
1243 return FALSE;
1245 /* Check next arena PREV_FREE flag */
1246 if (((const char *)(pArena + 1) + size < heapEnd) &&
1247 (*(const DWORD *)((const char *)(pArena + 1) + size) & ARENA_FLAG_PREV_FREE))
1249 ERR("Heap %p: in-use arena %p next block %p has PREV_FREE flag %x\n",
1250 subheap->heap, pArena, (const char *)(pArena + 1) + size,*(const DWORD *)((const char *)(pArena + 1) + size) );
1251 return FALSE;
1253 /* Check prev free arena */
1254 if (pArena->size & ARENA_FLAG_PREV_FREE)
1256 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
1257 /* Check prev pointer */
1258 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
1260 ERR("Heap %p: bad back ptr %p for arena %p\n",
1261 subheap->heap, pPrev, pArena );
1262 return FALSE;
1264 /* Check that prev arena is free */
1265 if (!(pPrev->size & ARENA_FLAG_FREE) ||
1266 (pPrev->magic != ARENA_FREE_MAGIC))
1268 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1269 subheap->heap, pPrev, pArena );
1270 return FALSE;
1272 /* Check that prev arena is really the previous block */
1273 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1275 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1276 subheap->heap, pPrev, pArena );
1277 return FALSE;
1280 /* Check unused size */
1281 if (pArena->unused_bytes > size)
1283 ERR("Heap %p: invalid unused size %08x/%08lx\n", subheap->heap, pArena->unused_bytes, size );
1284 return FALSE;
1286 /* Check unused bytes */
1287 if (pArena->magic == ARENA_PENDING_MAGIC)
1289 const DWORD *ptr = (const DWORD *)(pArena + 1);
1290 const DWORD *end = (const DWORD *)((const char *)ptr + size);
1292 while (ptr < end)
1294 if (*ptr != ARENA_FREE_FILLER)
1296 ERR("Heap %p: free block %p overwritten at %p by %08x\n",
1297 subheap->heap, (const ARENA_INUSE *)pArena + 1, ptr, *ptr );
1298 if (!*ptr) { HEAP_Dump( subheap->heap ); DbgBreakPoint(); }
1299 return FALSE;
1301 ptr++;
1304 else if (flags & HEAP_TAIL_CHECKING_ENABLED)
1306 const unsigned char *data = (const unsigned char *)(pArena + 1) + size - pArena->unused_bytes;
1308 for (i = 0; i < pArena->unused_bytes; i++)
1310 if (data[i] == ARENA_TAIL_FILLER) continue;
1311 ERR("Heap %p: block %p tail overwritten at %p (byte %u/%u == 0x%02x)\n",
1312 subheap->heap, pArena + 1, data + i, i, pArena->unused_bytes, data[i] );
1313 return FALSE;
1316 return TRUE;
1320 /***********************************************************************
1321 * HEAP_IsRealArena [Internal]
1322 * Validates a block is a valid arena.
1324 * RETURNS
1325 * TRUE: Success
1326 * FALSE: Failure
1328 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1329 DWORD flags, /* [in] Bit flags that control access during operation */
1330 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1331 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1332 * does not complain */
1334 SUBHEAP *subheap;
1335 BOOL ret = TRUE;
1336 const ARENA_LARGE *large_arena;
1338 flags &= HEAP_NO_SERIALIZE;
1339 flags |= heapPtr->flags;
1340 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1341 if (!(flags & HEAP_NO_SERIALIZE))
1342 RtlEnterCriticalSection( &heapPtr->critSection );
1344 if (block) /* only check this single memory block */
1346 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1348 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1349 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1351 if (!(large_arena = find_large_block( heapPtr, block )))
1353 if (quiet == NOISY)
1354 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1355 else if (WARN_ON(heap))
1356 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1357 ret = FALSE;
1359 else
1360 ret = validate_large_arena( heapPtr, large_arena, quiet );
1361 } else
1362 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1364 if (!(flags & HEAP_NO_SERIALIZE))
1365 RtlLeaveCriticalSection( &heapPtr->critSection );
1366 return ret;
1369 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1371 char *ptr = (char *)subheap->base + subheap->headerSize;
1372 while (ptr < (char *)subheap->base + subheap->size)
1374 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1376 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1377 ret = FALSE;
1378 break;
1380 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1382 else
1384 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1385 ret = FALSE;
1386 break;
1388 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1391 if (!ret) break;
1394 LIST_FOR_EACH_ENTRY( large_arena, &heapPtr->large_list, ARENA_LARGE, entry )
1395 if (!(ret = validate_large_arena( heapPtr, large_arena, quiet ))) break;
1397 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1398 return ret;
1402 /***********************************************************************
1403 * validate_block_pointer
1405 * Minimum validation needed to catch bad parameters in heap functions.
1407 static BOOL validate_block_pointer( HEAP *heap, SUBHEAP **ret_subheap, const ARENA_INUSE *arena )
1409 SUBHEAP *subheap;
1410 BOOL ret = FALSE;
1412 if (!(*ret_subheap = subheap = HEAP_FindSubHeap( heap, arena )))
1414 ARENA_LARGE *large_arena = find_large_block( heap, arena + 1 );
1416 if (!large_arena)
1418 WARN( "Heap %p: pointer %p is not inside heap\n", heap, arena + 1 );
1419 return FALSE;
1421 if ((heap->flags & HEAP_VALIDATE) && !validate_large_arena( heap, large_arena, QUIET ))
1422 return FALSE;
1423 return TRUE;
1426 if ((const char *)arena < (char *)subheap->base + subheap->headerSize)
1427 WARN( "Heap %p: pointer %p is inside subheap %p header\n", subheap->heap, arena + 1, subheap );
1428 else if (subheap->heap->flags & HEAP_VALIDATE) /* do the full validation */
1429 ret = HEAP_ValidateInUseArena( subheap, arena, QUIET );
1430 else if ((ULONG_PTR)arena % ALIGNMENT != ARENA_OFFSET)
1431 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, arena );
1432 else if (arena->magic == ARENA_PENDING_MAGIC)
1433 WARN( "Heap %p: block %p used after free\n", subheap->heap, arena + 1 );
1434 else if (arena->magic != ARENA_INUSE_MAGIC)
1435 WARN( "Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, arena->magic, arena );
1436 else if (arena->size & ARENA_FLAG_FREE)
1437 ERR( "Heap %p: bad flags %08x for in-use arena %p\n",
1438 subheap->heap, arena->size & ~ARENA_SIZE_MASK, arena );
1439 else if ((const char *)(arena + 1) + (arena->size & ARENA_SIZE_MASK) > (const char *)subheap->base + subheap->size ||
1440 (const char *)(arena + 1) + (arena->size & ARENA_SIZE_MASK) < (const char *)(arena + 1))
1441 ERR( "Heap %p: bad size %08x for in-use arena %p\n",
1442 subheap->heap, arena->size & ARENA_SIZE_MASK, arena );
1443 else
1444 ret = TRUE;
1446 return ret;
1450 /***********************************************************************
1451 * heap_set_debug_flags
1453 void heap_set_debug_flags( HANDLE handle )
1455 HEAP *heap = HEAP_GetPtr( handle );
1456 ULONG global_flags = RtlGetNtGlobalFlags();
1457 ULONG flags = 0;
1459 if (TRACE_ON(heap)) global_flags |= FLG_HEAP_VALIDATE_ALL;
1460 if (WARN_ON(heap)) global_flags |= FLG_HEAP_VALIDATE_PARAMETERS;
1462 if (global_flags & FLG_HEAP_ENABLE_TAIL_CHECK) flags |= HEAP_TAIL_CHECKING_ENABLED;
1463 if (global_flags & FLG_HEAP_ENABLE_FREE_CHECK) flags |= HEAP_FREE_CHECKING_ENABLED;
1464 if (global_flags & FLG_HEAP_DISABLE_COALESCING) flags |= HEAP_DISABLE_COALESCE_ON_FREE;
1465 if (global_flags & FLG_HEAP_PAGE_ALLOCS) flags |= HEAP_PAGE_ALLOCS | HEAP_GROWABLE;
1467 if (global_flags & FLG_HEAP_VALIDATE_PARAMETERS)
1468 flags |= HEAP_VALIDATE | HEAP_VALIDATE_PARAMS |
1469 HEAP_TAIL_CHECKING_ENABLED | HEAP_FREE_CHECKING_ENABLED;
1470 if (global_flags & FLG_HEAP_VALIDATE_ALL)
1471 flags |= HEAP_VALIDATE | HEAP_VALIDATE_ALL |
1472 HEAP_TAIL_CHECKING_ENABLED | HEAP_FREE_CHECKING_ENABLED;
1474 if (RUNNING_ON_VALGRIND) flags = 0; /* no sense in validating since Valgrind catches accesses */
1476 heap->flags |= flags;
1477 heap->force_flags |= flags & ~(HEAP_VALIDATE | HEAP_DISABLE_COALESCE_ON_FREE);
1479 if (flags & (HEAP_FREE_CHECKING_ENABLED | HEAP_TAIL_CHECKING_ENABLED)) /* fix existing blocks */
1481 SUBHEAP *subheap;
1482 ARENA_LARGE *large;
1484 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
1486 char *ptr = (char *)subheap->base + subheap->headerSize;
1487 char *end = (char *)subheap->base + subheap->commitSize;
1488 while (ptr < end)
1490 ARENA_INUSE *arena = (ARENA_INUSE *)ptr;
1491 SIZE_T size = arena->size & ARENA_SIZE_MASK;
1492 if (arena->size & ARENA_FLAG_FREE)
1494 SIZE_T count = size;
1496 ptr += sizeof(ARENA_FREE) + size;
1497 if (ptr >= end) count = end - (char *)((ARENA_FREE *)arena + 1);
1498 else count -= sizeof(ARENA_FREE *);
1499 mark_block_free( (ARENA_FREE *)arena + 1, count, flags );
1501 else
1503 if (arena->magic == ARENA_PENDING_MAGIC)
1504 mark_block_free( arena + 1, size, flags );
1505 else
1506 mark_block_tail( (char *)(arena + 1) + size - arena->unused_bytes,
1507 arena->unused_bytes, flags );
1508 ptr += sizeof(ARENA_INUSE) + size;
1513 LIST_FOR_EACH_ENTRY( large, &heap->large_list, ARENA_LARGE, entry )
1514 mark_block_tail( (char *)(large + 1) + large->data_size,
1515 large->block_size - sizeof(*large) - large->data_size, flags );
1518 if ((heap->flags & HEAP_GROWABLE) && !heap->pending_free &&
1519 ((flags & HEAP_FREE_CHECKING_ENABLED) || RUNNING_ON_VALGRIND))
1521 void *ptr = NULL;
1522 SIZE_T size = MAX_FREE_PENDING * sizeof(*heap->pending_free);
1524 if (!NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 4, &size, MEM_COMMIT, PAGE_READWRITE ))
1526 heap->pending_free = ptr;
1527 heap->pending_pos = 0;
1533 /***********************************************************************
1534 * RtlCreateHeap (NTDLL.@)
1536 * Create a new Heap.
1538 * PARAMS
1539 * flags [I] HEAP_ flags from "winnt.h"
1540 * addr [I] Desired base address
1541 * totalSize [I] Total size of the heap, or 0 for a growable heap
1542 * commitSize [I] Amount of heap space to commit
1543 * unknown [I] Not yet understood
1544 * definition [I] Heap definition
1546 * RETURNS
1547 * Success: A HANDLE to the newly created heap.
1548 * Failure: a NULL HANDLE.
1550 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1551 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1553 SUBHEAP *subheap;
1555 /* Allocate the heap block */
1557 if (!totalSize)
1559 totalSize = HEAP_DEF_SIZE;
1560 flags |= HEAP_GROWABLE;
1563 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1565 heap_set_debug_flags( subheap->heap );
1567 /* link it into the per-process heap list */
1568 if (processHeap)
1570 HEAP *heapPtr = subheap->heap;
1571 RtlEnterCriticalSection( &processHeap->critSection );
1572 list_add_head( &processHeap->entry, &heapPtr->entry );
1573 RtlLeaveCriticalSection( &processHeap->critSection );
1575 else if (!addr)
1577 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1578 list_init( &processHeap->entry );
1581 return subheap->heap;
1585 /***********************************************************************
1586 * RtlDestroyHeap (NTDLL.@)
1588 * Destroy a Heap created with RtlCreateHeap().
1590 * PARAMS
1591 * heap [I] Heap to destroy.
1593 * RETURNS
1594 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1595 * Failure: The Heap handle, if heap is the process heap.
1597 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1599 HEAP *heapPtr = HEAP_GetPtr( heap );
1600 SUBHEAP *subheap, *next;
1601 ARENA_LARGE *arena, *arena_next;
1602 SIZE_T size;
1603 void *addr;
1605 TRACE("%p\n", heap );
1606 if (!heapPtr) return heap;
1608 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1610 /* remove it from the per-process list */
1611 RtlEnterCriticalSection( &processHeap->critSection );
1612 list_remove( &heapPtr->entry );
1613 RtlLeaveCriticalSection( &processHeap->critSection );
1615 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1616 RtlDeleteCriticalSection( &heapPtr->critSection );
1618 LIST_FOR_EACH_ENTRY_SAFE( arena, arena_next, &heapPtr->large_list, ARENA_LARGE, entry )
1620 list_remove( &arena->entry );
1621 size = 0;
1622 addr = arena;
1623 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1625 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1627 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1628 subheap_notify_free_all(subheap);
1629 list_remove( &subheap->entry );
1630 size = 0;
1631 addr = subheap->base;
1632 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1634 subheap_notify_free_all(&heapPtr->subheap);
1635 if (heapPtr->pending_free)
1637 size = 0;
1638 addr = heapPtr->pending_free;
1639 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1641 size = 0;
1642 addr = heapPtr->subheap.base;
1643 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1644 return 0;
1648 /***********************************************************************
1649 * RtlAllocateHeap (NTDLL.@)
1651 * Allocate a memory block from a Heap.
1653 * PARAMS
1654 * heap [I] Heap to allocate block from
1655 * flags [I] HEAP_ flags from "winnt.h"
1656 * size [I] Size of the memory block to allocate
1658 * RETURNS
1659 * Success: A pointer to the newly allocated block
1660 * Failure: NULL.
1662 * NOTES
1663 * This call does not SetLastError().
1665 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1667 ARENA_FREE *pArena;
1668 ARENA_INUSE *pInUse;
1669 SUBHEAP *subheap;
1670 HEAP *heapPtr = HEAP_GetPtr( heap );
1671 SIZE_T rounded_size;
1673 /* Validate the parameters */
1675 if (!heapPtr) return NULL;
1676 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1677 flags |= heapPtr->flags;
1678 rounded_size = ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE( flags );
1679 if (rounded_size < size) /* overflow */
1681 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1682 return NULL;
1684 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1686 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1688 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1690 void *ret = allocate_large_block( heap, flags, size );
1691 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1692 if (!ret && (flags & HEAP_GENERATE_EXCEPTIONS)) RtlRaiseStatus( STATUS_NO_MEMORY );
1693 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, ret );
1694 return ret;
1697 /* Locate a suitable free block */
1699 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1701 TRACE("(%p,%08x,%08lx): returning NULL\n",
1702 heap, flags, size );
1703 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1704 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1705 return NULL;
1708 /* Remove the arena from the free list */
1710 list_remove( &pArena->entry );
1712 /* Build the in-use arena */
1714 pInUse = (ARENA_INUSE *)pArena;
1716 /* in-use arena is smaller than free arena,
1717 * so we have to add the difference to the size */
1718 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1719 pInUse->magic = ARENA_INUSE_MAGIC;
1721 /* Shrink the block */
1723 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1724 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1726 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1727 initialize_block( pInUse + 1, size, pInUse->unused_bytes, flags );
1729 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1731 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1732 return pInUse + 1;
1736 /***********************************************************************
1737 * RtlFreeHeap (NTDLL.@)
1739 * Free a memory block allocated with RtlAllocateHeap().
1741 * PARAMS
1742 * heap [I] Heap that block was allocated from
1743 * flags [I] HEAP_ flags from "winnt.h"
1744 * ptr [I] Block to free
1746 * RETURNS
1747 * Success: TRUE, if ptr is NULL or was freed successfully.
1748 * Failure: FALSE.
1750 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1752 ARENA_INUSE *pInUse;
1753 SUBHEAP *subheap;
1754 HEAP *heapPtr;
1756 /* Validate the parameters */
1758 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1760 heapPtr = HEAP_GetPtr( heap );
1761 if (!heapPtr)
1763 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1764 return FALSE;
1767 flags &= HEAP_NO_SERIALIZE;
1768 flags |= heapPtr->flags;
1769 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1771 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1772 notify_free( ptr );
1774 /* Some sanity checks */
1775 pInUse = (ARENA_INUSE *)ptr - 1;
1776 if (!validate_block_pointer( heapPtr, &subheap, pInUse )) goto error;
1778 if (!subheap)
1779 free_large_block( heapPtr, flags, ptr );
1780 else
1781 HEAP_MakeInUseBlockFree( subheap, pInUse );
1783 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1784 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1785 return TRUE;
1787 error:
1788 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1789 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1790 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1791 return FALSE;
1795 /***********************************************************************
1796 * RtlReAllocateHeap (NTDLL.@)
1798 * Change the size of a memory block allocated with RtlAllocateHeap().
1800 * PARAMS
1801 * heap [I] Heap that block was allocated from
1802 * flags [I] HEAP_ flags from "winnt.h"
1803 * ptr [I] Block to resize
1804 * size [I] Size of the memory block to allocate
1806 * RETURNS
1807 * Success: A pointer to the resized block (which may be different).
1808 * Failure: NULL.
1810 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1812 ARENA_INUSE *pArena;
1813 HEAP *heapPtr;
1814 SUBHEAP *subheap;
1815 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1816 void *ret;
1818 if (!ptr) return NULL;
1819 if (!(heapPtr = HEAP_GetPtr( heap )))
1821 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1822 return NULL;
1825 /* Validate the parameters */
1827 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1828 HEAP_REALLOC_IN_PLACE_ONLY;
1829 flags |= heapPtr->flags;
1830 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1832 rounded_size = ROUND_SIZE(size) + HEAP_TAIL_EXTRA_SIZE(flags);
1833 if (rounded_size < size) goto oom; /* overflow */
1834 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1836 pArena = (ARENA_INUSE *)ptr - 1;
1837 if (!validate_block_pointer( heapPtr, &subheap, pArena )) goto error;
1838 if (!subheap)
1840 if (!(ret = realloc_large_block( heapPtr, flags, ptr, size ))) goto oom;
1841 goto done;
1844 /* Check if we need to grow the block */
1846 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1847 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1848 if (rounded_size > oldBlockSize)
1850 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1852 if (rounded_size >= HEAP_MIN_LARGE_BLOCK_SIZE && (flags & HEAP_GROWABLE))
1854 if (flags & HEAP_REALLOC_IN_PLACE_ONLY) goto oom;
1855 if (!(ret = allocate_large_block( heapPtr, flags, size ))) goto oom;
1856 memcpy( ret, pArena + 1, oldActualSize );
1857 notify_free( pArena + 1 );
1858 HEAP_MakeInUseBlockFree( subheap, pArena );
1859 goto done;
1861 if ((pNext < (char *)subheap->base + subheap->size) &&
1862 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1863 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1865 /* The next block is free and large enough */
1866 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1867 list_remove( &pFree->entry );
1868 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1869 if (!HEAP_Commit( subheap, pArena, rounded_size )) goto oom;
1870 notify_realloc( pArena + 1, oldActualSize, size );
1871 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1873 else /* Do it the hard way */
1875 ARENA_FREE *pNew;
1876 ARENA_INUSE *pInUse;
1877 SUBHEAP *newsubheap;
1879 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1880 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1881 goto oom;
1883 /* Build the in-use arena */
1885 list_remove( &pNew->entry );
1886 pInUse = (ARENA_INUSE *)pNew;
1887 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1888 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1889 pInUse->magic = ARENA_INUSE_MAGIC;
1890 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1892 mark_block_initialized( pInUse + 1, oldActualSize );
1893 notify_alloc( pInUse + 1, size, FALSE );
1894 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1896 /* Free the previous block */
1898 notify_free( pArena + 1 );
1899 HEAP_MakeInUseBlockFree( subheap, pArena );
1900 subheap = newsubheap;
1901 pArena = pInUse;
1904 else
1906 notify_realloc( pArena + 1, oldActualSize, size );
1907 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1910 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1912 /* Clear the extra bytes if needed */
1914 if (size > oldActualSize)
1915 initialize_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize,
1916 pArena->unused_bytes, flags );
1917 else
1918 mark_block_tail( (char *)(pArena + 1) + size, pArena->unused_bytes, flags );
1920 /* Return the new arena */
1922 ret = pArena + 1;
1923 done:
1924 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1925 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, ret );
1926 return ret;
1928 oom:
1929 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1930 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1931 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1932 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1933 return NULL;
1935 error:
1936 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1937 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1938 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1939 return NULL;
1943 /***********************************************************************
1944 * RtlCompactHeap (NTDLL.@)
1946 * Compact the free space in a Heap.
1948 * PARAMS
1949 * heap [I] Heap that block was allocated from
1950 * flags [I] HEAP_ flags from "winnt.h"
1952 * RETURNS
1953 * The number of bytes compacted.
1955 * NOTES
1956 * This function is a harmless stub.
1958 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1960 static BOOL reported;
1961 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1962 return 0;
1966 /***********************************************************************
1967 * RtlLockHeap (NTDLL.@)
1969 * Lock a Heap.
1971 * PARAMS
1972 * heap [I] Heap to lock
1974 * RETURNS
1975 * Success: TRUE. The Heap is locked.
1976 * Failure: FALSE, if heap is invalid.
1978 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1980 HEAP *heapPtr = HEAP_GetPtr( heap );
1981 if (!heapPtr) return FALSE;
1982 RtlEnterCriticalSection( &heapPtr->critSection );
1983 return TRUE;
1987 /***********************************************************************
1988 * RtlUnlockHeap (NTDLL.@)
1990 * Unlock a Heap.
1992 * PARAMS
1993 * heap [I] Heap to unlock
1995 * RETURNS
1996 * Success: TRUE. The Heap is unlocked.
1997 * Failure: FALSE, if heap is invalid.
1999 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
2001 HEAP *heapPtr = HEAP_GetPtr( heap );
2002 if (!heapPtr) return FALSE;
2003 RtlLeaveCriticalSection( &heapPtr->critSection );
2004 return TRUE;
2008 /***********************************************************************
2009 * RtlSizeHeap (NTDLL.@)
2011 * Get the actual size of a memory block allocated from a Heap.
2013 * PARAMS
2014 * heap [I] Heap that block was allocated from
2015 * flags [I] HEAP_ flags from "winnt.h"
2016 * ptr [I] Block to get the size of
2018 * RETURNS
2019 * Success: The size of the block.
2020 * Failure: -1, heap or ptr are invalid.
2022 * NOTES
2023 * The size may be bigger than what was passed to RtlAllocateHeap().
2025 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
2027 SIZE_T ret;
2028 const ARENA_INUSE *pArena;
2029 SUBHEAP *subheap;
2030 HEAP *heapPtr = HEAP_GetPtr( heap );
2032 if (!heapPtr)
2034 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
2035 return ~0UL;
2037 flags &= HEAP_NO_SERIALIZE;
2038 flags |= heapPtr->flags;
2039 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
2041 pArena = (const ARENA_INUSE *)ptr - 1;
2042 if (!validate_block_pointer( heapPtr, &subheap, pArena ))
2044 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
2045 ret = ~0UL;
2047 else if (!subheap)
2049 const ARENA_LARGE *large_arena = (const ARENA_LARGE *)ptr - 1;
2050 ret = large_arena->data_size;
2052 else
2054 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
2056 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
2058 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
2059 return ret;
2063 /***********************************************************************
2064 * RtlValidateHeap (NTDLL.@)
2066 * Determine if a block is a valid allocation from a heap.
2068 * PARAMS
2069 * heap [I] Heap that block was allocated from
2070 * flags [I] HEAP_ flags from "winnt.h"
2071 * ptr [I] Block to check
2073 * RETURNS
2074 * Success: TRUE. The block was allocated from heap.
2075 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
2077 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
2079 HEAP *heapPtr = HEAP_GetPtr( heap );
2080 if (!heapPtr) return FALSE;
2081 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
2085 /***********************************************************************
2086 * RtlWalkHeap (NTDLL.@)
2088 * FIXME
2089 * The PROCESS_HEAP_ENTRY flag values seem different between this
2090 * function and HeapWalk(). To be checked.
2092 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
2094 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
2095 HEAP *heapPtr = HEAP_GetPtr(heap);
2096 SUBHEAP *sub, *currentheap = NULL;
2097 NTSTATUS ret;
2098 char *ptr;
2099 int region_index = 0;
2101 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
2103 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
2105 /* FIXME: enumerate large blocks too */
2107 /* set ptr to the next arena to be examined */
2109 if (!entry->lpData) /* first call (init) ? */
2111 TRACE("begin walking of heap %p.\n", heap);
2112 currentheap = &heapPtr->subheap;
2113 ptr = (char*)currentheap->base + currentheap->headerSize;
2115 else
2117 ptr = entry->lpData;
2118 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
2120 if ((ptr >= (char *)sub->base) &&
2121 (ptr < (char *)sub->base + sub->size))
2123 currentheap = sub;
2124 break;
2126 region_index++;
2128 if (currentheap == NULL)
2130 ERR("no matching subheap found, shouldn't happen !\n");
2131 ret = STATUS_NO_MORE_ENTRIES;
2132 goto HW_end;
2135 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC ||
2136 ((ARENA_INUSE *)ptr - 1)->magic == ARENA_PENDING_MAGIC)
2138 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
2139 ptr += pArena->size & ARENA_SIZE_MASK;
2141 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
2143 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
2144 ptr += pArena->size & ARENA_SIZE_MASK;
2146 else
2147 ptr += entry->cbData; /* point to next arena */
2149 if (ptr > (char *)currentheap->base + currentheap->size - 1)
2150 { /* proceed with next subheap */
2151 struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
2152 if (!next)
2153 { /* successfully finished */
2154 TRACE("end reached.\n");
2155 ret = STATUS_NO_MORE_ENTRIES;
2156 goto HW_end;
2158 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
2159 ptr = (char *)currentheap->base + currentheap->headerSize;
2163 entry->wFlags = 0;
2164 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
2166 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
2168 /*TRACE("free, magic: %04x\n", pArena->magic);*/
2170 entry->lpData = pArena + 1;
2171 entry->cbData = pArena->size & ARENA_SIZE_MASK;
2172 entry->cbOverhead = sizeof(ARENA_FREE);
2173 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
2175 else
2177 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
2179 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
2181 entry->lpData = pArena + 1;
2182 entry->cbData = pArena->size & ARENA_SIZE_MASK;
2183 entry->cbOverhead = sizeof(ARENA_INUSE);
2184 entry->wFlags = (pArena->magic == ARENA_PENDING_MAGIC) ?
2185 PROCESS_HEAP_UNCOMMITTED_RANGE : PROCESS_HEAP_ENTRY_BUSY;
2186 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
2187 and PROCESS_HEAP_ENTRY_DDESHARE yet */
2190 entry->iRegionIndex = region_index;
2192 /* first element of heap ? */
2193 if (ptr == (char *)currentheap->base + currentheap->headerSize)
2195 entry->wFlags |= PROCESS_HEAP_REGION;
2196 entry->u.Region.dwCommittedSize = currentheap->commitSize;
2197 entry->u.Region.dwUnCommittedSize =
2198 currentheap->size - currentheap->commitSize;
2199 entry->u.Region.lpFirstBlock = /* first valid block */
2200 (char *)currentheap->base + currentheap->headerSize;
2201 entry->u.Region.lpLastBlock = /* first invalid block */
2202 (char *)currentheap->base + currentheap->size;
2204 ret = STATUS_SUCCESS;
2205 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
2207 HW_end:
2208 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
2209 return ret;
2213 /***********************************************************************
2214 * RtlGetProcessHeaps (NTDLL.@)
2216 * Get the Heaps belonging to the current process.
2218 * PARAMS
2219 * count [I] size of heaps
2220 * heaps [O] Destination array for heap HANDLE's
2222 * RETURNS
2223 * Success: The number of Heaps allocated by the process.
2224 * Failure: 0.
2226 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
2228 ULONG total = 1; /* main heap */
2229 struct list *ptr;
2231 RtlEnterCriticalSection( &processHeap->critSection );
2232 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
2233 if (total <= count)
2235 *heaps++ = processHeap;
2236 LIST_FOR_EACH( ptr, &processHeap->entry )
2237 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
2239 RtlLeaveCriticalSection( &processHeap->critSection );
2240 return total;
2243 /***********************************************************************
2244 * RtlQueryHeapInformation (NTDLL.@)
2246 NTSTATUS WINAPI RtlQueryHeapInformation( HANDLE heap, HEAP_INFORMATION_CLASS info_class,
2247 PVOID info, SIZE_T size_in, PSIZE_T size_out)
2249 switch (info_class)
2251 case HeapCompatibilityInformation:
2252 if (size_out) *size_out = sizeof(ULONG);
2254 if (size_in < sizeof(ULONG))
2255 return STATUS_BUFFER_TOO_SMALL;
2257 *(ULONG *)info = 0; /* standard heap */
2258 return STATUS_SUCCESS;
2260 default:
2261 FIXME("Unknown heap information class %u\n", info_class);
2262 return STATUS_INVALID_INFO_CLASS;
2266 /***********************************************************************
2267 * RtlSetHeapInformation (NTDLL.@)
2269 NTSTATUS WINAPI RtlSetHeapInformation( HANDLE heap, HEAP_INFORMATION_CLASS info_class, PVOID info, SIZE_T size)
2271 FIXME("%p %d %p %ld stub\n", heap, info_class, info, size);
2272 return STATUS_SUCCESS;