comctl32: Move the getting of the DC outside of ANIMATE_DrawFrame.
[wine.git] / dlls / ntdll / heap.c
blob57ae2cb271b3a26abdd4014d4e2438f1dd9efa83
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);
46 /* Note: the heap data structures are loosely based on what Pietrek describes in his
47 * book 'Windows 95 System Programming Secrets', with some adaptations for
48 * better compatibility with NT.
51 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
52 * that there is no unaligned accesses to structure fields.
55 typedef struct tagARENA_INUSE
57 DWORD size; /* Block size; must be the first field */
58 DWORD magic : 24; /* Magic number */
59 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) */
60 } ARENA_INUSE;
62 typedef struct tagARENA_FREE
64 DWORD size; /* Block size; must be the first field */
65 DWORD magic; /* Magic number */
66 struct list entry; /* Entry in free list */
67 } ARENA_FREE;
69 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
70 #define ARENA_FLAG_PREV_FREE 0x00000002
71 #define ARENA_SIZE_MASK (~3)
72 #define ARENA_INUSE_MAGIC 0x455355 /* Value for arena 'magic' field */
73 #define ARENA_FREE_MAGIC 0x45455246 /* Value for arena 'magic' field */
75 #define ARENA_INUSE_FILLER 0x55
76 #define ARENA_FREE_FILLER 0xaa
78 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
79 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
81 #define QUIET 1 /* Suppress messages */
82 #define NOISY 0 /* Report all errors */
84 /* minimum data size (without arenas) of an allocated block */
85 /* make sure that it's larger than a free list entry */
86 #define HEAP_MIN_DATA_SIZE (2 * sizeof(struct list))
87 /* minimum size that must remain to shrink an allocated block */
88 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
90 /* Max size of the blocks on the free lists */
91 static const SIZE_T HEAP_freeListSizes[] =
93 0x10, 0x20, 0x30, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x1000, ~0UL
95 #define HEAP_NB_FREE_LISTS (sizeof(HEAP_freeListSizes)/sizeof(HEAP_freeListSizes[0]))
97 typedef struct
99 ARENA_FREE arena;
100 } FREE_LIST_ENTRY;
102 struct tagHEAP;
104 typedef struct tagSUBHEAP
106 void *base; /* Base address of the sub-heap memory block */
107 SIZE_T size; /* Size of the whole sub-heap */
108 SIZE_T commitSize; /* Committed size of the sub-heap */
109 struct list entry; /* Entry in sub-heap list */
110 struct tagHEAP *heap; /* Main heap structure */
111 DWORD headerSize; /* Size of the heap header */
112 DWORD magic; /* Magic number */
113 } SUBHEAP;
115 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
117 typedef struct tagHEAP
119 DWORD unknown[3];
120 DWORD flags; /* Heap flags */
121 DWORD force_flags; /* Forced heap flags for debugging */
122 SUBHEAP subheap; /* First sub-heap */
123 struct list entry; /* Entry in process heap list */
124 struct list subheap_list; /* Sub-heap list */
125 DWORD magic; /* Magic number */
126 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
127 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
128 } HEAP;
130 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
132 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
133 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
135 static HEAP *processHeap; /* main process heap */
137 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
139 /* mark a block of memory as free for debugging purposes */
140 static inline void mark_block_free( void *ptr, SIZE_T size )
142 if (TRACE_ON(heap) || WARN_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
143 #if defined(VALGRIND_MAKE_MEM_NOACCESS)
144 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_NOACCESS( ptr, size ));
145 #elif defined( VALGRIND_MAKE_NOACCESS)
146 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
147 #endif
150 /* mark a block of memory as initialized for debugging purposes */
151 static inline void mark_block_initialized( void *ptr, SIZE_T size )
153 #if defined(VALGRIND_MAKE_MEM_DEFINED)
154 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_DEFINED( ptr, size ));
155 #elif defined(VALGRIND_MAKE_READABLE)
156 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
157 #endif
160 /* mark a block of memory as uninitialized for debugging purposes */
161 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
163 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
164 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
165 #elif defined(VALGRIND_MAKE_WRITABLE)
166 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
167 #endif
168 if (TRACE_ON(heap) || WARN_ON(heap))
170 memset( ptr, ARENA_INUSE_FILLER, size );
171 #if defined(VALGRIND_MAKE_MEM_UNDEFINED)
172 VALGRIND_DISCARD( VALGRIND_MAKE_MEM_UNDEFINED( ptr, size ));
173 #elif defined(VALGRIND_MAKE_WRITABLE)
174 /* make it uninitialized to valgrind again */
175 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
176 #endif
180 /* clear contents of a block of memory */
181 static inline void clear_block( void *ptr, SIZE_T size )
183 mark_block_initialized( ptr, size );
184 memset( ptr, 0, size );
187 /* notify that a new block of memory has been allocated for debugging purposes */
188 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
190 #ifdef VALGRIND_MALLOCLIKE_BLOCK
191 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
192 #endif
195 /* notify that a block of memory has been freed for debugging purposes */
196 static inline void notify_free( void *ptr )
198 #ifdef VALGRIND_FREELIKE_BLOCK
199 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
200 #endif
203 /* locate a free list entry of the appropriate size */
204 /* size is the size of the whole block including the arena header */
205 static inline unsigned int get_freelist_index( SIZE_T size )
207 unsigned int i;
209 size -= sizeof(ARENA_FREE);
210 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
211 return i;
214 /* get the memory protection type to use for a given heap */
215 static inline ULONG get_protection_type( DWORD flags )
217 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
220 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
222 0, 0, NULL, /* will be set later */
223 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
224 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
228 /***********************************************************************
229 * HEAP_Dump
231 static void HEAP_Dump( HEAP *heap )
233 int i;
234 SUBHEAP *subheap;
235 char *ptr;
237 DPRINTF( "Heap: %p\n", heap );
238 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
239 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
241 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
242 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
243 DPRINTF( "%p free %08lx prev=%p next=%p\n",
244 &heap->freeList[i].arena, HEAP_freeListSizes[i],
245 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
246 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
248 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
250 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
251 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
252 subheap, subheap->base, subheap->size, subheap->commitSize );
254 DPRINTF( "\n Block Arena Stat Size Id\n" );
255 ptr = (char *)subheap->base + subheap->headerSize;
256 while (ptr < (char *)subheap->base + subheap->size)
258 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
260 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
261 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
262 pArena, pArena->magic,
263 pArena->size & ARENA_SIZE_MASK,
264 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
265 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
266 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
267 arenaSize += sizeof(ARENA_FREE);
268 freeSize += pArena->size & ARENA_SIZE_MASK;
270 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
272 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
273 DPRINTF( "%p %08x Used %08x back=%p\n",
274 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
275 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
276 arenaSize += sizeof(ARENA_INUSE);
277 usedSize += pArena->size & ARENA_SIZE_MASK;
279 else
281 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
282 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
283 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
284 arenaSize += sizeof(ARENA_INUSE);
285 usedSize += pArena->size & ARENA_SIZE_MASK;
288 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
289 subheap->size, subheap->commitSize, freeSize, usedSize,
290 arenaSize, (arenaSize * 100) / subheap->size );
295 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
297 WORD rem_flags;
298 TRACE( "Dumping entry %p\n", entry );
299 TRACE( "lpData\t\t: %p\n", entry->lpData );
300 TRACE( "cbData\t\t: %08x\n", entry->cbData);
301 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
302 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
303 TRACE( "WFlags\t\t: ");
304 if (entry->wFlags & PROCESS_HEAP_REGION)
305 TRACE( "PROCESS_HEAP_REGION ");
306 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
307 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
308 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
309 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
310 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
311 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
312 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
313 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
314 rem_flags = entry->wFlags &
315 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
316 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
317 PROCESS_HEAP_ENTRY_DDESHARE);
318 if (rem_flags)
319 TRACE( "Unknown %08x", rem_flags);
320 TRACE( "\n");
321 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
322 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
324 /* Treat as block */
325 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
327 if (entry->wFlags & PROCESS_HEAP_REGION)
329 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
330 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
331 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
332 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
336 /***********************************************************************
337 * HEAP_GetPtr
338 * RETURNS
339 * Pointer to the heap
340 * NULL: Failure
342 static HEAP *HEAP_GetPtr(
343 HANDLE heap /* [in] Handle to the heap */
345 HEAP *heapPtr = (HEAP *)heap;
346 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
348 ERR("Invalid heap %p!\n", heap );
349 return NULL;
351 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
353 HEAP_Dump( heapPtr );
354 assert( FALSE );
355 return NULL;
357 return heapPtr;
361 /***********************************************************************
362 * HEAP_InsertFreeBlock
364 * Insert a free block into the free list.
366 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
368 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
369 if (last)
371 /* insert at end of free list, i.e. before the next free list entry */
372 pEntry++;
373 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
374 list_add_before( &pEntry->arena.entry, &pArena->entry );
376 else
378 /* insert at head of free list */
379 list_add_after( &pEntry->arena.entry, &pArena->entry );
381 pArena->size |= ARENA_FLAG_FREE;
385 /***********************************************************************
386 * HEAP_FindSubHeap
387 * Find the sub-heap containing a given address.
389 * RETURNS
390 * Pointer: Success
391 * NULL: Failure
393 static SUBHEAP *HEAP_FindSubHeap(
394 const HEAP *heap, /* [in] Heap pointer */
395 LPCVOID ptr ) /* [in] Address */
397 SUBHEAP *sub;
398 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
399 if (((const char *)ptr >= (const char *)sub->base) &&
400 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
401 return sub;
402 return NULL;
406 /***********************************************************************
407 * HEAP_Commit
409 * Make sure the heap storage is committed for a given size in the specified arena.
411 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
413 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
414 SIZE_T size = (char *)ptr - (char *)subheap->base;
415 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
416 if (size > subheap->size) size = subheap->size;
417 if (size <= subheap->commitSize) return TRUE;
418 size -= subheap->commitSize;
419 ptr = (char *)subheap->base + subheap->commitSize;
420 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
421 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
423 WARN("Could not commit %08lx bytes at %p for heap %p\n",
424 size, ptr, subheap->heap );
425 return FALSE;
427 subheap->commitSize += size;
428 return TRUE;
432 /***********************************************************************
433 * HEAP_Decommit
435 * If possible, decommit the heap storage from (including) 'ptr'.
437 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
439 void *addr;
440 SIZE_T decommit_size;
441 SIZE_T size = (char *)ptr - (char *)subheap->base;
443 /* round to next block and add one full block */
444 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
445 if (size >= subheap->commitSize) return TRUE;
446 decommit_size = subheap->commitSize - size;
447 addr = (char *)subheap->base + size;
449 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
451 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
452 decommit_size, (char *)subheap->base + size, subheap->heap );
453 return FALSE;
455 subheap->commitSize -= decommit_size;
456 return TRUE;
460 /***********************************************************************
461 * HEAP_CreateFreeBlock
463 * Create a free block at a specified address. 'size' is the size of the
464 * whole block, including the new arena.
466 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
468 ARENA_FREE *pFree;
469 char *pEnd;
470 BOOL last;
472 /* Create a free arena */
473 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
474 pFree = (ARENA_FREE *)ptr;
475 pFree->magic = ARENA_FREE_MAGIC;
477 /* If debugging, erase the freed block content */
479 pEnd = (char *)ptr + size;
480 if (pEnd > (char *)subheap->base + subheap->commitSize)
481 pEnd = (char *)subheap->base + 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->base + 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->base + 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->base + 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->base + subheap->headerSize) &&
546 (subheap != &subheap->heap->subheap))
548 SIZE_T size = 0;
549 void *addr = subheap->base;
550 /* Remove the free block from the list */
551 list_remove( &pFree->entry );
552 /* Remove the subheap from the list */
553 list_remove( &subheap->entry );
554 /* Free the memory */
555 subheap->magic = 0;
556 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
557 return;
560 /* Decommit the end of the heap */
562 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
566 /***********************************************************************
567 * HEAP_ShrinkBlock
569 * Shrink an in-use block.
571 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
573 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
575 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
576 (pArena->size & ARENA_SIZE_MASK) - size );
577 /* assign size plus previous arena flags */
578 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
580 else
582 /* Turn off PREV_FREE flag in next block */
583 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
584 if (pNext < (char *)subheap->base + subheap->size)
585 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
589 /***********************************************************************
590 * HEAP_InitSubHeap
592 static SUBHEAP *HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
593 SIZE_T commitSize, SIZE_T totalSize )
595 SUBHEAP *subheap;
596 FREE_LIST_ENTRY *pEntry;
597 int i;
599 /* Commit memory */
601 if (flags & HEAP_SHARED)
602 commitSize = totalSize; /* always commit everything in a shared heap */
603 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
604 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
606 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
607 return NULL;
610 if (heap)
612 /* If this is a secondary subheap, insert it into list */
614 subheap = (SUBHEAP *)address;
615 subheap->base = address;
616 subheap->heap = heap;
617 subheap->size = totalSize;
618 subheap->commitSize = commitSize;
619 subheap->magic = SUBHEAP_MAGIC;
620 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
621 list_add_head( &heap->subheap_list, &subheap->entry );
623 else
625 /* If this is a primary subheap, initialize main heap */
627 heap = (HEAP *)address;
628 heap->flags = flags;
629 heap->magic = HEAP_MAGIC;
630 list_init( &heap->subheap_list );
632 subheap = &heap->subheap;
633 subheap->base = address;
634 subheap->heap = heap;
635 subheap->size = totalSize;
636 subheap->commitSize = commitSize;
637 subheap->magic = SUBHEAP_MAGIC;
638 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
639 list_add_head( &heap->subheap_list, &subheap->entry );
641 /* Build the free lists */
643 list_init( &heap->freeList[0].arena.entry );
644 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
646 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
647 pEntry->arena.magic = ARENA_FREE_MAGIC;
648 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
651 /* Initialize critical section */
653 if (!processHeap) /* do it by hand to avoid memory allocations */
655 heap->critSection.DebugInfo = &process_heap_critsect_debug;
656 heap->critSection.LockCount = -1;
657 heap->critSection.RecursionCount = 0;
658 heap->critSection.OwningThread = 0;
659 heap->critSection.LockSemaphore = 0;
660 heap->critSection.SpinCount = 0;
661 process_heap_critsect_debug.CriticalSection = &heap->critSection;
663 else
665 RtlInitializeCriticalSection( &heap->critSection );
666 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
669 if (flags & HEAP_SHARED)
671 /* let's assume that only one thread at a time will try to do this */
672 HANDLE sem = heap->critSection.LockSemaphore;
673 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
675 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
676 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
677 heap->critSection.LockSemaphore = sem;
678 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
679 heap->critSection.DebugInfo = NULL;
683 /* Create the first free block */
685 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
686 subheap->size - subheap->headerSize );
688 return subheap;
691 /***********************************************************************
692 * HEAP_CreateSubHeap
694 * Create a sub-heap of the given size.
695 * If heap == NULL, creates a main heap.
697 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
698 SIZE_T commitSize, SIZE_T totalSize )
700 LPVOID address = base;
701 SUBHEAP *ret;
703 /* round-up sizes on a 64K boundary */
704 totalSize = (totalSize + 0xffff) & 0xffff0000;
705 commitSize = (commitSize + 0xffff) & 0xffff0000;
706 if (!commitSize) commitSize = 0x10000;
707 if (totalSize < commitSize) totalSize = commitSize;
709 if (!address)
711 /* allocate the memory block */
712 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
713 MEM_RESERVE, get_protection_type( flags ) ))
715 WARN("Could not allocate %08lx bytes\n", totalSize );
716 return NULL;
720 /* Initialize subheap */
722 if (!(ret = HEAP_InitSubHeap( heap, address, flags, commitSize, totalSize )))
724 SIZE_T size = 0;
725 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
727 return ret;
731 /***********************************************************************
732 * HEAP_FindFreeBlock
734 * Find a free block at least as large as the requested size, and make sure
735 * the requested size is committed.
737 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
738 SUBHEAP **ppSubHeap )
740 SUBHEAP *subheap;
741 struct list *ptr;
742 SIZE_T total_size;
743 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
745 /* Find a suitable free list, and in it find a block large enough */
747 ptr = &pEntry->arena.entry;
748 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
750 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
751 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
752 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
753 if (arena_size >= size)
755 subheap = HEAP_FindSubHeap( heap, pArena );
756 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
757 *ppSubHeap = subheap;
758 return pArena;
762 /* If no block was found, attempt to grow the heap */
764 if (!(heap->flags & HEAP_GROWABLE))
766 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
767 return NULL;
769 /* make sure that we have a big enough size *committed* to fit another
770 * last free arena in !
771 * So just one heap struct, one first free arena which will eventually
772 * get used, and a second free arena that might get assigned all remaining
773 * free space in HEAP_ShrinkBlock() */
774 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
775 if (total_size < size) return NULL; /* overflow */
777 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
778 max( HEAP_DEF_SIZE, total_size ) )))
779 return NULL;
781 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
782 subheap, total_size, heap );
784 *ppSubHeap = subheap;
785 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
789 /***********************************************************************
790 * HEAP_IsValidArenaPtr
792 * Check that the pointer is inside the range possible for arenas.
794 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
796 int i;
797 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
798 if (!subheap) return FALSE;
799 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
800 if (subheap != &heap->subheap) return FALSE;
801 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
802 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
803 return FALSE;
807 /***********************************************************************
808 * HEAP_ValidateFreeArena
810 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
812 ARENA_FREE *prev, *next;
813 char *heapEnd = (char *)subheap->base + subheap->size;
815 /* Check for unaligned pointers */
816 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
818 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
819 return FALSE;
822 /* Check magic number */
823 if (pArena->magic != ARENA_FREE_MAGIC)
825 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
826 return FALSE;
828 /* Check size flags */
829 if (!(pArena->size & ARENA_FLAG_FREE) ||
830 (pArena->size & ARENA_FLAG_PREV_FREE))
832 ERR("Heap %p: bad flags %08x for free arena %p\n",
833 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
834 return FALSE;
836 /* Check arena size */
837 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
839 ERR("Heap %p: bad size %08x for free arena %p\n",
840 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
841 return FALSE;
843 /* Check that next pointer is valid */
844 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
845 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
847 ERR("Heap %p: bad next ptr %p for arena %p\n",
848 subheap->heap, next, pArena );
849 return FALSE;
851 /* Check that next arena is free */
852 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
854 ERR("Heap %p: next arena %p invalid for %p\n",
855 subheap->heap, next, pArena );
856 return FALSE;
858 /* Check that prev pointer is valid */
859 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
860 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
862 ERR("Heap %p: bad prev ptr %p for arena %p\n",
863 subheap->heap, prev, pArena );
864 return FALSE;
866 /* Check that prev arena is free */
867 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
869 /* this often means that the prev arena got overwritten
870 * by a memory write before that prev arena */
871 ERR("Heap %p: prev arena %p invalid for %p\n",
872 subheap->heap, prev, pArena );
873 return FALSE;
875 /* Check that next block has PREV_FREE flag */
876 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
878 if (!(*(DWORD *)((char *)(pArena + 1) +
879 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
881 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
882 subheap->heap, pArena );
883 return FALSE;
885 /* Check next block back pointer */
886 if (*((ARENA_FREE **)((char *)(pArena + 1) +
887 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
889 ERR("Heap %p: arena %p has wrong back ptr %p\n",
890 subheap->heap, pArena,
891 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
892 return FALSE;
895 return TRUE;
899 /***********************************************************************
900 * HEAP_ValidateInUseArena
902 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
904 const char *heapEnd = (const char *)subheap->base + subheap->size;
906 /* Check for unaligned pointers */
907 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
909 if ( quiet == NOISY )
911 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
912 if ( TRACE_ON(heap) )
913 HEAP_Dump( subheap->heap );
915 else if ( WARN_ON(heap) )
917 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
918 if ( TRACE_ON(heap) )
919 HEAP_Dump( subheap->heap );
921 return FALSE;
924 /* Check magic number */
925 if (pArena->magic != ARENA_INUSE_MAGIC)
927 if (quiet == NOISY) {
928 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
929 if (TRACE_ON(heap))
930 HEAP_Dump( subheap->heap );
931 } else if (WARN_ON(heap)) {
932 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
933 if (TRACE_ON(heap))
934 HEAP_Dump( subheap->heap );
936 return FALSE;
938 /* Check size flags */
939 if (pArena->size & ARENA_FLAG_FREE)
941 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
942 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
943 return FALSE;
945 /* Check arena size */
946 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
948 ERR("Heap %p: bad size %08x for in-use arena %p\n",
949 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
950 return FALSE;
952 /* Check next arena PREV_FREE flag */
953 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
954 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
956 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
957 subheap->heap, pArena );
958 return FALSE;
960 /* Check prev free arena */
961 if (pArena->size & ARENA_FLAG_PREV_FREE)
963 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
964 /* Check prev pointer */
965 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
967 ERR("Heap %p: bad back ptr %p for arena %p\n",
968 subheap->heap, pPrev, pArena );
969 return FALSE;
971 /* Check that prev arena is free */
972 if (!(pPrev->size & ARENA_FLAG_FREE) ||
973 (pPrev->magic != ARENA_FREE_MAGIC))
975 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
976 subheap->heap, pPrev, pArena );
977 return FALSE;
979 /* Check that prev arena is really the previous block */
980 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
982 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
983 subheap->heap, pPrev, pArena );
984 return FALSE;
987 return TRUE;
991 /***********************************************************************
992 * HEAP_IsRealArena [Internal]
993 * Validates a block is a valid arena.
995 * RETURNS
996 * TRUE: Success
997 * FALSE: Failure
999 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
1000 DWORD flags, /* [in] Bit flags that control access during operation */
1001 LPCVOID block, /* [in] Optional pointer to memory block to validate */
1002 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
1003 * does not complain */
1005 SUBHEAP *subheap;
1006 BOOL ret = TRUE;
1008 flags &= HEAP_NO_SERIALIZE;
1009 flags |= heapPtr->flags;
1010 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1011 if (!(flags & HEAP_NO_SERIALIZE))
1012 RtlEnterCriticalSection( &heapPtr->critSection );
1014 if (block) /* only check this single memory block */
1016 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1018 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1019 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1021 if (quiet == NOISY)
1022 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1023 else if (WARN_ON(heap))
1024 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1025 ret = FALSE;
1026 } else
1027 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1029 if (!(flags & HEAP_NO_SERIALIZE))
1030 RtlLeaveCriticalSection( &heapPtr->critSection );
1031 return ret;
1034 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1036 char *ptr = (char *)subheap->base + subheap->headerSize;
1037 while (ptr < (char *)subheap->base + 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 if (!ret) break;
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 );
1108 /* make sure structure alignment is correct */
1109 assert( (ULONG_PTR)&processHeap->freeList % ALIGNMENT == 0 );
1112 return (HANDLE)subheap->heap;
1116 /***********************************************************************
1117 * RtlDestroyHeap (NTDLL.@)
1119 * Destroy a Heap created with RtlCreateHeap().
1121 * PARAMS
1122 * heap [I] Heap to destroy.
1124 * RETURNS
1125 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1126 * Failure: The Heap handle, if heap is the process heap.
1128 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1130 HEAP *heapPtr = HEAP_GetPtr( heap );
1131 SUBHEAP *subheap, *next;
1132 SIZE_T size;
1133 void *addr;
1135 TRACE("%p\n", heap );
1136 if (!heapPtr) return heap;
1138 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1140 /* remove it from the per-process list */
1141 RtlEnterCriticalSection( &processHeap->critSection );
1142 list_remove( &heapPtr->entry );
1143 RtlLeaveCriticalSection( &processHeap->critSection );
1145 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1146 RtlDeleteCriticalSection( &heapPtr->critSection );
1148 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1150 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1151 list_remove( &subheap->entry );
1152 size = 0;
1153 addr = subheap->base;
1154 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1156 size = 0;
1157 addr = heapPtr->subheap.base;
1158 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1159 return 0;
1163 /***********************************************************************
1164 * RtlAllocateHeap (NTDLL.@)
1166 * Allocate a memory block from a Heap.
1168 * PARAMS
1169 * heap [I] Heap to allocate block from
1170 * flags [I] HEAP_ flags from "winnt.h"
1171 * size [I] Size of the memory block to allocate
1173 * RETURNS
1174 * Success: A pointer to the newly allocated block
1175 * Failure: NULL.
1177 * NOTES
1178 * This call does not SetLastError().
1180 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1182 ARENA_FREE *pArena;
1183 ARENA_INUSE *pInUse;
1184 SUBHEAP *subheap;
1185 HEAP *heapPtr = HEAP_GetPtr( heap );
1186 SIZE_T rounded_size;
1188 /* Validate the parameters */
1190 if (!heapPtr) return NULL;
1191 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1192 flags |= heapPtr->flags;
1193 rounded_size = ROUND_SIZE(size);
1194 if (rounded_size < size) /* overflow */
1196 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1197 return NULL;
1199 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1201 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1202 /* Locate a suitable free block */
1204 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1206 TRACE("(%p,%08x,%08lx): returning NULL\n",
1207 heap, flags, size );
1208 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1209 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1210 return NULL;
1213 /* Remove the arena from the free list */
1215 list_remove( &pArena->entry );
1217 /* Build the in-use arena */
1219 pInUse = (ARENA_INUSE *)pArena;
1221 /* in-use arena is smaller than free arena,
1222 * so we have to add the difference to the size */
1223 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1224 pInUse->magic = ARENA_INUSE_MAGIC;
1226 /* Shrink the block */
1228 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1229 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1231 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1233 if (flags & HEAP_ZERO_MEMORY)
1234 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1235 else
1236 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1238 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1240 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1241 return (LPVOID)(pInUse + 1);
1245 /***********************************************************************
1246 * RtlFreeHeap (NTDLL.@)
1248 * Free a memory block allocated with RtlAllocateHeap().
1250 * PARAMS
1251 * heap [I] Heap that block was allocated from
1252 * flags [I] HEAP_ flags from "winnt.h"
1253 * ptr [I] Block to free
1255 * RETURNS
1256 * Success: TRUE, if ptr is NULL or was freed successfully.
1257 * Failure: FALSE.
1259 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1261 ARENA_INUSE *pInUse;
1262 SUBHEAP *subheap;
1263 HEAP *heapPtr;
1265 /* Validate the parameters */
1267 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1269 heapPtr = HEAP_GetPtr( heap );
1270 if (!heapPtr)
1272 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1273 return FALSE;
1276 flags &= HEAP_NO_SERIALIZE;
1277 flags |= heapPtr->flags;
1278 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1280 /* Some sanity checks */
1282 pInUse = (ARENA_INUSE *)ptr - 1;
1283 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse ))) goto error;
1284 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1285 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1287 /* Turn the block into a free block */
1289 notify_free( ptr );
1291 HEAP_MakeInUseBlockFree( subheap, pInUse );
1293 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1295 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1296 return TRUE;
1298 error:
1299 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1300 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1301 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1302 return FALSE;
1306 /***********************************************************************
1307 * RtlReAllocateHeap (NTDLL.@)
1309 * Change the size of a memory block allocated with RtlAllocateHeap().
1311 * PARAMS
1312 * heap [I] Heap that block was allocated from
1313 * flags [I] HEAP_ flags from "winnt.h"
1314 * ptr [I] Block to resize
1315 * size [I] Size of the memory block to allocate
1317 * RETURNS
1318 * Success: A pointer to the resized block (which may be different).
1319 * Failure: NULL.
1321 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1323 ARENA_INUSE *pArena;
1324 HEAP *heapPtr;
1325 SUBHEAP *subheap;
1326 SIZE_T oldSize, rounded_size;
1328 if (!ptr) return NULL;
1329 if (!(heapPtr = HEAP_GetPtr( heap )))
1331 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1332 return NULL;
1335 /* Validate the parameters */
1337 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1338 HEAP_REALLOC_IN_PLACE_ONLY;
1339 flags |= heapPtr->flags;
1340 rounded_size = ROUND_SIZE(size);
1341 if (rounded_size < size) /* overflow */
1343 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1344 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1345 return NULL;
1347 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1349 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1351 pArena = (ARENA_INUSE *)ptr - 1;
1352 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena ))) goto error;
1353 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1354 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1356 /* Check if we need to grow the block */
1358 oldSize = (pArena->size & ARENA_SIZE_MASK);
1359 if (rounded_size > oldSize)
1361 char *pNext = (char *)(pArena + 1) + oldSize;
1362 if ((pNext < (char *)subheap->base + subheap->size) &&
1363 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1364 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1366 /* The next block is free and large enough */
1367 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1368 list_remove( &pFree->entry );
1369 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1370 if (!HEAP_Commit( subheap, pArena, rounded_size ))
1372 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1373 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1374 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1375 return NULL;
1377 notify_free( pArena + 1 );
1378 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1379 notify_alloc( pArena + 1, size, FALSE );
1380 /* FIXME: this is wrong as we may lose old VBits settings */
1381 mark_block_initialized( pArena + 1, oldSize );
1383 else /* Do it the hard way */
1385 ARENA_FREE *pNew;
1386 ARENA_INUSE *pInUse;
1387 SUBHEAP *newsubheap;
1389 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1390 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1392 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1393 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1394 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1395 return NULL;
1398 /* Build the in-use arena */
1400 list_remove( &pNew->entry );
1401 pInUse = (ARENA_INUSE *)pNew;
1402 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1403 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1404 pInUse->magic = ARENA_INUSE_MAGIC;
1405 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1406 mark_block_initialized( pInUse + 1, oldSize );
1407 notify_alloc( pInUse + 1, size, FALSE );
1408 memcpy( pInUse + 1, pArena + 1, oldSize );
1410 /* Free the previous block */
1412 notify_free( pArena + 1 );
1413 HEAP_MakeInUseBlockFree( subheap, pArena );
1414 subheap = newsubheap;
1415 pArena = pInUse;
1418 else
1420 /* Shrink the block */
1421 notify_free( pArena + 1 );
1422 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1423 notify_alloc( pArena + 1, size, FALSE );
1424 /* FIXME: this is wrong as we may lose old VBits settings */
1425 mark_block_initialized( pArena + 1, size );
1428 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1430 /* Clear the extra bytes if needed */
1432 if (rounded_size > oldSize)
1434 if (flags & HEAP_ZERO_MEMORY)
1435 clear_block( (char *)(pArena + 1) + oldSize,
1436 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1437 else
1438 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1439 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1442 /* Return the new arena */
1444 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1446 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1447 return (LPVOID)(pArena + 1);
1449 error:
1450 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1451 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1452 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1453 return NULL;
1457 /***********************************************************************
1458 * RtlCompactHeap (NTDLL.@)
1460 * Compact the free space in a Heap.
1462 * PARAMS
1463 * heap [I] Heap that block was allocated from
1464 * flags [I] HEAP_ flags from "winnt.h"
1466 * RETURNS
1467 * The number of bytes compacted.
1469 * NOTES
1470 * This function is a harmless stub.
1472 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1474 static BOOL reported;
1475 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1476 return 0;
1480 /***********************************************************************
1481 * RtlLockHeap (NTDLL.@)
1483 * Lock a Heap.
1485 * PARAMS
1486 * heap [I] Heap to lock
1488 * RETURNS
1489 * Success: TRUE. The Heap is locked.
1490 * Failure: FALSE, if heap is invalid.
1492 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1494 HEAP *heapPtr = HEAP_GetPtr( heap );
1495 if (!heapPtr) return FALSE;
1496 RtlEnterCriticalSection( &heapPtr->critSection );
1497 return TRUE;
1501 /***********************************************************************
1502 * RtlUnlockHeap (NTDLL.@)
1504 * Unlock a Heap.
1506 * PARAMS
1507 * heap [I] Heap to unlock
1509 * RETURNS
1510 * Success: TRUE. The Heap is unlocked.
1511 * Failure: FALSE, if heap is invalid.
1513 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1515 HEAP *heapPtr = HEAP_GetPtr( heap );
1516 if (!heapPtr) return FALSE;
1517 RtlLeaveCriticalSection( &heapPtr->critSection );
1518 return TRUE;
1522 /***********************************************************************
1523 * RtlSizeHeap (NTDLL.@)
1525 * Get the actual size of a memory block allocated from a Heap.
1527 * PARAMS
1528 * heap [I] Heap that block was allocated from
1529 * flags [I] HEAP_ flags from "winnt.h"
1530 * ptr [I] Block to get the size of
1532 * RETURNS
1533 * Success: The size of the block.
1534 * Failure: -1, heap or ptr are invalid.
1536 * NOTES
1537 * The size may be bigger than what was passed to RtlAllocateHeap().
1539 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1541 SIZE_T ret;
1542 HEAP *heapPtr = HEAP_GetPtr( heap );
1544 if (!heapPtr)
1546 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1547 return ~0UL;
1549 flags &= HEAP_NO_SERIALIZE;
1550 flags |= heapPtr->flags;
1551 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1552 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1554 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1555 ret = ~0UL;
1557 else
1559 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1560 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1562 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1564 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1565 return ret;
1569 /***********************************************************************
1570 * RtlValidateHeap (NTDLL.@)
1572 * Determine if a block is a valid allocation from a heap.
1574 * PARAMS
1575 * heap [I] Heap that block was allocated from
1576 * flags [I] HEAP_ flags from "winnt.h"
1577 * ptr [I] Block to check
1579 * RETURNS
1580 * Success: TRUE. The block was allocated from heap.
1581 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1583 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1585 HEAP *heapPtr = HEAP_GetPtr( heap );
1586 if (!heapPtr) return FALSE;
1587 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1591 /***********************************************************************
1592 * RtlWalkHeap (NTDLL.@)
1594 * FIXME
1595 * The PROCESS_HEAP_ENTRY flag values seem different between this
1596 * function and HeapWalk(). To be checked.
1598 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1600 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1601 HEAP *heapPtr = HEAP_GetPtr(heap);
1602 SUBHEAP *sub, *currentheap = NULL;
1603 NTSTATUS ret;
1604 char *ptr;
1605 int region_index = 0;
1607 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1609 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1611 /* set ptr to the next arena to be examined */
1613 if (!entry->lpData) /* first call (init) ? */
1615 TRACE("begin walking of heap %p.\n", heap);
1616 currentheap = &heapPtr->subheap;
1617 ptr = (char*)currentheap->base + currentheap->headerSize;
1619 else
1621 ptr = entry->lpData;
1622 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1624 if ((ptr >= (char *)sub->base) &&
1625 (ptr < (char *)sub->base + sub->size))
1627 currentheap = sub;
1628 break;
1630 region_index++;
1632 if (currentheap == NULL)
1634 ERR("no matching subheap found, shouldn't happen !\n");
1635 ret = STATUS_NO_MORE_ENTRIES;
1636 goto HW_end;
1639 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1641 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1642 ptr += pArena->size & ARENA_SIZE_MASK;
1644 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1646 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1647 ptr += pArena->size & ARENA_SIZE_MASK;
1649 else
1650 ptr += entry->cbData; /* point to next arena */
1652 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1653 { /* proceed with next subheap */
1654 struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
1655 if (!next)
1656 { /* successfully finished */
1657 TRACE("end reached.\n");
1658 ret = STATUS_NO_MORE_ENTRIES;
1659 goto HW_end;
1661 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1662 ptr = (char *)currentheap->base + currentheap->headerSize;
1666 entry->wFlags = 0;
1667 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1669 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1671 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1673 entry->lpData = pArena + 1;
1674 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1675 entry->cbOverhead = sizeof(ARENA_FREE);
1676 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1678 else
1680 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1682 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1684 entry->lpData = pArena + 1;
1685 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1686 entry->cbOverhead = sizeof(ARENA_INUSE);
1687 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1688 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1689 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1692 entry->iRegionIndex = region_index;
1694 /* first element of heap ? */
1695 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1697 entry->wFlags |= PROCESS_HEAP_REGION;
1698 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1699 entry->u.Region.dwUnCommittedSize =
1700 currentheap->size - currentheap->commitSize;
1701 entry->u.Region.lpFirstBlock = /* first valid block */
1702 (char *)currentheap->base + currentheap->headerSize;
1703 entry->u.Region.lpLastBlock = /* first invalid block */
1704 (char *)currentheap->base + currentheap->size;
1706 ret = STATUS_SUCCESS;
1707 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1709 HW_end:
1710 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1711 return ret;
1715 /***********************************************************************
1716 * RtlGetProcessHeaps (NTDLL.@)
1718 * Get the Heaps belonging to the current process.
1720 * PARAMS
1721 * count [I] size of heaps
1722 * heaps [O] Destination array for heap HANDLE's
1724 * RETURNS
1725 * Success: The number of Heaps allocated by the process.
1726 * Failure: 0.
1728 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1730 ULONG total = 1; /* main heap */
1731 struct list *ptr;
1733 RtlEnterCriticalSection( &processHeap->critSection );
1734 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1735 if (total <= count)
1737 *heaps++ = processHeap;
1738 LIST_FOR_EACH( ptr, &processHeap->entry )
1739 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1741 RtlLeaveCriticalSection( &processHeap->critSection );
1742 return total;