push 0b5f656d0c5c34ddfb204e40e069e78078c58084
[wine/hacks.git] / dlls / ntdll / heap.c
blobfcb378adfb65b7b434a587486d731fc836e4a946
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 *ptr )
199 #ifdef VALGRIND_FREELIKE_BLOCK
200 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
201 #endif
204 /* locate a free list entry of the appropriate size */
205 /* size is the size of the whole block including the arena header */
206 static inline unsigned int get_freelist_index( SIZE_T size )
208 unsigned int i;
210 size -= sizeof(ARENA_FREE);
211 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
212 return i;
215 /* get the memory protection type to use for a given heap */
216 static inline ULONG get_protection_type( DWORD flags )
218 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
221 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
223 0, 0, NULL, /* will be set later */
224 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
225 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
229 /***********************************************************************
230 * HEAP_Dump
232 static void HEAP_Dump( HEAP *heap )
234 int i;
235 SUBHEAP *subheap;
236 char *ptr;
238 DPRINTF( "Heap: %p\n", heap );
239 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
240 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
242 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
243 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
244 DPRINTF( "%p free %08lx prev=%p next=%p\n",
245 &heap->freeList[i].arena, HEAP_freeListSizes[i],
246 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
247 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
249 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
251 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
252 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
253 subheap, subheap->base, subheap->size, subheap->commitSize );
255 DPRINTF( "\n Block Arena Stat Size Id\n" );
256 ptr = (char *)subheap->base + subheap->headerSize;
257 while (ptr < (char *)subheap->base + subheap->size)
259 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
261 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
262 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
263 pArena, pArena->magic,
264 pArena->size & ARENA_SIZE_MASK,
265 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
266 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
267 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
268 arenaSize += sizeof(ARENA_FREE);
269 freeSize += pArena->size & ARENA_SIZE_MASK;
271 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
273 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
274 DPRINTF( "%p %08x Used %08x back=%p\n",
275 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
276 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
277 arenaSize += sizeof(ARENA_INUSE);
278 usedSize += pArena->size & ARENA_SIZE_MASK;
280 else
282 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
283 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
284 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
285 arenaSize += sizeof(ARENA_INUSE);
286 usedSize += pArena->size & ARENA_SIZE_MASK;
289 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
290 subheap->size, subheap->commitSize, freeSize, usedSize,
291 arenaSize, (arenaSize * 100) / subheap->size );
296 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
298 WORD rem_flags;
299 TRACE( "Dumping entry %p\n", entry );
300 TRACE( "lpData\t\t: %p\n", entry->lpData );
301 TRACE( "cbData\t\t: %08x\n", entry->cbData);
302 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
303 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
304 TRACE( "WFlags\t\t: ");
305 if (entry->wFlags & PROCESS_HEAP_REGION)
306 TRACE( "PROCESS_HEAP_REGION ");
307 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
308 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
309 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
310 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
311 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
312 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
313 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
314 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
315 rem_flags = entry->wFlags &
316 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
317 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
318 PROCESS_HEAP_ENTRY_DDESHARE);
319 if (rem_flags)
320 TRACE( "Unknown %08x", rem_flags);
321 TRACE( "\n");
322 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
323 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
325 /* Treat as block */
326 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
328 if (entry->wFlags & PROCESS_HEAP_REGION)
330 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
331 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
332 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
333 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
337 /***********************************************************************
338 * HEAP_GetPtr
339 * RETURNS
340 * Pointer to the heap
341 * NULL: Failure
343 static HEAP *HEAP_GetPtr(
344 HANDLE heap /* [in] Handle to the heap */
346 HEAP *heapPtr = (HEAP *)heap;
347 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
349 ERR("Invalid heap %p!\n", heap );
350 return NULL;
352 if ((TRACE_ON(heap)|| TRACE_ON(heap_poison)) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
354 HEAP_Dump( heapPtr );
355 assert( FALSE );
356 return NULL;
358 return heapPtr;
362 /***********************************************************************
363 * HEAP_InsertFreeBlock
365 * Insert a free block into the free list.
367 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
369 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
370 if (last)
372 /* insert at end of free list, i.e. before the next free list entry */
373 pEntry++;
374 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
375 list_add_before( &pEntry->arena.entry, &pArena->entry );
377 else
379 /* insert at head of free list */
380 list_add_after( &pEntry->arena.entry, &pArena->entry );
382 pArena->size |= ARENA_FLAG_FREE;
386 /***********************************************************************
387 * HEAP_FindSubHeap
388 * Find the sub-heap containing a given address.
390 * RETURNS
391 * Pointer: Success
392 * NULL: Failure
394 static SUBHEAP *HEAP_FindSubHeap(
395 const HEAP *heap, /* [in] Heap pointer */
396 LPCVOID ptr ) /* [in] Address */
398 SUBHEAP *sub;
399 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
400 if (((const char *)ptr >= (const char *)sub->base) &&
401 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
402 return sub;
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->base;
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->base + 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->base;
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->base + 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->base + 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->base + subheap->commitSize)
482 pEnd = (char *)subheap->base + subheap->commitSize;
483 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
485 /* Check if next block is free also */
487 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
488 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
490 /* Remove the next arena from the free list */
491 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
492 list_remove( &pNext->entry );
493 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
494 mark_block_free( pNext, sizeof(ARENA_FREE) );
497 /* Set the next block PREV_FREE flag and pointer */
499 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
500 if (!last)
502 DWORD *pNext = (DWORD *)((char *)ptr + size);
503 *pNext |= ARENA_FLAG_PREV_FREE;
504 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
505 *((ARENA_FREE **)pNext - 1) = pFree;
508 /* Last, insert the new block into the free list */
510 pFree->size = size - sizeof(*pFree);
511 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
515 /***********************************************************************
516 * HEAP_MakeInUseBlockFree
518 * Turn an in-use block into a free block. Can also decommit the end of
519 * the heap, and possibly even free the sub-heap altogether.
521 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
523 ARENA_FREE *pFree;
524 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
526 /* Check if we can merge with previous block */
528 if (pArena->size & ARENA_FLAG_PREV_FREE)
530 pFree = *((ARENA_FREE **)pArena - 1);
531 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
532 /* Remove it from the free list */
533 list_remove( &pFree->entry );
535 else pFree = (ARENA_FREE *)pArena;
537 /* Create a free block */
539 HEAP_CreateFreeBlock( subheap, pFree, size );
540 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
541 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
542 return; /* Not the last block, so nothing more to do */
544 /* Free the whole sub-heap if it's empty and not the original one */
546 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
547 (subheap != &subheap->heap->subheap))
549 SIZE_T size = 0;
550 void *addr = subheap->base;
551 /* Remove the free block from the list */
552 list_remove( &pFree->entry );
553 /* Remove the subheap from the list */
554 list_remove( &subheap->entry );
555 /* Free the memory */
556 subheap->magic = 0;
557 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &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->base + subheap->size)
586 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
590 /***********************************************************************
591 * HEAP_InitSubHeap
593 static SUBHEAP *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 NULL;
611 if (heap)
613 /* If this is a secondary subheap, insert it into list */
615 subheap = (SUBHEAP *)address;
616 subheap->base = address;
617 subheap->heap = heap;
618 subheap->size = totalSize;
619 subheap->commitSize = commitSize;
620 subheap->magic = SUBHEAP_MAGIC;
621 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
622 list_add_head( &heap->subheap_list, &subheap->entry );
624 else
626 /* If this is a primary subheap, initialize main heap */
628 heap = (HEAP *)address;
629 heap->flags = flags;
630 heap->magic = HEAP_MAGIC;
631 list_init( &heap->subheap_list );
633 subheap = &heap->subheap;
634 subheap->base = address;
635 subheap->heap = heap;
636 subheap->size = totalSize;
637 subheap->commitSize = commitSize;
638 subheap->magic = SUBHEAP_MAGIC;
639 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
640 list_add_head( &heap->subheap_list, &subheap->entry );
642 /* Build the free lists */
644 list_init( &heap->freeList[0].arena.entry );
645 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
647 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
648 pEntry->arena.magic = ARENA_FREE_MAGIC;
649 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
652 /* Initialize critical section */
654 if (!processHeap) /* do it by hand to avoid memory allocations */
656 if(TRACE_ON(heap_poison))
657 TRACE_(heap_poison)("poisioning heap\n");
658 heap->critSection.DebugInfo = &process_heap_critsect_debug;
659 heap->critSection.LockCount = -1;
660 heap->critSection.RecursionCount = 0;
661 heap->critSection.OwningThread = 0;
662 heap->critSection.LockSemaphore = 0;
663 heap->critSection.SpinCount = 0;
664 process_heap_critsect_debug.CriticalSection = &heap->critSection;
666 else
668 RtlInitializeCriticalSection( &heap->critSection );
669 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
672 if (flags & HEAP_SHARED)
674 /* let's assume that only one thread at a time will try to do this */
675 HANDLE sem = heap->critSection.LockSemaphore;
676 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
678 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
679 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
680 heap->critSection.LockSemaphore = sem;
681 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
682 heap->critSection.DebugInfo = NULL;
686 /* Create the first free block */
688 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
689 subheap->size - subheap->headerSize );
691 return subheap;
694 /***********************************************************************
695 * HEAP_CreateSubHeap
697 * Create a sub-heap of the given size.
698 * If heap == NULL, creates a main heap.
700 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
701 SIZE_T commitSize, SIZE_T totalSize )
703 LPVOID address = base;
704 SUBHEAP *ret;
706 /* round-up sizes on a 64K boundary */
707 totalSize = (totalSize + 0xffff) & 0xffff0000;
708 commitSize = (commitSize + 0xffff) & 0xffff0000;
709 if (!commitSize) commitSize = 0x10000;
710 if (totalSize < commitSize) totalSize = commitSize;
712 if (!address)
714 /* allocate the memory block */
715 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
716 MEM_RESERVE, get_protection_type( flags ) ))
718 WARN("Could not allocate %08lx bytes\n", totalSize );
719 return NULL;
723 /* Initialize subheap */
725 if (!(ret = HEAP_InitSubHeap( heap, address, flags, commitSize, totalSize )))
727 SIZE_T size = 0;
728 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
730 return ret;
734 /***********************************************************************
735 * HEAP_FindFreeBlock
737 * Find a free block at least as large as the requested size, and make sure
738 * the requested size is committed.
740 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
741 SUBHEAP **ppSubHeap )
743 SUBHEAP *subheap;
744 struct list *ptr;
745 SIZE_T total_size;
746 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
748 /* Find a suitable free list, and in it find a block large enough */
750 ptr = &pEntry->arena.entry;
751 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
753 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
754 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
755 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
756 if (arena_size >= size)
758 subheap = HEAP_FindSubHeap( heap, pArena );
759 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
760 *ppSubHeap = subheap;
761 return pArena;
765 /* If no block was found, attempt to grow the heap */
767 if (!(heap->flags & HEAP_GROWABLE))
769 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
770 return NULL;
772 /* make sure that we have a big enough size *committed* to fit another
773 * last free arena in !
774 * So just one heap struct, one first free arena which will eventually
775 * get used, and a second free arena that might get assigned all remaining
776 * free space in HEAP_ShrinkBlock() */
777 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
778 if (total_size < size) return NULL; /* overflow */
780 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
781 max( HEAP_DEF_SIZE, total_size ) )))
782 return NULL;
784 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
785 subheap, total_size, heap );
787 *ppSubHeap = subheap;
788 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
792 /***********************************************************************
793 * HEAP_IsValidArenaPtr
795 * Check that the pointer is inside the range possible for arenas.
797 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
799 int i;
800 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
801 if (!subheap) return FALSE;
802 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
803 if (subheap != &heap->subheap) return FALSE;
804 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
805 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
806 return FALSE;
810 /***********************************************************************
811 * HEAP_ValidateFreeArena
813 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
815 ARENA_FREE *prev, *next;
816 char *heapEnd = (char *)subheap->base + subheap->size;
818 /* Check for unaligned pointers */
819 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
821 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
822 return FALSE;
825 /* Check magic number */
826 if (pArena->magic != ARENA_FREE_MAGIC)
828 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
829 return FALSE;
831 /* Check size flags */
832 if (!(pArena->size & ARENA_FLAG_FREE) ||
833 (pArena->size & ARENA_FLAG_PREV_FREE))
835 ERR("Heap %p: bad flags %08x for free arena %p\n",
836 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
837 return FALSE;
839 /* Check arena size */
840 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
842 ERR("Heap %p: bad size %08x for free arena %p\n",
843 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
844 return FALSE;
846 /* Check that next pointer is valid */
847 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
848 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
850 ERR("Heap %p: bad next ptr %p for arena %p\n",
851 subheap->heap, next, pArena );
852 return FALSE;
854 /* Check that next arena is free */
855 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
857 ERR("Heap %p: next arena %p invalid for %p\n",
858 subheap->heap, next, pArena );
859 return FALSE;
861 /* Check that prev pointer is valid */
862 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
863 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
865 ERR("Heap %p: bad prev ptr %p for arena %p\n",
866 subheap->heap, prev, pArena );
867 return FALSE;
869 /* Check that prev arena is free */
870 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
872 /* this often means that the prev arena got overwritten
873 * by a memory write before that prev arena */
874 ERR("Heap %p: prev arena %p invalid for %p\n",
875 subheap->heap, prev, pArena );
876 return FALSE;
878 /* Check that next block has PREV_FREE flag */
879 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
881 if (!(*(DWORD *)((char *)(pArena + 1) +
882 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
884 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
885 subheap->heap, pArena );
886 return FALSE;
888 /* Check next block back pointer */
889 if (*((ARENA_FREE **)((char *)(pArena + 1) +
890 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
892 ERR("Heap %p: arena %p has wrong back ptr %p\n",
893 subheap->heap, pArena,
894 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
895 return FALSE;
898 return TRUE;
902 /***********************************************************************
903 * HEAP_ValidateInUseArena
905 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
907 const char *heapEnd = (const char *)subheap->base + subheap->size;
909 /* Check for unaligned pointers */
910 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
912 if ( quiet == NOISY )
914 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
915 if ( TRACE_ON(heap) )
916 HEAP_Dump( subheap->heap );
918 else if ( WARN_ON(heap) )
920 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
921 if ( TRACE_ON(heap) )
922 HEAP_Dump( subheap->heap );
924 return FALSE;
927 /* Check magic number */
928 if (pArena->magic != ARENA_INUSE_MAGIC)
930 if (quiet == NOISY) {
931 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
932 if (TRACE_ON(heap))
933 HEAP_Dump( subheap->heap );
934 } else if (WARN_ON(heap)) {
935 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
936 if (TRACE_ON(heap))
937 HEAP_Dump( subheap->heap );
939 return FALSE;
941 /* Check size flags */
942 if (pArena->size & ARENA_FLAG_FREE)
944 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
945 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
946 return FALSE;
948 /* Check arena size */
949 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
951 ERR("Heap %p: bad size %08x for in-use arena %p\n",
952 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
953 return FALSE;
955 /* Check next arena PREV_FREE flag */
956 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
957 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
959 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
960 subheap->heap, pArena );
961 return FALSE;
963 /* Check prev free arena */
964 if (pArena->size & ARENA_FLAG_PREV_FREE)
966 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
967 /* Check prev pointer */
968 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
970 ERR("Heap %p: bad back ptr %p for arena %p\n",
971 subheap->heap, pPrev, pArena );
972 return FALSE;
974 /* Check that prev arena is free */
975 if (!(pPrev->size & ARENA_FLAG_FREE) ||
976 (pPrev->magic != ARENA_FREE_MAGIC))
978 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
979 subheap->heap, pPrev, pArena );
980 return FALSE;
982 /* Check that prev arena is really the previous block */
983 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
985 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
986 subheap->heap, pPrev, pArena );
987 return FALSE;
990 return TRUE;
994 /***********************************************************************
995 * HEAP_IsRealArena [Internal]
996 * Validates a block is a valid arena.
998 * RETURNS
999 * TRUE: Success
1000 * FALSE: Failure
1002 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1003 DWORD flags, /* [in] Bit flags that control access during operation */
1004 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1005 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1006 * does not complain */
1008 SUBHEAP *subheap;
1009 BOOL ret = TRUE;
1011 flags &= HEAP_NO_SERIALIZE;
1012 flags |= heapPtr->flags;
1013 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1014 if (!(flags & HEAP_NO_SERIALIZE))
1015 RtlEnterCriticalSection( &heapPtr->critSection );
1017 if (block) /* only check this single memory block */
1019 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1021 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1022 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1024 if (quiet == NOISY)
1025 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1026 else if (WARN_ON(heap))
1027 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1028 ret = FALSE;
1029 } else
1030 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1032 if (!(flags & HEAP_NO_SERIALIZE))
1033 RtlLeaveCriticalSection( &heapPtr->critSection );
1034 return ret;
1037 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1039 char *ptr = (char *)subheap->base + subheap->headerSize;
1040 while (ptr < (char *)subheap->base + subheap->size)
1042 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1044 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1045 ret = FALSE;
1046 break;
1048 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1050 else
1052 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1053 ret = FALSE;
1054 break;
1056 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1059 if (!ret) break;
1062 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1063 return ret;
1067 /***********************************************************************
1068 * RtlCreateHeap (NTDLL.@)
1070 * Create a new Heap.
1072 * PARAMS
1073 * flags [I] HEAP_ flags from "winnt.h"
1074 * addr [I] Desired base address
1075 * totalSize [I] Total size of the heap, or 0 for a growable heap
1076 * commitSize [I] Amount of heap space to commit
1077 * unknown [I] Not yet understood
1078 * definition [I] Heap definition
1080 * RETURNS
1081 * Success: A HANDLE to the newly created heap.
1082 * Failure: a NULL HANDLE.
1084 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1085 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1087 SUBHEAP *subheap;
1089 /* Allocate the heap block */
1091 if (!totalSize)
1093 totalSize = HEAP_DEF_SIZE;
1094 flags |= HEAP_GROWABLE;
1097 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1099 /* link it into the per-process heap list */
1100 if (processHeap)
1102 HEAP *heapPtr = subheap->heap;
1103 RtlEnterCriticalSection( &processHeap->critSection );
1104 list_add_head( &processHeap->entry, &heapPtr->entry );
1105 RtlLeaveCriticalSection( &processHeap->critSection );
1107 else
1109 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1110 list_init( &processHeap->entry );
1111 /* make sure structure alignment is correct */
1112 assert( (ULONG_PTR)&processHeap->freeList % ALIGNMENT == 0 );
1115 return (HANDLE)subheap->heap;
1119 /***********************************************************************
1120 * RtlDestroyHeap (NTDLL.@)
1122 * Destroy a Heap created with RtlCreateHeap().
1124 * PARAMS
1125 * heap [I] Heap to destroy.
1127 * RETURNS
1128 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1129 * Failure: The Heap handle, if heap is the process heap.
1131 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1133 HEAP *heapPtr = HEAP_GetPtr( heap );
1134 SUBHEAP *subheap, *next;
1135 SIZE_T size;
1136 void *addr;
1138 TRACE("%p\n", heap );
1139 if (!heapPtr) return heap;
1141 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1143 /* remove it from the per-process list */
1144 RtlEnterCriticalSection( &processHeap->critSection );
1145 list_remove( &heapPtr->entry );
1146 RtlLeaveCriticalSection( &processHeap->critSection );
1148 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1149 RtlDeleteCriticalSection( &heapPtr->critSection );
1151 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1153 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1154 list_remove( &subheap->entry );
1155 size = 0;
1156 addr = subheap->base;
1157 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1159 size = 0;
1160 addr = heapPtr->subheap.base;
1161 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1162 return 0;
1166 /***********************************************************************
1167 * RtlAllocateHeap (NTDLL.@)
1169 * Allocate a memory block from a Heap.
1171 * PARAMS
1172 * heap [I] Heap to allocate block from
1173 * flags [I] HEAP_ flags from "winnt.h"
1174 * size [I] Size of the memory block to allocate
1176 * RETURNS
1177 * Success: A pointer to the newly allocated block
1178 * Failure: NULL.
1180 * NOTES
1181 * This call does not SetLastError().
1183 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1185 ARENA_FREE *pArena;
1186 ARENA_INUSE *pInUse;
1187 SUBHEAP *subheap;
1188 HEAP *heapPtr = HEAP_GetPtr( heap );
1189 SIZE_T rounded_size;
1191 /* Validate the parameters */
1193 if (!heapPtr) return NULL;
1194 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1195 flags |= heapPtr->flags;
1196 rounded_size = ROUND_SIZE(size);
1197 if (rounded_size < size) /* overflow */
1199 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1200 return NULL;
1202 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1204 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1205 /* Locate a suitable free block */
1207 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1209 TRACE("(%p,%08x,%08lx): returning NULL\n",
1210 heap, flags, size );
1211 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1212 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1213 return NULL;
1216 /* Remove the arena from the free list */
1218 list_remove( &pArena->entry );
1220 /* Build the in-use arena */
1222 pInUse = (ARENA_INUSE *)pArena;
1224 /* in-use arena is smaller than free arena,
1225 * so we have to add the difference to the size */
1226 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1227 pInUse->magic = ARENA_INUSE_MAGIC;
1229 /* Shrink the block */
1231 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1232 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1234 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1236 if (flags & HEAP_ZERO_MEMORY)
1237 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1238 else
1239 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1241 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1243 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1244 return (LPVOID)(pInUse + 1);
1248 /***********************************************************************
1249 * RtlFreeHeap (NTDLL.@)
1251 * Free a memory block allocated with RtlAllocateHeap().
1253 * PARAMS
1254 * heap [I] Heap that block was allocated from
1255 * flags [I] HEAP_ flags from "winnt.h"
1256 * ptr [I] Block to free
1258 * RETURNS
1259 * Success: TRUE, if ptr is NULL or was freed successfully.
1260 * Failure: FALSE.
1262 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1264 ARENA_INUSE *pInUse;
1265 SUBHEAP *subheap;
1266 HEAP *heapPtr;
1268 /* Validate the parameters */
1270 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1272 heapPtr = HEAP_GetPtr( heap );
1273 if (!heapPtr)
1275 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1276 return FALSE;
1279 flags &= HEAP_NO_SERIALIZE;
1280 flags |= heapPtr->flags;
1281 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1283 /* Some sanity checks */
1285 pInUse = (ARENA_INUSE *)ptr - 1;
1286 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse ))) goto error;
1287 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1288 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1290 /* Turn the block into a free block */
1292 notify_free( ptr );
1294 HEAP_MakeInUseBlockFree( subheap, pInUse );
1296 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1298 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1299 return TRUE;
1301 error:
1302 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1303 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1304 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1305 return FALSE;
1309 /***********************************************************************
1310 * RtlReAllocateHeap (NTDLL.@)
1312 * Change the size of a memory block allocated with RtlAllocateHeap().
1314 * PARAMS
1315 * heap [I] Heap that block was allocated from
1316 * flags [I] HEAP_ flags from "winnt.h"
1317 * ptr [I] Block to resize
1318 * size [I] Size of the memory block to allocate
1320 * RETURNS
1321 * Success: A pointer to the resized block (which may be different).
1322 * Failure: NULL.
1324 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1326 ARENA_INUSE *pArena;
1327 HEAP *heapPtr;
1328 SUBHEAP *subheap;
1329 SIZE_T oldSize, rounded_size;
1331 if (!ptr) return NULL;
1332 if (!(heapPtr = HEAP_GetPtr( heap )))
1334 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1335 return NULL;
1338 /* Validate the parameters */
1340 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1341 HEAP_REALLOC_IN_PLACE_ONLY;
1342 flags |= heapPtr->flags;
1343 rounded_size = ROUND_SIZE(size);
1344 if (rounded_size < size) /* overflow */
1346 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1347 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1348 return NULL;
1350 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1352 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1354 pArena = (ARENA_INUSE *)ptr - 1;
1355 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena ))) goto error;
1356 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1357 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1359 /* Check if we need to grow the block */
1361 oldSize = (pArena->size & ARENA_SIZE_MASK);
1362 if (rounded_size > oldSize)
1364 char *pNext = (char *)(pArena + 1) + oldSize;
1365 if ((pNext < (char *)subheap->base + subheap->size) &&
1366 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1367 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1369 /* The next block is free and large enough */
1370 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1371 list_remove( &pFree->entry );
1372 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1373 if (!HEAP_Commit( subheap, pArena, rounded_size ))
1375 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1376 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1377 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1378 return NULL;
1380 notify_free( pArena + 1 );
1381 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1382 notify_alloc( pArena + 1, size, FALSE );
1383 /* FIXME: this is wrong as we may lose old VBits settings */
1384 mark_block_initialized( pArena + 1, oldSize );
1386 else /* Do it the hard way */
1388 ARENA_FREE *pNew;
1389 ARENA_INUSE *pInUse;
1390 SUBHEAP *newsubheap;
1392 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1393 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1395 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1396 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1397 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1398 return NULL;
1401 /* Build the in-use arena */
1403 list_remove( &pNew->entry );
1404 pInUse = (ARENA_INUSE *)pNew;
1405 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1406 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1407 pInUse->magic = ARENA_INUSE_MAGIC;
1408 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1409 mark_block_initialized( pInUse + 1, oldSize );
1410 notify_alloc( pInUse + 1, size, FALSE );
1411 memcpy( pInUse + 1, pArena + 1, oldSize );
1413 /* Free the previous block */
1415 notify_free( pArena + 1 );
1416 HEAP_MakeInUseBlockFree( subheap, pArena );
1417 subheap = newsubheap;
1418 pArena = pInUse;
1421 else
1423 /* Shrink the block */
1424 notify_free( pArena + 1 );
1425 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1426 notify_alloc( pArena + 1, size, FALSE );
1427 /* FIXME: this is wrong as we may lose old VBits settings */
1428 mark_block_initialized( pArena + 1, size );
1431 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1433 /* Clear the extra bytes if needed */
1435 if (rounded_size > oldSize)
1437 if (flags & HEAP_ZERO_MEMORY)
1438 clear_block( (char *)(pArena + 1) + oldSize,
1439 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1440 else
1441 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1442 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1445 /* Return the new arena */
1447 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1449 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1450 return (LPVOID)(pArena + 1);
1452 error:
1453 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1454 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1455 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1456 return NULL;
1460 /***********************************************************************
1461 * RtlCompactHeap (NTDLL.@)
1463 * Compact the free space in a Heap.
1465 * PARAMS
1466 * heap [I] Heap that block was allocated from
1467 * flags [I] HEAP_ flags from "winnt.h"
1469 * RETURNS
1470 * The number of bytes compacted.
1472 * NOTES
1473 * This function is a harmless stub.
1475 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1477 static BOOL reported;
1478 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1479 return 0;
1483 /***********************************************************************
1484 * RtlLockHeap (NTDLL.@)
1486 * Lock a Heap.
1488 * PARAMS
1489 * heap [I] Heap to lock
1491 * RETURNS
1492 * Success: TRUE. The Heap is locked.
1493 * Failure: FALSE, if heap is invalid.
1495 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1497 HEAP *heapPtr = HEAP_GetPtr( heap );
1498 if (!heapPtr) return FALSE;
1499 RtlEnterCriticalSection( &heapPtr->critSection );
1500 return TRUE;
1504 /***********************************************************************
1505 * RtlUnlockHeap (NTDLL.@)
1507 * Unlock a Heap.
1509 * PARAMS
1510 * heap [I] Heap to unlock
1512 * RETURNS
1513 * Success: TRUE. The Heap is unlocked.
1514 * Failure: FALSE, if heap is invalid.
1516 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1518 HEAP *heapPtr = HEAP_GetPtr( heap );
1519 if (!heapPtr) return FALSE;
1520 RtlLeaveCriticalSection( &heapPtr->critSection );
1521 return TRUE;
1525 /***********************************************************************
1526 * RtlSizeHeap (NTDLL.@)
1528 * Get the actual size of a memory block allocated from a Heap.
1530 * PARAMS
1531 * heap [I] Heap that block was allocated from
1532 * flags [I] HEAP_ flags from "winnt.h"
1533 * ptr [I] Block to get the size of
1535 * RETURNS
1536 * Success: The size of the block.
1537 * Failure: -1, heap or ptr are invalid.
1539 * NOTES
1540 * The size may be bigger than what was passed to RtlAllocateHeap().
1542 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1544 SIZE_T ret;
1545 HEAP *heapPtr = HEAP_GetPtr( heap );
1547 if (!heapPtr)
1549 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1550 return ~0UL;
1552 flags &= HEAP_NO_SERIALIZE;
1553 flags |= heapPtr->flags;
1554 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1555 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1557 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1558 ret = ~0UL;
1560 else
1562 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1563 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1565 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1567 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1568 return ret;
1572 /***********************************************************************
1573 * RtlValidateHeap (NTDLL.@)
1575 * Determine if a block is a valid allocation from a heap.
1577 * PARAMS
1578 * heap [I] Heap that block was allocated from
1579 * flags [I] HEAP_ flags from "winnt.h"
1580 * ptr [I] Block to check
1582 * RETURNS
1583 * Success: TRUE. The block was allocated from heap.
1584 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1586 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1588 HEAP *heapPtr = HEAP_GetPtr( heap );
1589 if (!heapPtr) return FALSE;
1590 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1594 /***********************************************************************
1595 * RtlWalkHeap (NTDLL.@)
1597 * FIXME
1598 * The PROCESS_HEAP_ENTRY flag values seem different between this
1599 * function and HeapWalk(). To be checked.
1601 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1603 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1604 HEAP *heapPtr = HEAP_GetPtr(heap);
1605 SUBHEAP *sub, *currentheap = NULL;
1606 NTSTATUS ret;
1607 char *ptr;
1608 int region_index = 0;
1610 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1612 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1614 /* set ptr to the next arena to be examined */
1616 if (!entry->lpData) /* first call (init) ? */
1618 TRACE("begin walking of heap %p.\n", heap);
1619 currentheap = &heapPtr->subheap;
1620 ptr = (char*)currentheap->base + currentheap->headerSize;
1622 else
1624 ptr = entry->lpData;
1625 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1627 if ((ptr >= (char *)sub->base) &&
1628 (ptr < (char *)sub->base + sub->size))
1630 currentheap = sub;
1631 break;
1633 region_index++;
1635 if (currentheap == NULL)
1637 ERR("no matching subheap found, shouldn't happen !\n");
1638 ret = STATUS_NO_MORE_ENTRIES;
1639 goto HW_end;
1642 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1644 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1645 ptr += pArena->size & ARENA_SIZE_MASK;
1647 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1649 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1650 ptr += pArena->size & ARENA_SIZE_MASK;
1652 else
1653 ptr += entry->cbData; /* point to next arena */
1655 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1656 { /* proceed with next subheap */
1657 struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
1658 if (!next)
1659 { /* successfully finished */
1660 TRACE("end reached.\n");
1661 ret = STATUS_NO_MORE_ENTRIES;
1662 goto HW_end;
1664 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1665 ptr = (char *)currentheap->base + currentheap->headerSize;
1669 entry->wFlags = 0;
1670 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1672 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1674 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1676 entry->lpData = pArena + 1;
1677 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1678 entry->cbOverhead = sizeof(ARENA_FREE);
1679 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1681 else
1683 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1685 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1687 entry->lpData = pArena + 1;
1688 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1689 entry->cbOverhead = sizeof(ARENA_INUSE);
1690 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1691 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1692 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1695 entry->iRegionIndex = region_index;
1697 /* first element of heap ? */
1698 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1700 entry->wFlags |= PROCESS_HEAP_REGION;
1701 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1702 entry->u.Region.dwUnCommittedSize =
1703 currentheap->size - currentheap->commitSize;
1704 entry->u.Region.lpFirstBlock = /* first valid block */
1705 (char *)currentheap->base + currentheap->headerSize;
1706 entry->u.Region.lpLastBlock = /* first invalid block */
1707 (char *)currentheap->base + currentheap->size;
1709 ret = STATUS_SUCCESS;
1710 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1712 HW_end:
1713 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1714 return ret;
1718 /***********************************************************************
1719 * RtlGetProcessHeaps (NTDLL.@)
1721 * Get the Heaps belonging to the current process.
1723 * PARAMS
1724 * count [I] size of heaps
1725 * heaps [O] Destination array for heap HANDLE's
1727 * RETURNS
1728 * Success: The number of Heaps allocated by the process.
1729 * Failure: 0.
1731 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1733 ULONG total = 1; /* main heap */
1734 struct list *ptr;
1736 RtlEnterCriticalSection( &processHeap->critSection );
1737 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1738 if (total <= count)
1740 *heaps++ = processHeap;
1741 LIST_FOR_EACH( ptr, &processHeap->entry )
1742 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1744 RtlLeaveCriticalSection( &processHeap->critSection );
1745 return total;