push a6a7df41ae272b3b1bf5fcfb544267c1e96afa99
[wine/hacks.git] / dlls / ntdll / heap.c
blobd18489cc2a125f54f22587091b14ab5ce334965b
1 /*
2 * Win32 heap functions
4 * Copyright 1996 Alexandre Julliard
5 * Copyright 1998 Ulrich Weigand
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "config.h"
24 #include <assert.h>
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <string.h>
29 #ifdef HAVE_VALGRIND_MEMCHECK_H
30 #include <valgrind/memcheck.h>
31 #endif
33 #define NONAMELESSUNION
34 #define NONAMELESSSTRUCT
35 #include "ntstatus.h"
36 #define WIN32_NO_STATUS
37 #include "windef.h"
38 #include "winnt.h"
39 #include "winternl.h"
40 #include "wine/list.h"
41 #include "wine/debug.h"
42 #include "wine/server.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(heap);
45 WINE_DECLARE_DEBUG_CHANNEL(heap_poison);
47 /* Note: the heap data structures are loosely based on what Pietrek describes in his
48 * book 'Windows 95 System Programming Secrets', with some adaptations for
49 * better compatibility with NT.
52 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
53 * that there is no unaligned accesses to structure fields.
56 typedef struct tagARENA_INUSE
58 DWORD size; /* Block size; must be the first field */
59 DWORD magic : 24; /* Magic number */
60 DWORD unused_bytes : 8; /* Number of bytes in the block not used by user data (max value is HEAP_MIN_DATA_SIZE+HEAP_MIN_SHRINK_SIZE) */
61 } ARENA_INUSE;
63 typedef struct tagARENA_FREE
65 DWORD size; /* Block size; must be the first field */
66 DWORD magic; /* Magic number */
67 struct list entry; /* Entry in free list */
68 } ARENA_FREE;
70 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
71 #define ARENA_FLAG_PREV_FREE 0x00000002
72 #define ARENA_SIZE_MASK (~3)
73 #define ARENA_INUSE_MAGIC 0x455355 /* Value for arena 'magic' field */
74 #define ARENA_FREE_MAGIC 0x45455246 /* Value for arena 'magic' field */
76 #define ARENA_INUSE_FILLER 0x55
77 #define ARENA_FREE_FILLER 0xaa
79 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
80 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
82 #define QUIET 1 /* Suppress messages */
83 #define NOISY 0 /* Report all errors */
85 /* minimum data size (without arenas) of an allocated block */
86 /* make sure that it's larger than a free list entry */
87 #define HEAP_MIN_DATA_SIZE (2 * sizeof(struct list))
88 /* minimum size that must remain to shrink an allocated block */
89 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
91 /* Max size of the blocks on the free lists */
92 static const SIZE_T HEAP_freeListSizes[] =
94 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
96 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
98 typedef struct
100 ARENA_FREE arena;
101 } FREE_LIST_ENTRY;
103 struct tagHEAP;
105 typedef struct tagSUBHEAP
107 void *base; /* Base address of the sub-heap memory block */
108 SIZE_T size; /* Size of the whole sub-heap */
109 SIZE_T commitSize; /* Committed size of the sub-heap */
110 struct list entry; /* Entry in sub-heap list */
111 struct tagHEAP *heap; /* Main heap structure */
112 DWORD headerSize; /* Size of the heap header */
113 DWORD magic; /* Magic number */
114 } SUBHEAP;
116 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
118 typedef struct tagHEAP
120 DWORD unknown[3];
121 DWORD flags; /* Heap flags */
122 DWORD force_flags; /* Forced heap flags for debugging */
123 SUBHEAP subheap; /* First sub-heap */
124 struct list entry; /* Entry in process heap list */
125 struct list subheap_list; /* Sub-heap list */
126 DWORD magic; /* Magic number */
127 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
128 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
129 } HEAP;
131 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
133 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
134 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
136 static HEAP *processHeap; /* main process heap */
138 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
140 /* mark a block of memory as free for debugging purposes */
141 static inline void mark_block_free( void *ptr, SIZE_T size )
143 if (TRACE_ON(heap) || WARN_ON(heap) || TRACE_ON(heap_poison)) memset( ptr, ARENA_FREE_FILLER, size );
144 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
145 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
146 #elif defined( VALGRIND_MAKE_NOACCESS)
147 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
148 #endif
151 /* mark a block of memory as initialized for debugging purposes */
152 static inline void mark_block_initialized( void *ptr, SIZE_T size )
154 #if defined(VALGRIND_MAKE_MEM_DEFINED)
155 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
156 #elif defined(VALGRIND_MAKE_READABLE)
157 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
158 #endif
161 /* mark a block of memory as uninitialized for debugging purposes */
162 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
164 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
165 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
166 #elif defined(VALGRIND_MAKE_WRITABLE)
167 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
168 #endif
169 if (TRACE_ON(heap) || WARN_ON(heap) || TRACE_ON(heap_poison))
171 memset( ptr, ARENA_INUSE_FILLER, size );
172 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
173 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
174 #elif defined(VALGRIND_MAKE_WRITABLE)
175 /* make it uninitialized to valgrind again */
176 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
177 #endif
181 /* clear contents of a block of memory */
182 static inline void clear_block( void *ptr, SIZE_T size )
184 mark_block_initialized( ptr, size );
185 memset( ptr, 0, size );
188 /* notify that a new block of memory has been allocated for debugging purposes */
189 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
191 #ifdef VALGRIND_MALLOCLIKE_BLOCK
192 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
193 #endif
196 /* notify that a block of memory has been freed for debugging purposes */
197 static inline void notify_free( void const *ptr )
199 #ifdef VALGRIND_FREELIKE_BLOCK
200 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
201 #endif
204 static void subheap_notify_free_all(SUBHEAP const *subheap)
206 #ifdef VALGRIND_FREELIKE_BLOCK
207 char const *ptr = (char const *)subheap->base + subheap->headerSize;
209 if (!RUNNING_ON_VALGRIND) return;
211 while (ptr < (char const *)subheap->base + subheap->size)
213 if (*(const DWORD *)ptr & ARENA_FLAG_FREE)
215 ARENA_FREE const *pArena = (ARENA_FREE const *)ptr;
216 if (pArena->magic!=ARENA_FREE_MAGIC) ERR("bad free_magic @%p\n", pArena);
217 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
219 else
221 ARENA_INUSE const *pArena = (ARENA_INUSE const *)ptr;
222 if (pArena->magic!=ARENA_INUSE_MAGIC) ERR("bad inuse_magic @%p\n", pArena);
223 notify_free(pArena + 1);
224 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
227 #endif
230 /* locate a free list entry of the appropriate size */
231 /* size is the size of the whole block including the arena header */
232 static inline unsigned int get_freelist_index( SIZE_T size )
234 unsigned int i;
236 size -= sizeof(ARENA_FREE);
237 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
238 return i;
241 /* get the memory protection type to use for a given heap */
242 static inline ULONG get_protection_type( DWORD flags )
244 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
247 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
249 0, 0, NULL, /* will be set later */
250 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
251 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
255 /***********************************************************************
256 * HEAP_Dump
258 static void HEAP_Dump( HEAP *heap )
260 unsigned int i;
261 SUBHEAP *subheap;
262 char *ptr;
264 DPRINTF( "Heap: %p\n", heap );
265 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
266 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
268 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
269 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
270 DPRINTF( "%p free %08lx prev=%p next=%p\n",
271 &heap->freeList[i].arena, HEAP_freeListSizes[i],
272 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
273 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
275 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
277 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
278 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
279 subheap, subheap->base, subheap->size, subheap->commitSize );
281 DPRINTF( "\n Block Arena Stat Size Id\n" );
282 ptr = (char *)subheap->base + subheap->headerSize;
283 while (ptr < (char *)subheap->base + subheap->size)
285 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
287 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
288 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
289 pArena, pArena->magic,
290 pArena->size & ARENA_SIZE_MASK,
291 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
292 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
293 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
294 arenaSize += sizeof(ARENA_FREE);
295 freeSize += pArena->size & ARENA_SIZE_MASK;
297 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
299 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
300 DPRINTF( "%p %08x Used %08x back=%p\n",
301 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
302 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
303 arenaSize += sizeof(ARENA_INUSE);
304 usedSize += pArena->size & ARENA_SIZE_MASK;
306 else
308 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
309 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
310 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
311 arenaSize += sizeof(ARENA_INUSE);
312 usedSize += pArena->size & ARENA_SIZE_MASK;
315 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
316 subheap->size, subheap->commitSize, freeSize, usedSize,
317 arenaSize, (arenaSize * 100) / subheap->size );
322 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
324 WORD rem_flags;
325 TRACE( "Dumping entry %p\n", entry );
326 TRACE( "lpData\t\t: %p\n", entry->lpData );
327 TRACE( "cbData\t\t: %08x\n", entry->cbData);
328 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
329 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
330 TRACE( "WFlags\t\t: ");
331 if (entry->wFlags & PROCESS_HEAP_REGION)
332 TRACE( "PROCESS_HEAP_REGION ");
333 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
334 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
335 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
336 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
337 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
338 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
339 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
340 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
341 rem_flags = entry->wFlags &
342 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
343 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
344 PROCESS_HEAP_ENTRY_DDESHARE);
345 if (rem_flags)
346 TRACE( "Unknown %08x", rem_flags);
347 TRACE( "\n");
348 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
349 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
351 /* Treat as block */
352 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
354 if (entry->wFlags & PROCESS_HEAP_REGION)
356 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
357 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
358 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
359 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
363 /***********************************************************************
364 * HEAP_GetPtr
365 * RETURNS
366 * Pointer to the heap
367 * NULL: Failure
369 static HEAP *HEAP_GetPtr(
370 HANDLE heap /* [in] Handle to the heap */
372 HEAP *heapPtr = (HEAP *)heap;
373 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
375 ERR("Invalid heap %p!\n", heap );
376 return NULL;
378 if ((TRACE_ON(heap)|| TRACE_ON(heap_poison)) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
380 HEAP_Dump( heapPtr );
381 assert( FALSE );
382 return NULL;
384 return heapPtr;
388 /***********************************************************************
389 * HEAP_InsertFreeBlock
391 * Insert a free block into the free list.
393 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
395 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
396 if (last)
398 /* insert at end of free list, i.e. before the next free list entry */
399 pEntry++;
400 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
401 list_add_before( &pEntry->arena.entry, &pArena->entry );
403 else
405 /* insert at head of free list */
406 list_add_after( &pEntry->arena.entry, &pArena->entry );
408 pArena->size |= ARENA_FLAG_FREE;
412 /***********************************************************************
413 * HEAP_FindSubHeap
414 * Find the sub-heap containing a given address.
416 * RETURNS
417 * Pointer: Success
418 * NULL: Failure
420 static SUBHEAP *HEAP_FindSubHeap(
421 const HEAP *heap, /* [in] Heap pointer */
422 LPCVOID ptr ) /* [in] Address */
424 SUBHEAP *sub;
425 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
426 if (((const char *)ptr >= (const char *)sub->base) &&
427 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
428 return sub;
429 return NULL;
433 /***********************************************************************
434 * HEAP_Commit
436 * Make sure the heap storage is committed for a given size in the specified arena.
438 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
440 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
441 SIZE_T size = (char *)ptr - (char *)subheap->base;
442 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
443 if (size > subheap->size) size = subheap->size;
444 if (size <= subheap->commitSize) return TRUE;
445 size -= subheap->commitSize;
446 ptr = (char *)subheap->base + subheap->commitSize;
447 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
448 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
450 WARN("Could not commit %08lx bytes at %p for heap %p\n",
451 size, ptr, subheap->heap );
452 return FALSE;
454 subheap->commitSize += size;
455 return TRUE;
459 /***********************************************************************
460 * HEAP_Decommit
462 * If possible, decommit the heap storage from (including) 'ptr'.
464 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
466 void *addr;
467 SIZE_T decommit_size;
468 SIZE_T size = (char *)ptr - (char *)subheap->base;
470 /* round to next block and add one full block */
471 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
472 if (size >= subheap->commitSize) return TRUE;
473 decommit_size = subheap->commitSize - size;
474 addr = (char *)subheap->base + size;
476 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
478 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
479 decommit_size, (char *)subheap->base + size, subheap->heap );
480 return FALSE;
482 subheap->commitSize -= decommit_size;
483 return TRUE;
487 /***********************************************************************
488 * HEAP_CreateFreeBlock
490 * Create a free block at a specified address. 'size' is the size of the
491 * whole block, including the new arena.
493 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
495 ARENA_FREE *pFree;
496 char *pEnd;
497 BOOL last;
499 /* Create a free arena */
500 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
501 pFree = (ARENA_FREE *)ptr;
502 pFree->magic = ARENA_FREE_MAGIC;
504 /* If debugging, erase the freed block content */
506 pEnd = (char *)ptr + size;
507 if (pEnd > (char *)subheap->base + subheap->commitSize)
508 pEnd = (char *)subheap->base + subheap->commitSize;
509 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
511 /* Check if next block is free also */
513 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
514 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
516 /* Remove the next arena from the free list */
517 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
518 list_remove( &pNext->entry );
519 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
520 mark_block_free( pNext, sizeof(ARENA_FREE) );
523 /* Set the next block PREV_FREE flag and pointer */
525 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
526 if (!last)
528 DWORD *pNext = (DWORD *)((char *)ptr + size);
529 *pNext |= ARENA_FLAG_PREV_FREE;
530 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
531 *((ARENA_FREE **)pNext - 1) = pFree;
534 /* Last, insert the new block into the free list */
536 pFree->size = size - sizeof(*pFree);
537 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
541 /***********************************************************************
542 * HEAP_MakeInUseBlockFree
544 * Turn an in-use block into a free block. Can also decommit the end of
545 * the heap, and possibly even free the sub-heap altogether.
547 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
549 ARENA_FREE *pFree;
550 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
552 /* Check if we can merge with previous block */
554 if (pArena->size & ARENA_FLAG_PREV_FREE)
556 pFree = *((ARENA_FREE **)pArena - 1);
557 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
558 /* Remove it from the free list */
559 list_remove( &pFree->entry );
561 else pFree = (ARENA_FREE *)pArena;
563 /* Create a free block */
565 HEAP_CreateFreeBlock( subheap, pFree, size );
566 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
567 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
568 return; /* Not the last block, so nothing more to do */
570 /* Free the whole sub-heap if it's empty and not the original one */
572 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
573 (subheap != &subheap->heap->subheap))
575 SIZE_T size = 0;
576 void *addr = subheap->base;
577 /* Remove the free block from the list */
578 list_remove( &pFree->entry );
579 /* Remove the subheap from the list */
580 list_remove( &subheap->entry );
581 /* Free the memory */
582 subheap->magic = 0;
583 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
584 return;
587 /* Decommit the end of the heap */
589 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
593 /***********************************************************************
594 * HEAP_ShrinkBlock
596 * Shrink an in-use block.
598 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
600 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
602 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
603 (pArena->size & ARENA_SIZE_MASK) - size );
604 /* assign size plus previous arena flags */
605 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
607 else
609 /* Turn off PREV_FREE flag in next block */
610 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
611 if (pNext < (char *)subheap->base + subheap->size)
612 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
616 /***********************************************************************
617 * HEAP_InitSubHeap
619 static SUBHEAP *HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
620 SIZE_T commitSize, SIZE_T totalSize )
622 SUBHEAP *subheap;
623 FREE_LIST_ENTRY *pEntry;
624 unsigned int i;
626 /* Commit memory */
628 if (flags & HEAP_SHARED)
629 commitSize = totalSize; /* always commit everything in a shared heap */
630 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
631 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
633 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
634 return NULL;
637 if (heap)
639 /* If this is a secondary subheap, insert it into list */
641 subheap = (SUBHEAP *)address;
642 subheap->base = address;
643 subheap->heap = heap;
644 subheap->size = totalSize;
645 subheap->commitSize = commitSize;
646 subheap->magic = SUBHEAP_MAGIC;
647 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
648 list_add_head( &heap->subheap_list, &subheap->entry );
650 else
652 /* If this is a primary subheap, initialize main heap */
654 heap = (HEAP *)address;
655 heap->flags = flags;
656 heap->magic = HEAP_MAGIC;
657 list_init( &heap->subheap_list );
659 subheap = &heap->subheap;
660 subheap->base = address;
661 subheap->heap = heap;
662 subheap->size = totalSize;
663 subheap->commitSize = commitSize;
664 subheap->magic = SUBHEAP_MAGIC;
665 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
666 list_add_head( &heap->subheap_list, &subheap->entry );
668 /* Build the free lists */
670 list_init( &heap->freeList[0].arena.entry );
671 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
673 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
674 pEntry->arena.magic = ARENA_FREE_MAGIC;
675 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
678 /* Initialize critical section */
680 if (!processHeap) /* do it by hand to avoid memory allocations */
682 if(TRACE_ON(heap_poison))
683 TRACE_(heap_poison)("poisioning heap\n");
684 heap->critSection.DebugInfo = &process_heap_critsect_debug;
685 heap->critSection.LockCount = -1;
686 heap->critSection.RecursionCount = 0;
687 heap->critSection.OwningThread = 0;
688 heap->critSection.LockSemaphore = 0;
689 heap->critSection.SpinCount = 0;
690 process_heap_critsect_debug.CriticalSection = &heap->critSection;
692 else
694 RtlInitializeCriticalSection( &heap->critSection );
695 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
698 if (flags & HEAP_SHARED)
700 /* let's assume that only one thread at a time will try to do this */
701 HANDLE sem = heap->critSection.LockSemaphore;
702 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
704 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
705 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
706 heap->critSection.LockSemaphore = sem;
707 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
708 heap->critSection.DebugInfo = NULL;
712 /* Create the first free block */
714 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
715 subheap->size - subheap->headerSize );
717 return subheap;
720 /***********************************************************************
721 * HEAP_CreateSubHeap
723 * Create a sub-heap of the given size.
724 * If heap == NULL, creates a main heap.
726 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
727 SIZE_T commitSize, SIZE_T totalSize )
729 LPVOID address = base;
730 SUBHEAP *ret;
732 /* round-up sizes on a 64K boundary */
733 totalSize = (totalSize + 0xffff) & 0xffff0000;
734 commitSize = (commitSize + 0xffff) & 0xffff0000;
735 if (!commitSize) commitSize = 0x10000;
736 if (totalSize < commitSize) totalSize = commitSize;
738 if (!address)
740 /* allocate the memory block */
741 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
742 MEM_RESERVE, get_protection_type( flags ) ))
744 WARN("Could not allocate %08lx bytes\n", totalSize );
745 return NULL;
749 /* Initialize subheap */
751 if (!(ret = HEAP_InitSubHeap( heap, address, flags, commitSize, totalSize )))
753 SIZE_T size = 0;
754 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
756 return ret;
760 /***********************************************************************
761 * HEAP_FindFreeBlock
763 * Find a free block at least as large as the requested size, and make sure
764 * the requested size is committed.
766 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
767 SUBHEAP **ppSubHeap )
769 SUBHEAP *subheap;
770 struct list *ptr;
771 SIZE_T total_size;
772 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
774 /* Find a suitable free list, and in it find a block large enough */
776 ptr = &pEntry->arena.entry;
777 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
779 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
780 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
781 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
782 if (arena_size >= size)
784 subheap = HEAP_FindSubHeap( heap, pArena );
785 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
786 *ppSubHeap = subheap;
787 return pArena;
791 /* If no block was found, attempt to grow the heap */
793 if (!(heap->flags & HEAP_GROWABLE))
795 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
796 return NULL;
798 /* make sure that we have a big enough size *committed* to fit another
799 * last free arena in !
800 * So just one heap struct, one first free arena which will eventually
801 * get used, and a second free arena that might get assigned all remaining
802 * free space in HEAP_ShrinkBlock() */
803 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
804 if (total_size < size) return NULL; /* overflow */
806 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
807 max( HEAP_DEF_SIZE, total_size ) )))
808 return NULL;
810 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
811 subheap, total_size, heap );
813 *ppSubHeap = subheap;
814 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
818 /***********************************************************************
819 * HEAP_IsValidArenaPtr
821 * Check that the pointer is inside the range possible for arenas.
823 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
825 unsigned int i;
826 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
827 if (!subheap) return FALSE;
828 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
829 if (subheap != &heap->subheap) return FALSE;
830 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
831 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
832 return FALSE;
836 /***********************************************************************
837 * HEAP_ValidateFreeArena
839 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
841 ARENA_FREE *prev, *next;
842 char *heapEnd = (char *)subheap->base + subheap->size;
844 /* Check for unaligned pointers */
845 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
847 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
848 return FALSE;
851 /* Check magic number */
852 if (pArena->magic != ARENA_FREE_MAGIC)
854 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
855 return FALSE;
857 /* Check size flags */
858 if (!(pArena->size & ARENA_FLAG_FREE) ||
859 (pArena->size & ARENA_FLAG_PREV_FREE))
861 ERR("Heap %p: bad flags %08x for free arena %p\n",
862 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
863 return FALSE;
865 /* Check arena size */
866 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
868 ERR("Heap %p: bad size %08x for free arena %p\n",
869 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
870 return FALSE;
872 /* Check that next pointer is valid */
873 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
874 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
876 ERR("Heap %p: bad next ptr %p for arena %p\n",
877 subheap->heap, next, pArena );
878 return FALSE;
880 /* Check that next arena is free */
881 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
883 ERR("Heap %p: next arena %p invalid for %p\n",
884 subheap->heap, next, pArena );
885 return FALSE;
887 /* Check that prev pointer is valid */
888 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
889 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
891 ERR("Heap %p: bad prev ptr %p for arena %p\n",
892 subheap->heap, prev, pArena );
893 return FALSE;
895 /* Check that prev arena is free */
896 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
898 /* this often means that the prev arena got overwritten
899 * by a memory write before that prev arena */
900 ERR("Heap %p: prev arena %p invalid for %p\n",
901 subheap->heap, prev, pArena );
902 return FALSE;
904 /* Check that next block has PREV_FREE flag */
905 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
907 if (!(*(DWORD *)((char *)(pArena + 1) +
908 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
910 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
911 subheap->heap, pArena );
912 return FALSE;
914 /* Check next block back pointer */
915 if (*((ARENA_FREE **)((char *)(pArena + 1) +
916 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
918 ERR("Heap %p: arena %p has wrong back ptr %p\n",
919 subheap->heap, pArena,
920 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
921 return FALSE;
924 return TRUE;
928 /***********************************************************************
929 * HEAP_ValidateInUseArena
931 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
933 const char *heapEnd = (const char *)subheap->base + subheap->size;
935 /* Check for unaligned pointers */
936 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
938 if ( quiet == NOISY )
940 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
941 if ( TRACE_ON(heap) )
942 HEAP_Dump( subheap->heap );
944 else if ( WARN_ON(heap) )
946 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
947 if ( TRACE_ON(heap) )
948 HEAP_Dump( subheap->heap );
950 return FALSE;
953 /* Check magic number */
954 if (pArena->magic != ARENA_INUSE_MAGIC)
956 if (quiet == NOISY) {
957 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
958 if (TRACE_ON(heap))
959 HEAP_Dump( subheap->heap );
960 } else if (WARN_ON(heap)) {
961 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
962 if (TRACE_ON(heap))
963 HEAP_Dump( subheap->heap );
965 return FALSE;
967 /* Check size flags */
968 if (pArena->size & ARENA_FLAG_FREE)
970 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
971 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
972 return FALSE;
974 /* Check arena size */
975 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
977 ERR("Heap %p: bad size %08x for in-use arena %p\n",
978 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
979 return FALSE;
981 /* Check next arena PREV_FREE flag */
982 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
983 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
985 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
986 subheap->heap, pArena );
987 return FALSE;
989 /* Check prev free arena */
990 if (pArena->size & ARENA_FLAG_PREV_FREE)
992 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
993 /* Check prev pointer */
994 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
996 ERR("Heap %p: bad back ptr %p for arena %p\n",
997 subheap->heap, pPrev, pArena );
998 return FALSE;
1000 /* Check that prev arena is free */
1001 if (!(pPrev->size & ARENA_FLAG_FREE) ||
1002 (pPrev->magic != ARENA_FREE_MAGIC))
1004 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1005 subheap->heap, pPrev, pArena );
1006 return FALSE;
1008 /* Check that prev arena is really the previous block */
1009 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
1011 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1012 subheap->heap, pPrev, pArena );
1013 return FALSE;
1016 return TRUE;
1020 /***********************************************************************
1021 * HEAP_IsRealArena [Internal]
1022 * Validates a block is a valid arena.
1024 * RETURNS
1025 * TRUE: Success
1026 * FALSE: Failure
1028 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1029 DWORD flags, /* [in] Bit flags that control access during operation */
1030 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1031 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1032 * does not complain */
1034 SUBHEAP *subheap;
1035 BOOL ret = TRUE;
1037 flags &= HEAP_NO_SERIALIZE;
1038 flags |= heapPtr->flags;
1039 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1040 if (!(flags & HEAP_NO_SERIALIZE))
1041 RtlEnterCriticalSection( &heapPtr->critSection );
1043 if (block) /* only check this single memory block */
1045 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1047 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1048 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1050 if (quiet == NOISY)
1051 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1052 else if (WARN_ON(heap))
1053 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1054 ret = FALSE;
1055 } else
1056 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1058 if (!(flags & HEAP_NO_SERIALIZE))
1059 RtlLeaveCriticalSection( &heapPtr->critSection );
1060 return ret;
1063 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1065 char *ptr = (char *)subheap->base + subheap->headerSize;
1066 while (ptr < (char *)subheap->base + subheap->size)
1068 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1070 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1071 ret = FALSE;
1072 break;
1074 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1076 else
1078 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1079 ret = FALSE;
1080 break;
1082 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1085 if (!ret) break;
1088 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1089 return ret;
1093 /***********************************************************************
1094 * RtlCreateHeap (NTDLL.@)
1096 * Create a new Heap.
1098 * PARAMS
1099 * flags [I] HEAP_ flags from "winnt.h"
1100 * addr [I] Desired base address
1101 * totalSize [I] Total size of the heap, or 0 for a growable heap
1102 * commitSize [I] Amount of heap space to commit
1103 * unknown [I] Not yet understood
1104 * definition [I] Heap definition
1106 * RETURNS
1107 * Success: A HANDLE to the newly created heap.
1108 * Failure: a NULL HANDLE.
1110 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1111 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1113 SUBHEAP *subheap;
1115 /* Allocate the heap block */
1117 if (!totalSize)
1119 totalSize = HEAP_DEF_SIZE;
1120 flags |= HEAP_GROWABLE;
1123 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1125 /* link it into the per-process heap list */
1126 if (processHeap)
1128 HEAP *heapPtr = subheap->heap;
1129 RtlEnterCriticalSection( &processHeap->critSection );
1130 list_add_head( &processHeap->entry, &heapPtr->entry );
1131 RtlLeaveCriticalSection( &processHeap->critSection );
1133 else
1135 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1136 list_init( &processHeap->entry );
1137 /* make sure structure alignment is correct */
1138 assert( (ULONG_PTR)processHeap->freeList % ALIGNMENT == 0 );
1141 return (HANDLE)subheap->heap;
1145 /***********************************************************************
1146 * RtlDestroyHeap (NTDLL.@)
1148 * Destroy a Heap created with RtlCreateHeap().
1150 * PARAMS
1151 * heap [I] Heap to destroy.
1153 * RETURNS
1154 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1155 * Failure: The Heap handle, if heap is the process heap.
1157 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1159 HEAP *heapPtr = HEAP_GetPtr( heap );
1160 SUBHEAP *subheap, *next;
1161 SIZE_T size;
1162 void *addr;
1164 TRACE("%p\n", heap );
1165 if (!heapPtr) return heap;
1167 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1169 /* remove it from the per-process list */
1170 RtlEnterCriticalSection( &processHeap->critSection );
1171 list_remove( &heapPtr->entry );
1172 RtlLeaveCriticalSection( &processHeap->critSection );
1174 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1175 RtlDeleteCriticalSection( &heapPtr->critSection );
1177 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1179 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1180 subheap_notify_free_all(subheap);
1181 list_remove( &subheap->entry );
1182 size = 0;
1183 addr = subheap->base;
1184 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1186 subheap_notify_free_all(&heapPtr->subheap);
1187 size = 0;
1188 addr = heapPtr->subheap.base;
1189 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1190 return 0;
1194 /***********************************************************************
1195 * RtlAllocateHeap (NTDLL.@)
1197 * Allocate a memory block from a Heap.
1199 * PARAMS
1200 * heap [I] Heap to allocate block from
1201 * flags [I] HEAP_ flags from "winnt.h"
1202 * size [I] Size of the memory block to allocate
1204 * RETURNS
1205 * Success: A pointer to the newly allocated block
1206 * Failure: NULL.
1208 * NOTES
1209 * This call does not SetLastError().
1211 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1213 ARENA_FREE *pArena;
1214 ARENA_INUSE *pInUse;
1215 SUBHEAP *subheap;
1216 HEAP *heapPtr = HEAP_GetPtr( heap );
1217 SIZE_T rounded_size;
1219 /* Validate the parameters */
1221 if (!heapPtr) return NULL;
1222 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1223 flags |= heapPtr->flags;
1224 rounded_size = ROUND_SIZE(size);
1225 if (rounded_size < size) /* overflow */
1227 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1228 return NULL;
1230 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1232 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1233 /* Locate a suitable free block */
1235 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1237 TRACE("(%p,%08x,%08lx): returning NULL\n",
1238 heap, flags, size );
1239 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1240 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1241 return NULL;
1244 /* Remove the arena from the free list */
1246 list_remove( &pArena->entry );
1248 /* Build the in-use arena */
1250 pInUse = (ARENA_INUSE *)pArena;
1252 /* in-use arena is smaller than free arena,
1253 * so we have to add the difference to the size */
1254 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1255 pInUse->magic = ARENA_INUSE_MAGIC;
1257 /* Shrink the block */
1259 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1260 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1262 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1264 if (flags & HEAP_ZERO_MEMORY)
1266 clear_block( pInUse + 1, size );
1267 mark_block_uninitialized( (char *)(pInUse + 1) + size, pInUse->unused_bytes );
1269 else
1270 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1272 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1274 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1275 return (LPVOID)(pInUse + 1);
1279 /***********************************************************************
1280 * RtlFreeHeap (NTDLL.@)
1282 * Free a memory block allocated with RtlAllocateHeap().
1284 * PARAMS
1285 * heap [I] Heap that block was allocated from
1286 * flags [I] HEAP_ flags from "winnt.h"
1287 * ptr [I] Block to free
1289 * RETURNS
1290 * Success: TRUE, if ptr is NULL or was freed successfully.
1291 * Failure: FALSE.
1293 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1295 ARENA_INUSE *pInUse;
1296 SUBHEAP *subheap;
1297 HEAP *heapPtr;
1299 /* Validate the parameters */
1301 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1303 heapPtr = HEAP_GetPtr( heap );
1304 if (!heapPtr)
1306 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1307 return FALSE;
1310 flags &= HEAP_NO_SERIALIZE;
1311 flags |= heapPtr->flags;
1312 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1314 /* Inform valgrind we are trying to free memory, so it can throw up an error message */
1315 notify_free( ptr );
1317 /* Some sanity checks */
1318 pInUse = (ARENA_INUSE *)ptr - 1;
1319 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse ))) goto error;
1320 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1321 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1323 /* Turn the block into a free block */
1325 HEAP_MakeInUseBlockFree( subheap, pInUse );
1327 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1329 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1330 return TRUE;
1332 error:
1333 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1334 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1335 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1336 return FALSE;
1340 /***********************************************************************
1341 * RtlReAllocateHeap (NTDLL.@)
1343 * Change the size of a memory block allocated with RtlAllocateHeap().
1345 * PARAMS
1346 * heap [I] Heap that block was allocated from
1347 * flags [I] HEAP_ flags from "winnt.h"
1348 * ptr [I] Block to resize
1349 * size [I] Size of the memory block to allocate
1351 * RETURNS
1352 * Success: A pointer to the resized block (which may be different).
1353 * Failure: NULL.
1355 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1357 ARENA_INUSE *pArena;
1358 HEAP *heapPtr;
1359 SUBHEAP *subheap;
1360 SIZE_T oldBlockSize, oldActualSize, rounded_size;
1362 if (!ptr) return NULL;
1363 if (!(heapPtr = HEAP_GetPtr( heap )))
1365 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1366 return NULL;
1369 /* Validate the parameters */
1371 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1372 HEAP_REALLOC_IN_PLACE_ONLY;
1373 flags |= heapPtr->flags;
1374 rounded_size = ROUND_SIZE(size);
1375 if (rounded_size < size) /* overflow */
1377 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1378 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1379 return NULL;
1381 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1383 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1385 pArena = (ARENA_INUSE *)ptr - 1;
1386 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena ))) goto error;
1387 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1388 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1390 /* Check if we need to grow the block */
1392 oldBlockSize = (pArena->size & ARENA_SIZE_MASK);
1393 oldActualSize = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1394 if (rounded_size > oldBlockSize)
1396 char *pNext = (char *)(pArena + 1) + oldBlockSize;
1397 if ((pNext < (char *)subheap->base + subheap->size) &&
1398 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1399 (oldBlockSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1401 /* The next block is free and large enough */
1402 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1403 list_remove( &pFree->entry );
1404 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1405 if (!HEAP_Commit( subheap, pArena, rounded_size ))
1407 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1408 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1409 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1410 return NULL;
1412 notify_free( pArena + 1 );
1413 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1414 notify_alloc( pArena + 1, size, FALSE );
1415 /* FIXME: this is wrong as we may lose old VBits settings */
1416 mark_block_initialized( pArena + 1, oldActualSize );
1418 else /* Do it the hard way */
1420 ARENA_FREE *pNew;
1421 ARENA_INUSE *pInUse;
1422 SUBHEAP *newsubheap;
1424 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1425 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1427 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1428 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1429 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1430 return NULL;
1433 /* Build the in-use arena */
1435 list_remove( &pNew->entry );
1436 pInUse = (ARENA_INUSE *)pNew;
1437 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1438 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1439 pInUse->magic = ARENA_INUSE_MAGIC;
1440 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1442 mark_block_initialized( pInUse + 1, oldActualSize );
1443 notify_alloc( pInUse + 1, size, FALSE );
1444 memcpy( pInUse + 1, pArena + 1, oldActualSize );
1446 /* Free the previous block */
1448 notify_free( pArena + 1 );
1449 HEAP_MakeInUseBlockFree( subheap, pArena );
1450 subheap = newsubheap;
1451 pArena = pInUse;
1454 else
1456 /* Shrink the block */
1457 notify_free( pArena + 1 );
1458 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1459 notify_alloc( pArena + 1, size, FALSE );
1460 /* FIXME: this is wrong as we may lose old VBits settings */
1461 mark_block_initialized( pArena + 1, size );
1464 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1466 /* Clear the extra bytes if needed */
1468 if (size > oldActualSize)
1470 if (flags & HEAP_ZERO_MEMORY)
1472 clear_block( (char *)(pArena + 1) + oldActualSize, size - oldActualSize );
1473 mark_block_uninitialized( (char *)(pArena + 1) + size, pArena->unused_bytes );
1475 else
1476 mark_block_uninitialized( (char *)(pArena + 1) + oldActualSize,
1477 (pArena->size & ARENA_SIZE_MASK) - oldActualSize );
1480 /* Return the new arena */
1482 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1484 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1485 return (LPVOID)(pArena + 1);
1487 error:
1488 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1489 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1490 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1491 return NULL;
1495 /***********************************************************************
1496 * RtlCompactHeap (NTDLL.@)
1498 * Compact the free space in a Heap.
1500 * PARAMS
1501 * heap [I] Heap that block was allocated from
1502 * flags [I] HEAP_ flags from "winnt.h"
1504 * RETURNS
1505 * The number of bytes compacted.
1507 * NOTES
1508 * This function is a harmless stub.
1510 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1512 static BOOL reported;
1513 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1514 return 0;
1518 /***********************************************************************
1519 * RtlLockHeap (NTDLL.@)
1521 * Lock a Heap.
1523 * PARAMS
1524 * heap [I] Heap to lock
1526 * RETURNS
1527 * Success: TRUE. The Heap is locked.
1528 * Failure: FALSE, if heap is invalid.
1530 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1532 HEAP *heapPtr = HEAP_GetPtr( heap );
1533 if (!heapPtr) return FALSE;
1534 RtlEnterCriticalSection( &heapPtr->critSection );
1535 return TRUE;
1539 /***********************************************************************
1540 * RtlUnlockHeap (NTDLL.@)
1542 * Unlock a Heap.
1544 * PARAMS
1545 * heap [I] Heap to unlock
1547 * RETURNS
1548 * Success: TRUE. The Heap is unlocked.
1549 * Failure: FALSE, if heap is invalid.
1551 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1553 HEAP *heapPtr = HEAP_GetPtr( heap );
1554 if (!heapPtr) return FALSE;
1555 RtlLeaveCriticalSection( &heapPtr->critSection );
1556 return TRUE;
1560 /***********************************************************************
1561 * RtlSizeHeap (NTDLL.@)
1563 * Get the actual size of a memory block allocated from a Heap.
1565 * PARAMS
1566 * heap [I] Heap that block was allocated from
1567 * flags [I] HEAP_ flags from "winnt.h"
1568 * ptr [I] Block to get the size of
1570 * RETURNS
1571 * Success: The size of the block.
1572 * Failure: -1, heap or ptr are invalid.
1574 * NOTES
1575 * The size may be bigger than what was passed to RtlAllocateHeap().
1577 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1579 SIZE_T ret;
1580 HEAP *heapPtr = HEAP_GetPtr( heap );
1582 if (!heapPtr)
1584 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1585 return ~0UL;
1587 flags &= HEAP_NO_SERIALIZE;
1588 flags |= heapPtr->flags;
1589 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1590 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1592 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1593 ret = ~0UL;
1595 else
1597 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1598 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1600 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1602 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1603 return ret;
1607 /***********************************************************************
1608 * RtlValidateHeap (NTDLL.@)
1610 * Determine if a block is a valid allocation from a heap.
1612 * PARAMS
1613 * heap [I] Heap that block was allocated from
1614 * flags [I] HEAP_ flags from "winnt.h"
1615 * ptr [I] Block to check
1617 * RETURNS
1618 * Success: TRUE. The block was allocated from heap.
1619 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1621 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1623 HEAP *heapPtr = HEAP_GetPtr( heap );
1624 if (!heapPtr) return FALSE;
1625 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1629 /***********************************************************************
1630 * RtlWalkHeap (NTDLL.@)
1632 * FIXME
1633 * The PROCESS_HEAP_ENTRY flag values seem different between this
1634 * function and HeapWalk(). To be checked.
1636 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1638 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1639 HEAP *heapPtr = HEAP_GetPtr(heap);
1640 SUBHEAP *sub, *currentheap = NULL;
1641 NTSTATUS ret;
1642 char *ptr;
1643 int region_index = 0;
1645 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1647 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1649 /* set ptr to the next arena to be examined */
1651 if (!entry->lpData) /* first call (init) ? */
1653 TRACE("begin walking of heap %p.\n", heap);
1654 currentheap = &heapPtr->subheap;
1655 ptr = (char*)currentheap->base + currentheap->headerSize;
1657 else
1659 ptr = entry->lpData;
1660 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1662 if ((ptr >= (char *)sub->base) &&
1663 (ptr < (char *)sub->base + sub->size))
1665 currentheap = sub;
1666 break;
1668 region_index++;
1670 if (currentheap == NULL)
1672 ERR("no matching subheap found, shouldn't happen !\n");
1673 ret = STATUS_NO_MORE_ENTRIES;
1674 goto HW_end;
1677 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1679 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1680 ptr += pArena->size & ARENA_SIZE_MASK;
1682 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1684 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1685 ptr += pArena->size & ARENA_SIZE_MASK;
1687 else
1688 ptr += entry->cbData; /* point to next arena */
1690 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1691 { /* proceed with next subheap */
1692 struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
1693 if (!next)
1694 { /* successfully finished */
1695 TRACE("end reached.\n");
1696 ret = STATUS_NO_MORE_ENTRIES;
1697 goto HW_end;
1699 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1700 ptr = (char *)currentheap->base + currentheap->headerSize;
1704 entry->wFlags = 0;
1705 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1707 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1709 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1711 entry->lpData = pArena + 1;
1712 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1713 entry->cbOverhead = sizeof(ARENA_FREE);
1714 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1716 else
1718 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1720 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1722 entry->lpData = pArena + 1;
1723 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1724 entry->cbOverhead = sizeof(ARENA_INUSE);
1725 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1726 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1727 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1730 entry->iRegionIndex = region_index;
1732 /* first element of heap ? */
1733 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1735 entry->wFlags |= PROCESS_HEAP_REGION;
1736 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1737 entry->u.Region.dwUnCommittedSize =
1738 currentheap->size - currentheap->commitSize;
1739 entry->u.Region.lpFirstBlock = /* first valid block */
1740 (char *)currentheap->base + currentheap->headerSize;
1741 entry->u.Region.lpLastBlock = /* first invalid block */
1742 (char *)currentheap->base + currentheap->size;
1744 ret = STATUS_SUCCESS;
1745 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1747 HW_end:
1748 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1749 return ret;
1753 /***********************************************************************
1754 * RtlGetProcessHeaps (NTDLL.@)
1756 * Get the Heaps belonging to the current process.
1758 * PARAMS
1759 * count [I] size of heaps
1760 * heaps [O] Destination array for heap HANDLE's
1762 * RETURNS
1763 * Success: The number of Heaps allocated by the process.
1764 * Failure: 0.
1766 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1768 ULONG total = 1; /* main heap */
1769 struct list *ptr;
1771 RtlEnterCriticalSection( &processHeap->critSection );
1772 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1773 if (total <= count)
1775 *heaps++ = processHeap;
1776 LIST_FOR_EACH( ptr, &processHeap->entry )
1777 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1779 RtlLeaveCriticalSection( &processHeap->critSection );
1780 return total;