push 27a9569132e9fc3a545aded7efca0a004a7b7ea9
[wine/hacks.git] / dlls / ntdll / heap.c
blobc410f78a60b76a43cde5c54803a035a07cea22e5
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 "winternl.h"
39 #include "winnt.h"
40 #include "winternl.h"
41 #include "wine/list.h"
42 #include "wine/debug.h"
43 #include "wine/server.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(heap);
46 WINE_DECLARE_DEBUG_CHANNEL(heap_poison);
48 /* Note: the heap data structures are based on what Pietrek describes in his
49 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
50 * the same, but could be easily adapted if it turns out some programs
51 * require it.
54 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
55 * that there is no unaligned accesses to structure fields.
58 typedef struct tagARENA_INUSE
60 DWORD size; /* Block size; must be the first field */
61 DWORD magic : 24; /* Magic number */
62 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) */
63 } ARENA_INUSE;
65 typedef struct tagARENA_FREE
67 DWORD size; /* Block size; must be the first field */
68 DWORD magic; /* Magic number */
69 struct list entry; /* Entry in free list */
70 } ARENA_FREE;
72 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
73 #define ARENA_FLAG_PREV_FREE 0x00000002
74 #define ARENA_SIZE_MASK (~3)
75 #define ARENA_INUSE_MAGIC 0x455355 /* Value for arena 'magic' field */
76 #define ARENA_FREE_MAGIC 0x45455246 /* Value for arena 'magic' field */
78 #define ARENA_INUSE_FILLER 0x55
79 #define ARENA_FREE_FILLER 0xaa
81 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
82 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
84 #define QUIET 1 /* Suppress messages */
85 #define NOISY 0 /* Report all errors */
87 /* minimum data size (without arenas) of an allocated block */
88 /* make sure that it's larger than a free list entry */
89 #define HEAP_MIN_DATA_SIZE (2 * sizeof(struct list))
90 /* minimum size that must remain to shrink an allocated block */
91 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
93 /* Max size of the blocks on the free lists */
94 static const SIZE_T HEAP_freeListSizes[] =
96 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
98 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
100 typedef struct
102 ARENA_FREE arena;
103 } FREE_LIST_ENTRY;
105 struct tagHEAP;
107 typedef struct tagSUBHEAP
109 DWORD size; /* Size of the whole sub-heap */
110 DWORD commitSize; /* Committed size of the sub-heap */
111 DWORD headerSize; /* Size of the heap header */
112 struct tagSUBHEAP *next; /* Next sub-heap */
113 struct tagHEAP *heap; /* Main heap structure */
114 DWORD magic; /* Magic number */
115 } SUBHEAP;
117 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
119 typedef struct tagHEAP
121 SUBHEAP subheap; /* First sub-heap */
122 struct list entry; /* Entry in process heap list */
123 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
124 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
125 DWORD flags; /* Heap flags */
126 DWORD magic; /* Magic number */
127 } HEAP;
129 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
131 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
132 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
134 static HEAP *processHeap; /* main process heap */
136 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
138 /* mark a block of memory as free for debugging purposes */
139 static inline void mark_block_free( void *ptr, SIZE_T size )
141 if (TRACE_ON(heap) || TRACE_ON(heap_poison)) memset( ptr, ARENA_FREE_FILLER, size );
142 #ifdef VALGRIND_MAKE_NOACCESS
143 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
144 #endif
147 /* mark a block of memory as initialized for debugging purposes */
148 static inline void mark_block_initialized( void *ptr, SIZE_T size )
150 #ifdef VALGRIND_MAKE_READABLE
151 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
152 #endif
155 /* mark a block of memory as uninitialized for debugging purposes */
156 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
158 #ifdef VALGRIND_MAKE_WRITABLE
159 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
160 #endif
161 if (TRACE_ON(heap) || TRACE_ON(heap_poison))
163 memset( ptr, ARENA_INUSE_FILLER, size );
164 #ifdef VALGRIND_MAKE_WRITABLE
165 /* make it uninitialized to valgrind again */
166 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
167 #endif
171 /* clear contents of a block of memory */
172 static inline void clear_block( void *ptr, SIZE_T size )
174 mark_block_initialized( ptr, size );
175 memset( ptr, 0, size );
178 /* notify that a new block of memory has been allocated for debugging purposes */
179 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
181 #ifdef VALGRIND_MALLOCLIKE_BLOCK
182 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
183 #endif
186 /* notify that a block of memory has been freed for debugging purposes */
187 static inline void notify_free( void *ptr )
189 #ifdef VALGRIND_FREELIKE_BLOCK
190 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
191 #endif
194 /* locate a free list entry of the appropriate size */
195 /* size is the size of the whole block including the arena header */
196 static inline unsigned int get_freelist_index( SIZE_T size )
198 unsigned int i;
200 size -= sizeof(ARENA_FREE);
201 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
202 return i;
205 /* get the memory protection type to use for a given heap */
206 static inline ULONG get_protection_type( DWORD flags )
208 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
211 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
213 0, 0, NULL, /* will be set later */
214 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
215 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
219 /***********************************************************************
220 * HEAP_Dump
222 static void HEAP_Dump( HEAP *heap )
224 int i;
225 SUBHEAP *subheap;
226 char *ptr;
228 DPRINTF( "Heap: %p\n", heap );
229 DPRINTF( "Next: %p Sub-heaps: %p",
230 LIST_ENTRY( heap->entry.next, HEAP, entry ), &heap->subheap );
231 subheap = &heap->subheap;
232 while (subheap->next)
234 DPRINTF( " -> %p", subheap->next );
235 subheap = subheap->next;
238 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
239 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
240 DPRINTF( "%p free %08lx prev=%p next=%p\n",
241 &heap->freeList[i].arena, HEAP_freeListSizes[i],
242 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
243 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
245 subheap = &heap->subheap;
246 while (subheap)
248 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
249 DPRINTF( "\n\nSub-heap %p: size=%08x committed=%08x\n",
250 subheap, subheap->size, subheap->commitSize );
252 DPRINTF( "\n Block Stat Size Id\n" );
253 ptr = (char*)subheap + subheap->headerSize;
254 while (ptr < (char *)subheap + subheap->size)
256 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
258 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
259 DPRINTF( "%p free %08x prev=%p next=%p\n",
260 pArena, pArena->size & ARENA_SIZE_MASK,
261 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
262 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
263 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
264 arenaSize += sizeof(ARENA_FREE);
265 freeSize += pArena->size & ARENA_SIZE_MASK;
267 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
269 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
270 DPRINTF( "%p Used %08x back=%p\n",
271 pArena, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
272 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
273 arenaSize += sizeof(ARENA_INUSE);
274 usedSize += pArena->size & ARENA_SIZE_MASK;
276 else
278 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
279 DPRINTF( "%p used %08x\n", pArena, pArena->size & ARENA_SIZE_MASK );
280 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
281 arenaSize += sizeof(ARENA_INUSE);
282 usedSize += pArena->size & ARENA_SIZE_MASK;
285 DPRINTF( "\nTotal: Size=%08x Committed=%08x Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
286 subheap->size, subheap->commitSize, freeSize, usedSize,
287 arenaSize, (arenaSize * 100) / subheap->size );
288 subheap = subheap->next;
293 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
295 WORD rem_flags;
296 TRACE( "Dumping entry %p\n", entry );
297 TRACE( "lpData\t\t: %p\n", entry->lpData );
298 TRACE( "cbData\t\t: %08x\n", entry->cbData);
299 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
300 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
301 TRACE( "WFlags\t\t: ");
302 if (entry->wFlags & PROCESS_HEAP_REGION)
303 TRACE( "PROCESS_HEAP_REGION ");
304 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
305 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
306 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
307 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
308 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
309 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
310 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
311 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
312 rem_flags = entry->wFlags &
313 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
314 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
315 PROCESS_HEAP_ENTRY_DDESHARE);
316 if (rem_flags)
317 TRACE( "Unknown %08x", rem_flags);
318 TRACE( "\n");
319 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
320 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
322 /* Treat as block */
323 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
325 if (entry->wFlags & PROCESS_HEAP_REGION)
327 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
328 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
329 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
330 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
334 /***********************************************************************
335 * HEAP_GetPtr
336 * RETURNS
337 * Pointer to the heap
338 * NULL: Failure
340 static HEAP *HEAP_GetPtr(
341 HANDLE heap /* [in] Handle to the heap */
343 HEAP *heapPtr = (HEAP *)heap;
344 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
346 ERR("Invalid heap %p!\n", heap );
347 return NULL;
349 if ((TRACE_ON(heap)|| TRACE_ON(heap_poison)) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
351 HEAP_Dump( heapPtr );
352 assert( FALSE );
353 return NULL;
355 return heapPtr;
359 /***********************************************************************
360 * HEAP_InsertFreeBlock
362 * Insert a free block into the free list.
364 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
366 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
367 if (last)
369 /* insert at end of free list, i.e. before the next free list entry */
370 pEntry++;
371 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
372 list_add_before( &pEntry->arena.entry, &pArena->entry );
374 else
376 /* insert at head of free list */
377 list_add_after( &pEntry->arena.entry, &pArena->entry );
379 pArena->size |= ARENA_FLAG_FREE;
383 /***********************************************************************
384 * HEAP_FindSubHeap
385 * Find the sub-heap containing a given address.
387 * RETURNS
388 * Pointer: Success
389 * NULL: Failure
391 static SUBHEAP *HEAP_FindSubHeap(
392 const HEAP *heap, /* [in] Heap pointer */
393 LPCVOID ptr /* [in] Address */
395 const SUBHEAP *sub = &heap->subheap;
396 while (sub)
398 if (((const char *)ptr >= (const char *)sub) &&
399 ((const char *)ptr < (const char *)sub + sub->size - sizeof(ARENA_INUSE)))
400 return (SUBHEAP *)sub;
401 sub = sub->next;
403 return NULL;
407 /***********************************************************************
408 * HEAP_Commit
410 * Make sure the heap storage is committed for a given size in the specified arena.
412 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
414 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
415 SIZE_T size = (char *)ptr - (char *)subheap;
416 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
417 if (size > subheap->size) size = subheap->size;
418 if (size <= subheap->commitSize) return TRUE;
419 size -= subheap->commitSize;
420 ptr = (char *)subheap + subheap->commitSize;
421 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
422 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
424 WARN("Could not commit %08lx bytes at %p for heap %p\n",
425 size, ptr, subheap->heap );
426 return FALSE;
428 subheap->commitSize += size;
429 return TRUE;
433 /***********************************************************************
434 * HEAP_Decommit
436 * If possible, decommit the heap storage from (including) 'ptr'.
438 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
440 void *addr;
441 SIZE_T decommit_size;
442 SIZE_T size = (char *)ptr - (char *)subheap;
444 /* round to next block and add one full block */
445 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
446 if (size >= subheap->commitSize) return TRUE;
447 decommit_size = subheap->commitSize - size;
448 addr = (char *)subheap + size;
450 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
452 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
453 decommit_size, (char *)subheap + size, subheap->heap );
454 return FALSE;
456 subheap->commitSize -= decommit_size;
457 return TRUE;
461 /***********************************************************************
462 * HEAP_CreateFreeBlock
464 * Create a free block at a specified address. 'size' is the size of the
465 * whole block, including the new arena.
467 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
469 ARENA_FREE *pFree;
470 char *pEnd;
471 BOOL last;
473 /* Create a free arena */
474 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
475 pFree = (ARENA_FREE *)ptr;
476 pFree->magic = ARENA_FREE_MAGIC;
478 /* If debugging, erase the freed block content */
480 pEnd = (char *)ptr + size;
481 if (pEnd > (char *)subheap + subheap->commitSize) pEnd = (char *)subheap + subheap->commitSize;
482 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
484 /* Check if next block is free also */
486 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
487 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
489 /* Remove the next arena from the free list */
490 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
491 list_remove( &pNext->entry );
492 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
493 mark_block_free( pNext, sizeof(ARENA_FREE) );
496 /* Set the next block PREV_FREE flag and pointer */
498 last = ((char *)ptr + size >= (char *)subheap + subheap->size);
499 if (!last)
501 DWORD *pNext = (DWORD *)((char *)ptr + size);
502 *pNext |= ARENA_FLAG_PREV_FREE;
503 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
504 *((ARENA_FREE **)pNext - 1) = pFree;
507 /* Last, insert the new block into the free list */
509 pFree->size = size - sizeof(*pFree);
510 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
514 /***********************************************************************
515 * HEAP_MakeInUseBlockFree
517 * Turn an in-use block into a free block. Can also decommit the end of
518 * the heap, and possibly even free the sub-heap altogether.
520 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
522 ARENA_FREE *pFree;
523 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
525 /* Check if we can merge with previous block */
527 if (pArena->size & ARENA_FLAG_PREV_FREE)
529 pFree = *((ARENA_FREE **)pArena - 1);
530 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
531 /* Remove it from the free list */
532 list_remove( &pFree->entry );
534 else pFree = (ARENA_FREE *)pArena;
536 /* Create a free block */
538 HEAP_CreateFreeBlock( subheap, pFree, size );
539 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
540 if ((char *)pFree + size < (char *)subheap + subheap->size)
541 return; /* Not the last block, so nothing more to do */
543 /* Free the whole sub-heap if it's empty and not the original one */
545 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
546 (subheap != &subheap->heap->subheap))
548 SIZE_T size = 0;
549 SUBHEAP *pPrev = &subheap->heap->subheap;
550 /* Remove the free block from the list */
551 list_remove( &pFree->entry );
552 /* Remove the subheap from the list */
553 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
554 if (pPrev) pPrev->next = subheap->next;
555 /* Free the memory */
556 subheap->magic = 0;
557 NtFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap, &size, MEM_RELEASE );
558 return;
561 /* Decommit the end of the heap */
563 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
567 /***********************************************************************
568 * HEAP_ShrinkBlock
570 * Shrink an in-use block.
572 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
574 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
576 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
577 (pArena->size & ARENA_SIZE_MASK) - size );
578 /* assign size plus previous arena flags */
579 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
581 else
583 /* Turn off PREV_FREE flag in next block */
584 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
585 if (pNext < (char *)subheap + subheap->size)
586 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
590 /***********************************************************************
591 * HEAP_InitSubHeap
593 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
594 SIZE_T commitSize, SIZE_T totalSize )
596 SUBHEAP *subheap;
597 FREE_LIST_ENTRY *pEntry;
598 int i;
600 /* Commit memory */
602 if (flags & HEAP_SHARED)
603 commitSize = totalSize; /* always commit everything in a shared heap */
604 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
605 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
607 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
608 return FALSE;
611 /* Fill the sub-heap structure */
613 subheap = (SUBHEAP *)address;
614 subheap->heap = heap;
615 subheap->size = totalSize;
616 subheap->commitSize = commitSize;
617 subheap->magic = SUBHEAP_MAGIC;
619 if ( subheap != (SUBHEAP *)heap )
621 /* If this is a secondary subheap, insert it into list */
623 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
624 subheap->next = heap->subheap.next;
625 heap->subheap.next = subheap;
627 else
629 /* If this is a primary subheap, initialize main heap */
631 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
632 subheap->next = NULL;
633 heap->flags = flags;
634 heap->magic = HEAP_MAGIC;
636 /* Build the free lists */
638 list_init( &heap->freeList[0].arena.entry );
639 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
641 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
642 pEntry->arena.magic = ARENA_FREE_MAGIC;
643 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
646 /* Initialize critical section */
648 if (!processHeap) /* do it by hand to avoid memory allocations */
650 if(TRACE_ON(heap_poison))
651 TRACE_(heap_poison)("poisioning heap\n");
652 heap->critSection.DebugInfo = &process_heap_critsect_debug;
653 heap->critSection.LockCount = -1;
654 heap->critSection.RecursionCount = 0;
655 heap->critSection.OwningThread = 0;
656 heap->critSection.LockSemaphore = 0;
657 heap->critSection.SpinCount = 0;
658 process_heap_critsect_debug.CriticalSection = &heap->critSection;
660 else
662 RtlInitializeCriticalSection( &heap->critSection );
663 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
666 if (flags & HEAP_SHARED)
668 /* let's assume that only one thread at a time will try to do this */
669 HANDLE sem = heap->critSection.LockSemaphore;
670 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
672 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
673 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
674 heap->critSection.LockSemaphore = sem;
675 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
676 heap->critSection.DebugInfo = NULL;
680 /* Create the first free block */
682 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
683 subheap->size - subheap->headerSize );
685 return TRUE;
688 /***********************************************************************
689 * HEAP_CreateSubHeap
691 * Create a sub-heap of the given size.
692 * If heap == NULL, creates a main heap.
694 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
695 SIZE_T commitSize, SIZE_T totalSize )
697 LPVOID address = base;
699 /* round-up sizes on a 64K boundary */
700 totalSize = (totalSize + 0xffff) & 0xffff0000;
701 commitSize = (commitSize + 0xffff) & 0xffff0000;
702 if (!commitSize) commitSize = 0x10000;
703 if (totalSize < commitSize) totalSize = commitSize;
705 if (!address)
707 /* allocate the memory block */
708 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
709 MEM_RESERVE, get_protection_type( flags ) ))
711 WARN("Could not allocate %08lx bytes\n", totalSize );
712 return NULL;
716 /* Initialize subheap */
718 if (!HEAP_InitSubHeap( heap ? heap : (HEAP *)address,
719 address, flags, commitSize, totalSize ))
721 SIZE_T size = 0;
722 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
723 return NULL;
726 return (SUBHEAP *)address;
730 /***********************************************************************
731 * HEAP_FindFreeBlock
733 * Find a free block at least as large as the requested size, and make sure
734 * the requested size is committed.
736 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
737 SUBHEAP **ppSubHeap )
739 SUBHEAP *subheap;
740 struct list *ptr;
741 SIZE_T total_size;
742 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
744 /* Find a suitable free list, and in it find a block large enough */
746 ptr = &pEntry->arena.entry;
747 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
749 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
750 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
751 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
752 if (arena_size >= size)
754 subheap = HEAP_FindSubHeap( heap, pArena );
755 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
756 *ppSubHeap = subheap;
757 return pArena;
761 /* If no block was found, attempt to grow the heap */
763 if (!(heap->flags & HEAP_GROWABLE))
765 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
766 return NULL;
768 /* make sure that we have a big enough size *committed* to fit another
769 * last free arena in !
770 * So just one heap struct, one first free arena which will eventually
771 * get used, and a second free arena that might get assigned all remaining
772 * free space in HEAP_ShrinkBlock() */
773 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
774 if (total_size < size) return NULL; /* overflow */
776 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
777 max( HEAP_DEF_SIZE, total_size ) )))
778 return NULL;
780 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
781 subheap, total_size, heap );
783 *ppSubHeap = subheap;
784 return (ARENA_FREE *)(subheap + 1);
788 /***********************************************************************
789 * HEAP_IsValidArenaPtr
791 * Check that the pointer is inside the range possible for arenas.
793 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
795 int i;
796 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
797 if (!subheap) return FALSE;
798 if ((const char *)ptr >= (const char *)subheap + subheap->headerSize) return TRUE;
799 if (subheap != &heap->subheap) return FALSE;
800 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
801 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
802 return FALSE;
806 /***********************************************************************
807 * HEAP_ValidateFreeArena
809 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
811 ARENA_FREE *prev, *next;
812 char *heapEnd = (char *)subheap + subheap->size;
814 /* Check for unaligned pointers */
815 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
817 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
818 return FALSE;
821 /* Check magic number */
822 if (pArena->magic != ARENA_FREE_MAGIC)
824 ERR("Heap %p: invalid free arena magic for %p\n", subheap->heap, pArena );
825 return FALSE;
827 /* Check size flags */
828 if (!(pArena->size & ARENA_FLAG_FREE) ||
829 (pArena->size & ARENA_FLAG_PREV_FREE))
831 ERR("Heap %p: bad flags %08x for free arena %p\n",
832 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
833 return FALSE;
835 /* Check arena size */
836 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
838 ERR("Heap %p: bad size %08x for free arena %p\n",
839 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
840 return FALSE;
842 /* Check that next pointer is valid */
843 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
844 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
846 ERR("Heap %p: bad next ptr %p for arena %p\n",
847 subheap->heap, next, pArena );
848 return FALSE;
850 /* Check that next arena is free */
851 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
853 ERR("Heap %p: next arena %p invalid for %p\n",
854 subheap->heap, next, pArena );
855 return FALSE;
857 /* Check that prev pointer is valid */
858 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
859 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
861 ERR("Heap %p: bad prev ptr %p for arena %p\n",
862 subheap->heap, prev, pArena );
863 return FALSE;
865 /* Check that prev arena is free */
866 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
868 /* this often means that the prev arena got overwritten
869 * by a memory write before that prev arena */
870 ERR("Heap %p: prev arena %p invalid for %p\n",
871 subheap->heap, prev, pArena );
872 return FALSE;
874 /* Check that next block has PREV_FREE flag */
875 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
877 if (!(*(DWORD *)((char *)(pArena + 1) +
878 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
880 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
881 subheap->heap, pArena );
882 return FALSE;
884 /* Check next block back pointer */
885 if (*((ARENA_FREE **)((char *)(pArena + 1) +
886 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
888 ERR("Heap %p: arena %p has wrong back ptr %p\n",
889 subheap->heap, pArena,
890 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
891 return FALSE;
894 return TRUE;
898 /***********************************************************************
899 * HEAP_ValidateInUseArena
901 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
903 const char *heapEnd = (const char *)subheap + subheap->size;
905 /* Check for unaligned pointers */
906 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
908 if ( quiet == NOISY )
910 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
911 if ( TRACE_ON(heap) )
912 HEAP_Dump( subheap->heap );
914 else if ( WARN_ON(heap) )
916 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
917 if ( TRACE_ON(heap) )
918 HEAP_Dump( subheap->heap );
920 return FALSE;
923 /* Check magic number */
924 if (pArena->magic != ARENA_INUSE_MAGIC)
926 if (quiet == NOISY) {
927 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
928 if (TRACE_ON(heap))
929 HEAP_Dump( subheap->heap );
930 } else if (WARN_ON(heap)) {
931 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
932 if (TRACE_ON(heap))
933 HEAP_Dump( subheap->heap );
935 return FALSE;
937 /* Check size flags */
938 if (pArena->size & ARENA_FLAG_FREE)
940 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
941 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
942 return FALSE;
944 /* Check arena size */
945 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
947 ERR("Heap %p: bad size %08x for in-use arena %p\n",
948 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
949 return FALSE;
951 /* Check next arena PREV_FREE flag */
952 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
953 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
955 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
956 subheap->heap, pArena );
957 return FALSE;
959 /* Check prev free arena */
960 if (pArena->size & ARENA_FLAG_PREV_FREE)
962 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
963 /* Check prev pointer */
964 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
966 ERR("Heap %p: bad back ptr %p for arena %p\n",
967 subheap->heap, pPrev, pArena );
968 return FALSE;
970 /* Check that prev arena is free */
971 if (!(pPrev->size & ARENA_FLAG_FREE) ||
972 (pPrev->magic != ARENA_FREE_MAGIC))
974 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
975 subheap->heap, pPrev, pArena );
976 return FALSE;
978 /* Check that prev arena is really the previous block */
979 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
981 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
982 subheap->heap, pPrev, pArena );
983 return FALSE;
986 return TRUE;
990 /***********************************************************************
991 * HEAP_IsRealArena [Internal]
992 * Validates a block is a valid arena.
994 * RETURNS
995 * TRUE: Success
996 * FALSE: Failure
998 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
999 DWORD flags, /* [in] Bit flags that control access during operation */
1000 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1001 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1002 * does not complain */
1004 SUBHEAP *subheap;
1005 BOOL ret = TRUE;
1007 flags &= HEAP_NO_SERIALIZE;
1008 flags |= heapPtr->flags;
1009 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1010 if (!(flags & HEAP_NO_SERIALIZE))
1011 RtlEnterCriticalSection( &heapPtr->critSection );
1013 if (block) /* only check this single memory block */
1015 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1017 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1018 ((const char *)arena < (char *)subheap + subheap->headerSize))
1020 if (quiet == NOISY)
1021 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1022 else if (WARN_ON(heap))
1023 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1024 ret = FALSE;
1025 } else
1026 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1028 if (!(flags & HEAP_NO_SERIALIZE))
1029 RtlLeaveCriticalSection( &heapPtr->critSection );
1030 return ret;
1033 subheap = &heapPtr->subheap;
1034 while (subheap && ret)
1036 char *ptr = (char *)subheap + subheap->headerSize;
1037 while (ptr < (char *)subheap + subheap->size)
1039 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1041 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1042 ret = FALSE;
1043 break;
1045 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1047 else
1049 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1050 ret = FALSE;
1051 break;
1053 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1056 subheap = subheap->next;
1059 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1060 return ret;
1064 /***********************************************************************
1065 * RtlCreateHeap (NTDLL.@)
1067 * Create a new Heap.
1069 * PARAMS
1070 * flags [I] HEAP_ flags from "winnt.h"
1071 * addr [I] Desired base address
1072 * totalSize [I] Total size of the heap, or 0 for a growable heap
1073 * commitSize [I] Amount of heap space to commit
1074 * unknown [I] Not yet understood
1075 * definition [I] Heap definition
1077 * RETURNS
1078 * Success: A HANDLE to the newly created heap.
1079 * Failure: a NULL HANDLE.
1081 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1082 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1084 SUBHEAP *subheap;
1086 /* Allocate the heap block */
1088 if (!totalSize)
1090 totalSize = HEAP_DEF_SIZE;
1091 flags |= HEAP_GROWABLE;
1094 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1096 /* link it into the per-process heap list */
1097 if (processHeap)
1099 HEAP *heapPtr = subheap->heap;
1100 RtlEnterCriticalSection( &processHeap->critSection );
1101 list_add_head( &processHeap->entry, &heapPtr->entry );
1102 RtlLeaveCriticalSection( &processHeap->critSection );
1104 else
1106 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1107 list_init( &processHeap->entry );
1110 return (HANDLE)subheap;
1114 /***********************************************************************
1115 * RtlDestroyHeap (NTDLL.@)
1117 * Destroy a Heap created with RtlCreateHeap().
1119 * PARAMS
1120 * heap [I] Heap to destroy.
1122 * RETURNS
1123 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1124 * Failure: The Heap handle, if heap is the process heap.
1126 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1128 HEAP *heapPtr = HEAP_GetPtr( heap );
1129 SUBHEAP *subheap;
1131 TRACE("%p\n", heap );
1132 if (!heapPtr) return heap;
1134 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1136 /* remove it from the per-process list */
1137 RtlEnterCriticalSection( &processHeap->critSection );
1138 list_remove( &heapPtr->entry );
1139 RtlLeaveCriticalSection( &processHeap->critSection );
1141 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1142 RtlDeleteCriticalSection( &heapPtr->critSection );
1143 subheap = &heapPtr->subheap;
1144 while (subheap)
1146 SUBHEAP *next = subheap->next;
1147 SIZE_T size = 0;
1148 void *addr = subheap;
1149 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1150 subheap = next;
1152 return 0;
1156 /***********************************************************************
1157 * RtlAllocateHeap (NTDLL.@)
1159 * Allocate a memory block from a Heap.
1161 * PARAMS
1162 * heap [I] Heap to allocate block from
1163 * flags [I] HEAP_ flags from "winnt.h"
1164 * size [I] Size of the memory block to allocate
1166 * RETURNS
1167 * Success: A pointer to the newly allocated block
1168 * Failure: NULL.
1170 * NOTES
1171 * This call does not SetLastError().
1173 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1175 ARENA_FREE *pArena;
1176 ARENA_INUSE *pInUse;
1177 SUBHEAP *subheap;
1178 HEAP *heapPtr = HEAP_GetPtr( heap );
1179 SIZE_T rounded_size;
1181 /* Validate the parameters */
1183 if (!heapPtr) return NULL;
1184 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1185 flags |= heapPtr->flags;
1186 rounded_size = ROUND_SIZE(size);
1187 if (rounded_size < size) /* overflow */
1189 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1190 return NULL;
1192 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1194 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1195 /* Locate a suitable free block */
1197 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1199 TRACE("(%p,%08x,%08lx): returning NULL\n",
1200 heap, flags, size );
1201 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1202 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1203 return NULL;
1206 /* Remove the arena from the free list */
1208 list_remove( &pArena->entry );
1210 /* Build the in-use arena */
1212 pInUse = (ARENA_INUSE *)pArena;
1214 /* in-use arena is smaller than free arena,
1215 * so we have to add the difference to the size */
1216 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1217 pInUse->magic = ARENA_INUSE_MAGIC;
1219 /* Shrink the block */
1221 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1222 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1224 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1226 if (flags & HEAP_ZERO_MEMORY)
1227 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1228 else
1229 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1231 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1233 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1234 return (LPVOID)(pInUse + 1);
1238 /***********************************************************************
1239 * RtlFreeHeap (NTDLL.@)
1241 * Free a memory block allocated with RtlAllocateHeap().
1243 * PARAMS
1244 * heap [I] Heap that block was allocated from
1245 * flags [I] HEAP_ flags from "winnt.h"
1246 * ptr [I] Block to free
1248 * RETURNS
1249 * Success: TRUE, if ptr is NULL or was freed successfully.
1250 * Failure: FALSE.
1252 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1254 ARENA_INUSE *pInUse;
1255 SUBHEAP *subheap;
1256 HEAP *heapPtr;
1258 /* Validate the parameters */
1260 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1262 heapPtr = HEAP_GetPtr( heap );
1263 if (!heapPtr)
1265 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1266 return FALSE;
1269 flags &= HEAP_NO_SERIALIZE;
1270 flags |= heapPtr->flags;
1271 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1273 /* Some sanity checks */
1275 pInUse = (ARENA_INUSE *)ptr - 1;
1276 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse ))) goto error;
1277 if ((char *)pInUse < (char *)subheap + subheap->headerSize) goto error;
1278 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1280 /* Turn the block into a free block */
1282 notify_free( ptr );
1284 HEAP_MakeInUseBlockFree( subheap, pInUse );
1286 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1288 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1289 return TRUE;
1291 error:
1292 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1293 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1294 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1295 return FALSE;
1299 /***********************************************************************
1300 * RtlReAllocateHeap (NTDLL.@)
1302 * Change the size of a memory block allocated with RtlAllocateHeap().
1304 * PARAMS
1305 * heap [I] Heap that block was allocated from
1306 * flags [I] HEAP_ flags from "winnt.h"
1307 * ptr [I] Block to resize
1308 * size [I] Size of the memory block to allocate
1310 * RETURNS
1311 * Success: A pointer to the resized block (which may be different).
1312 * Failure: NULL.
1314 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1316 ARENA_INUSE *pArena;
1317 HEAP *heapPtr;
1318 SUBHEAP *subheap;
1319 SIZE_T oldSize, rounded_size;
1321 if (!ptr) return NULL;
1322 if (!(heapPtr = HEAP_GetPtr( heap )))
1324 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1325 return NULL;
1328 /* Validate the parameters */
1330 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1331 HEAP_REALLOC_IN_PLACE_ONLY;
1332 flags |= heapPtr->flags;
1333 rounded_size = ROUND_SIZE(size);
1334 if (rounded_size < size) /* overflow */
1336 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1337 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1338 return NULL;
1340 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1342 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1344 pArena = (ARENA_INUSE *)ptr - 1;
1345 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena ))) goto error;
1346 if ((char *)pArena < (char *)subheap + subheap->headerSize) goto error;
1347 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1349 /* Check if we need to grow the block */
1351 oldSize = (pArena->size & ARENA_SIZE_MASK);
1352 if (rounded_size > oldSize)
1354 char *pNext = (char *)(pArena + 1) + oldSize;
1355 if ((pNext < (char *)subheap + subheap->size) &&
1356 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1357 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1359 /* The next block is free and large enough */
1360 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1361 list_remove( &pFree->entry );
1362 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1363 if (!HEAP_Commit( subheap, pArena, rounded_size ))
1365 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1366 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1367 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1368 return NULL;
1370 notify_free( pArena + 1 );
1371 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1372 notify_alloc( pArena + 1, size, FALSE );
1373 /* FIXME: this is wrong as we may lose old VBits settings */
1374 mark_block_initialized( pArena + 1, oldSize );
1376 else /* Do it the hard way */
1378 ARENA_FREE *pNew;
1379 ARENA_INUSE *pInUse;
1380 SUBHEAP *newsubheap;
1382 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1383 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1385 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1386 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1387 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1388 return NULL;
1391 /* Build the in-use arena */
1393 list_remove( &pNew->entry );
1394 pInUse = (ARENA_INUSE *)pNew;
1395 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1396 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1397 pInUse->magic = ARENA_INUSE_MAGIC;
1398 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1399 mark_block_initialized( pInUse + 1, oldSize );
1400 notify_alloc( pInUse + 1, size, FALSE );
1401 memcpy( pInUse + 1, pArena + 1, oldSize );
1403 /* Free the previous block */
1405 notify_free( pArena + 1 );
1406 HEAP_MakeInUseBlockFree( subheap, pArena );
1407 subheap = newsubheap;
1408 pArena = pInUse;
1411 else
1413 /* Shrink the block */
1414 notify_free( pArena + 1 );
1415 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1416 notify_alloc( pArena + 1, size, FALSE );
1417 /* FIXME: this is wrong as we may lose old VBits settings */
1418 mark_block_initialized( pArena + 1, size );
1421 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1423 /* Clear the extra bytes if needed */
1425 if (rounded_size > oldSize)
1427 if (flags & HEAP_ZERO_MEMORY)
1428 clear_block( (char *)(pArena + 1) + oldSize,
1429 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1430 else
1431 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1432 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1435 /* Return the new arena */
1437 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1439 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1440 return (LPVOID)(pArena + 1);
1442 error:
1443 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1444 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1445 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1446 return NULL;
1450 /***********************************************************************
1451 * RtlCompactHeap (NTDLL.@)
1453 * Compact the free space in a Heap.
1455 * PARAMS
1456 * heap [I] Heap that block was allocated from
1457 * flags [I] HEAP_ flags from "winnt.h"
1459 * RETURNS
1460 * The number of bytes compacted.
1462 * NOTES
1463 * This function is a harmless stub.
1465 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1467 FIXME( "stub\n" );
1468 return 0;
1472 /***********************************************************************
1473 * RtlLockHeap (NTDLL.@)
1475 * Lock a Heap.
1477 * PARAMS
1478 * heap [I] Heap to lock
1480 * RETURNS
1481 * Success: TRUE. The Heap is locked.
1482 * Failure: FALSE, if heap is invalid.
1484 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1486 HEAP *heapPtr = HEAP_GetPtr( heap );
1487 if (!heapPtr) return FALSE;
1488 RtlEnterCriticalSection( &heapPtr->critSection );
1489 return TRUE;
1493 /***********************************************************************
1494 * RtlUnlockHeap (NTDLL.@)
1496 * Unlock a Heap.
1498 * PARAMS
1499 * heap [I] Heap to unlock
1501 * RETURNS
1502 * Success: TRUE. The Heap is unlocked.
1503 * Failure: FALSE, if heap is invalid.
1505 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1507 HEAP *heapPtr = HEAP_GetPtr( heap );
1508 if (!heapPtr) return FALSE;
1509 RtlLeaveCriticalSection( &heapPtr->critSection );
1510 return TRUE;
1514 /***********************************************************************
1515 * RtlSizeHeap (NTDLL.@)
1517 * Get the actual size of a memory block allocated from a Heap.
1519 * PARAMS
1520 * heap [I] Heap that block was allocated from
1521 * flags [I] HEAP_ flags from "winnt.h"
1522 * ptr [I] Block to get the size of
1524 * RETURNS
1525 * Success: The size of the block.
1526 * Failure: -1, heap or ptr are invalid.
1528 * NOTES
1529 * The size may be bigger than what was passed to RtlAllocateHeap().
1531 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1533 SIZE_T ret;
1534 HEAP *heapPtr = HEAP_GetPtr( heap );
1536 if (!heapPtr)
1538 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1539 return ~0UL;
1541 flags &= HEAP_NO_SERIALIZE;
1542 flags |= heapPtr->flags;
1543 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1544 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1546 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1547 ret = ~0UL;
1549 else
1551 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1552 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1554 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1556 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1557 return ret;
1561 /***********************************************************************
1562 * RtlValidateHeap (NTDLL.@)
1564 * Determine if a block is a valid allocation from a heap.
1566 * PARAMS
1567 * heap [I] Heap that block was allocated from
1568 * flags [I] HEAP_ flags from "winnt.h"
1569 * ptr [I] Block to check
1571 * RETURNS
1572 * Success: TRUE. The block was allocated from heap.
1573 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1575 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1577 HEAP *heapPtr = HEAP_GetPtr( heap );
1578 if (!heapPtr) return FALSE;
1579 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1583 /***********************************************************************
1584 * RtlWalkHeap (NTDLL.@)
1586 * FIXME
1587 * The PROCESS_HEAP_ENTRY flag values seem different between this
1588 * function and HeapWalk(). To be checked.
1590 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1592 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1593 HEAP *heapPtr = HEAP_GetPtr(heap);
1594 SUBHEAP *sub, *currentheap = NULL;
1595 NTSTATUS ret;
1596 char *ptr;
1597 int region_index = 0;
1599 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1601 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1603 /* set ptr to the next arena to be examined */
1605 if (!entry->lpData) /* first call (init) ? */
1607 TRACE("begin walking of heap %p.\n", heap);
1608 currentheap = &heapPtr->subheap;
1609 ptr = (char*)currentheap + currentheap->headerSize;
1611 else
1613 ptr = entry->lpData;
1614 sub = &heapPtr->subheap;
1615 while (sub)
1617 if (((char *)ptr >= (char *)sub) &&
1618 ((char *)ptr < (char *)sub + sub->size))
1620 currentheap = sub;
1621 break;
1623 sub = sub->next;
1624 region_index++;
1626 if (currentheap == NULL)
1628 ERR("no matching subheap found, shouldn't happen !\n");
1629 ret = STATUS_NO_MORE_ENTRIES;
1630 goto HW_end;
1633 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1635 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1636 ptr += pArena->size & ARENA_SIZE_MASK;
1638 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1640 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1641 ptr += pArena->size & ARENA_SIZE_MASK;
1643 else
1644 ptr += entry->cbData; /* point to next arena */
1646 if (ptr > (char *)currentheap + currentheap->size - 1)
1647 { /* proceed with next subheap */
1648 if (!(currentheap = currentheap->next))
1649 { /* successfully finished */
1650 TRACE("end reached.\n");
1651 ret = STATUS_NO_MORE_ENTRIES;
1652 goto HW_end;
1654 ptr = (char*)currentheap + currentheap->headerSize;
1658 entry->wFlags = 0;
1659 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1661 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1663 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1665 entry->lpData = pArena + 1;
1666 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1667 entry->cbOverhead = sizeof(ARENA_FREE);
1668 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1670 else
1672 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1674 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1676 entry->lpData = pArena + 1;
1677 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1678 entry->cbOverhead = sizeof(ARENA_INUSE);
1679 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1680 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1681 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1684 entry->iRegionIndex = region_index;
1686 /* first element of heap ? */
1687 if (ptr == (char *)(currentheap + currentheap->headerSize))
1689 entry->wFlags |= PROCESS_HEAP_REGION;
1690 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1691 entry->u.Region.dwUnCommittedSize =
1692 currentheap->size - currentheap->commitSize;
1693 entry->u.Region.lpFirstBlock = /* first valid block */
1694 currentheap + currentheap->headerSize;
1695 entry->u.Region.lpLastBlock = /* first invalid block */
1696 currentheap + currentheap->size;
1698 ret = STATUS_SUCCESS;
1699 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1701 HW_end:
1702 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1703 return ret;
1707 /***********************************************************************
1708 * RtlGetProcessHeaps (NTDLL.@)
1710 * Get the Heaps belonging to the current process.
1712 * PARAMS
1713 * count [I] size of heaps
1714 * heaps [O] Destination array for heap HANDLE's
1716 * RETURNS
1717 * Success: The number of Heaps allocated by the process.
1718 * Failure: 0.
1720 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1722 ULONG total = 1; /* main heap */
1723 struct list *ptr;
1725 RtlEnterCriticalSection( &processHeap->critSection );
1726 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1727 if (total <= count)
1729 *heaps++ = processHeap;
1730 LIST_FOR_EACH( ptr, &processHeap->entry )
1731 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1733 RtlLeaveCriticalSection( &processHeap->critSection );
1734 return total;