push 0f15bbd80d260bbd8adf052e820484a405c49375
[wine/hacks.git] / dlls / ntdll / heap.c
blob2ba2bf0f9301aa05e597a6003f9d920f5791ab09
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 #ifdef VALGRIND_MAKE_NOACCESS
145 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
146 #endif
149 /* mark a block of memory as initialized for debugging purposes */
150 static inline void mark_block_initialized( void *ptr, SIZE_T size )
152 #ifdef VALGRIND_MAKE_READABLE
153 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
154 #endif
157 /* mark a block of memory as uninitialized for debugging purposes */
158 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
160 #ifdef VALGRIND_MAKE_WRITABLE
161 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
162 #endif
163 if (TRACE_ON(heap) || WARN_ON(heap) || TRACE_ON(heap_poison))
165 memset( ptr, ARENA_INUSE_FILLER, size );
166 #ifdef VALGRIND_MAKE_WRITABLE
167 /* make it uninitialized to valgrind again */
168 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
169 #endif
173 /* clear contents of a block of memory */
174 static inline void clear_block( void *ptr, SIZE_T size )
176 mark_block_initialized( ptr, size );
177 memset( ptr, 0, size );
180 /* notify that a new block of memory has been allocated for debugging purposes */
181 static inline void notify_alloc( void *ptr, SIZE_T size, BOOL init )
183 #ifdef VALGRIND_MALLOCLIKE_BLOCK
184 VALGRIND_MALLOCLIKE_BLOCK( ptr, size, 0, init );
185 #endif
188 /* notify that a block of memory has been freed for debugging purposes */
189 static inline void notify_free( void *ptr )
191 #ifdef VALGRIND_FREELIKE_BLOCK
192 VALGRIND_FREELIKE_BLOCK( ptr, 0 );
193 #endif
196 /* locate a free list entry of the appropriate size */
197 /* size is the size of the whole block including the arena header */
198 static inline unsigned int get_freelist_index( SIZE_T size )
200 unsigned int i;
202 size -= sizeof(ARENA_FREE);
203 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
204 return i;
207 /* get the memory protection type to use for a given heap */
208 static inline ULONG get_protection_type( DWORD flags )
210 return (flags & HEAP_CREATE_ENABLE_EXECUTE) ? PAGE_EXECUTE_READWRITE : PAGE_READWRITE;
213 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
215 0, 0, NULL, /* will be set later */
216 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
217 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
221 /***********************************************************************
222 * HEAP_Dump
224 static void HEAP_Dump( HEAP *heap )
226 int i;
227 SUBHEAP *subheap;
228 char *ptr;
230 DPRINTF( "Heap: %p\n", heap );
231 DPRINTF( "Next: %p Sub-heaps:", LIST_ENTRY( heap->entry.next, HEAP, entry ) );
232 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry ) DPRINTF( " %p", subheap );
234 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
235 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
236 DPRINTF( "%p free %08lx prev=%p next=%p\n",
237 &heap->freeList[i].arena, HEAP_freeListSizes[i],
238 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
239 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
241 LIST_FOR_EACH_ENTRY( subheap, &heap->subheap_list, SUBHEAP, entry )
243 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
244 DPRINTF( "\n\nSub-heap %p: base=%p size=%08lx committed=%08lx\n",
245 subheap, subheap->base, subheap->size, subheap->commitSize );
247 DPRINTF( "\n Block Arena Stat Size Id\n" );
248 ptr = (char *)subheap->base + subheap->headerSize;
249 while (ptr < (char *)subheap->base + subheap->size)
251 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
253 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
254 DPRINTF( "%p %08x free %08x prev=%p next=%p\n",
255 pArena, pArena->magic,
256 pArena->size & ARENA_SIZE_MASK,
257 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
258 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
259 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
260 arenaSize += sizeof(ARENA_FREE);
261 freeSize += pArena->size & ARENA_SIZE_MASK;
263 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
265 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
266 DPRINTF( "%p %08x Used %08x back=%p\n",
267 pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
268 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
269 arenaSize += sizeof(ARENA_INUSE);
270 usedSize += pArena->size & ARENA_SIZE_MASK;
272 else
274 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
275 DPRINTF( "%p %08x used %08x\n", pArena, pArena->magic, pArena->size & ARENA_SIZE_MASK );
276 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
277 arenaSize += sizeof(ARENA_INUSE);
278 usedSize += pArena->size & ARENA_SIZE_MASK;
281 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
282 subheap->size, subheap->commitSize, freeSize, usedSize,
283 arenaSize, (arenaSize * 100) / subheap->size );
288 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
290 WORD rem_flags;
291 TRACE( "Dumping entry %p\n", entry );
292 TRACE( "lpData\t\t: %p\n", entry->lpData );
293 TRACE( "cbData\t\t: %08x\n", entry->cbData);
294 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
295 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
296 TRACE( "WFlags\t\t: ");
297 if (entry->wFlags & PROCESS_HEAP_REGION)
298 TRACE( "PROCESS_HEAP_REGION ");
299 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
300 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
301 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
302 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
303 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
304 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
305 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
306 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
307 rem_flags = entry->wFlags &
308 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
309 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
310 PROCESS_HEAP_ENTRY_DDESHARE);
311 if (rem_flags)
312 TRACE( "Unknown %08x", rem_flags);
313 TRACE( "\n");
314 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
315 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
317 /* Treat as block */
318 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
320 if (entry->wFlags & PROCESS_HEAP_REGION)
322 TRACE( "Region.dwCommittedSize\t:%08x\n",entry->u.Region.dwCommittedSize);
323 TRACE( "Region.dwUnCommittedSize\t:%08x\n",entry->u.Region.dwUnCommittedSize);
324 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
325 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
329 /***********************************************************************
330 * HEAP_GetPtr
331 * RETURNS
332 * Pointer to the heap
333 * NULL: Failure
335 static HEAP *HEAP_GetPtr(
336 HANDLE heap /* [in] Handle to the heap */
338 HEAP *heapPtr = (HEAP *)heap;
339 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
341 ERR("Invalid heap %p!\n", heap );
342 return NULL;
344 if ((TRACE_ON(heap)|| TRACE_ON(heap_poison)) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
346 HEAP_Dump( heapPtr );
347 assert( FALSE );
348 return NULL;
350 return heapPtr;
354 /***********************************************************************
355 * HEAP_InsertFreeBlock
357 * Insert a free block into the free list.
359 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
361 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
362 if (last)
364 /* insert at end of free list, i.e. before the next free list entry */
365 pEntry++;
366 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
367 list_add_before( &pEntry->arena.entry, &pArena->entry );
369 else
371 /* insert at head of free list */
372 list_add_after( &pEntry->arena.entry, &pArena->entry );
374 pArena->size |= ARENA_FLAG_FREE;
378 /***********************************************************************
379 * HEAP_FindSubHeap
380 * Find the sub-heap containing a given address.
382 * RETURNS
383 * Pointer: Success
384 * NULL: Failure
386 static SUBHEAP *HEAP_FindSubHeap(
387 const HEAP *heap, /* [in] Heap pointer */
388 LPCVOID ptr ) /* [in] Address */
390 SUBHEAP *sub;
391 LIST_FOR_EACH_ENTRY( sub, &heap->subheap_list, SUBHEAP, entry )
392 if (((const char *)ptr >= (const char *)sub->base) &&
393 ((const char *)ptr < (const char *)sub->base + sub->size - sizeof(ARENA_INUSE)))
394 return sub;
395 return NULL;
399 /***********************************************************************
400 * HEAP_Commit
402 * Make sure the heap storage is committed for a given size in the specified arena.
404 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
406 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
407 SIZE_T size = (char *)ptr - (char *)subheap->base;
408 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
409 if (size > subheap->size) size = subheap->size;
410 if (size <= subheap->commitSize) return TRUE;
411 size -= subheap->commitSize;
412 ptr = (char *)subheap->base + subheap->commitSize;
413 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
414 &size, MEM_COMMIT, get_protection_type( subheap->heap->flags ) ))
416 WARN("Could not commit %08lx bytes at %p for heap %p\n",
417 size, ptr, subheap->heap );
418 return FALSE;
420 subheap->commitSize += size;
421 return TRUE;
425 /***********************************************************************
426 * HEAP_Decommit
428 * If possible, decommit the heap storage from (including) 'ptr'.
430 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
432 void *addr;
433 SIZE_T decommit_size;
434 SIZE_T size = (char *)ptr - (char *)subheap->base;
436 /* round to next block and add one full block */
437 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
438 if (size >= subheap->commitSize) return TRUE;
439 decommit_size = subheap->commitSize - size;
440 addr = (char *)subheap->base + size;
442 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
444 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
445 decommit_size, (char *)subheap->base + size, subheap->heap );
446 return FALSE;
448 subheap->commitSize -= decommit_size;
449 return TRUE;
453 /***********************************************************************
454 * HEAP_CreateFreeBlock
456 * Create a free block at a specified address. 'size' is the size of the
457 * whole block, including the new arena.
459 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
461 ARENA_FREE *pFree;
462 char *pEnd;
463 BOOL last;
465 /* Create a free arena */
466 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
467 pFree = (ARENA_FREE *)ptr;
468 pFree->magic = ARENA_FREE_MAGIC;
470 /* If debugging, erase the freed block content */
472 pEnd = (char *)ptr + size;
473 if (pEnd > (char *)subheap->base + subheap->commitSize)
474 pEnd = (char *)subheap->base + subheap->commitSize;
475 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
477 /* Check if next block is free also */
479 if (((char *)ptr + size < (char *)subheap->base + subheap->size) &&
480 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
482 /* Remove the next arena from the free list */
483 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
484 list_remove( &pNext->entry );
485 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
486 mark_block_free( pNext, sizeof(ARENA_FREE) );
489 /* Set the next block PREV_FREE flag and pointer */
491 last = ((char *)ptr + size >= (char *)subheap->base + subheap->size);
492 if (!last)
494 DWORD *pNext = (DWORD *)((char *)ptr + size);
495 *pNext |= ARENA_FLAG_PREV_FREE;
496 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
497 *((ARENA_FREE **)pNext - 1) = pFree;
500 /* Last, insert the new block into the free list */
502 pFree->size = size - sizeof(*pFree);
503 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
507 /***********************************************************************
508 * HEAP_MakeInUseBlockFree
510 * Turn an in-use block into a free block. Can also decommit the end of
511 * the heap, and possibly even free the sub-heap altogether.
513 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
515 ARENA_FREE *pFree;
516 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
518 /* Check if we can merge with previous block */
520 if (pArena->size & ARENA_FLAG_PREV_FREE)
522 pFree = *((ARENA_FREE **)pArena - 1);
523 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
524 /* Remove it from the free list */
525 list_remove( &pFree->entry );
527 else pFree = (ARENA_FREE *)pArena;
529 /* Create a free block */
531 HEAP_CreateFreeBlock( subheap, pFree, size );
532 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
533 if ((char *)pFree + size < (char *)subheap->base + subheap->size)
534 return; /* Not the last block, so nothing more to do */
536 /* Free the whole sub-heap if it's empty and not the original one */
538 if (((char *)pFree == (char *)subheap->base + subheap->headerSize) &&
539 (subheap != &subheap->heap->subheap))
541 SIZE_T size = 0;
542 void *addr = subheap->base;
543 /* Remove the free block from the list */
544 list_remove( &pFree->entry );
545 /* Remove the subheap from the list */
546 list_remove( &subheap->entry );
547 /* Free the memory */
548 subheap->magic = 0;
549 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
550 return;
553 /* Decommit the end of the heap */
555 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
559 /***********************************************************************
560 * HEAP_ShrinkBlock
562 * Shrink an in-use block.
564 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
566 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
568 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
569 (pArena->size & ARENA_SIZE_MASK) - size );
570 /* assign size plus previous arena flags */
571 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
573 else
575 /* Turn off PREV_FREE flag in next block */
576 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
577 if (pNext < (char *)subheap->base + subheap->size)
578 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
582 /***********************************************************************
583 * HEAP_InitSubHeap
585 static SUBHEAP *HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
586 SIZE_T commitSize, SIZE_T totalSize )
588 SUBHEAP *subheap;
589 FREE_LIST_ENTRY *pEntry;
590 int i;
592 /* Commit memory */
594 if (flags & HEAP_SHARED)
595 commitSize = totalSize; /* always commit everything in a shared heap */
596 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
597 &commitSize, MEM_COMMIT, get_protection_type( flags ) ))
599 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
600 return NULL;
603 if (heap)
605 /* If this is a secondary subheap, insert it into list */
607 subheap = (SUBHEAP *)address;
608 subheap->base = address;
609 subheap->heap = heap;
610 subheap->size = totalSize;
611 subheap->commitSize = commitSize;
612 subheap->magic = SUBHEAP_MAGIC;
613 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
614 list_add_head( &heap->subheap_list, &subheap->entry );
616 else
618 /* If this is a primary subheap, initialize main heap */
620 heap = (HEAP *)address;
621 heap->flags = flags;
622 heap->magic = HEAP_MAGIC;
623 list_init( &heap->subheap_list );
625 subheap = &heap->subheap;
626 subheap->base = address;
627 subheap->heap = heap;
628 subheap->size = totalSize;
629 subheap->commitSize = commitSize;
630 subheap->magic = SUBHEAP_MAGIC;
631 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
632 list_add_head( &heap->subheap_list, &subheap->entry );
634 /* Build the free lists */
636 list_init( &heap->freeList[0].arena.entry );
637 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
639 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
640 pEntry->arena.magic = ARENA_FREE_MAGIC;
641 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
644 /* Initialize critical section */
646 if (!processHeap) /* do it by hand to avoid memory allocations */
648 if(TRACE_ON(heap_poison))
649 TRACE_(heap_poison)("poisioning heap\n");
650 heap->critSection.DebugInfo = &process_heap_critsect_debug;
651 heap->critSection.LockCount = -1;
652 heap->critSection.RecursionCount = 0;
653 heap->critSection.OwningThread = 0;
654 heap->critSection.LockSemaphore = 0;
655 heap->critSection.SpinCount = 0;
656 process_heap_critsect_debug.CriticalSection = &heap->critSection;
658 else
660 RtlInitializeCriticalSection( &heap->critSection );
661 heap->critSection.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": HEAP.critSection");
664 if (flags & HEAP_SHARED)
666 /* let's assume that only one thread at a time will try to do this */
667 HANDLE sem = heap->critSection.LockSemaphore;
668 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
670 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
671 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
672 heap->critSection.LockSemaphore = sem;
673 RtlFreeHeap( processHeap, 0, heap->critSection.DebugInfo );
674 heap->critSection.DebugInfo = NULL;
678 /* Create the first free block */
680 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap->base + subheap->headerSize,
681 subheap->size - subheap->headerSize );
683 return subheap;
686 /***********************************************************************
687 * HEAP_CreateSubHeap
689 * Create a sub-heap of the given size.
690 * If heap == NULL, creates a main heap.
692 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
693 SIZE_T commitSize, SIZE_T totalSize )
695 LPVOID address = base;
696 SUBHEAP *ret;
698 /* round-up sizes on a 64K boundary */
699 totalSize = (totalSize + 0xffff) & 0xffff0000;
700 commitSize = (commitSize + 0xffff) & 0xffff0000;
701 if (!commitSize) commitSize = 0x10000;
702 if (totalSize < commitSize) totalSize = commitSize;
704 if (!address)
706 /* allocate the memory block */
707 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
708 MEM_RESERVE, get_protection_type( flags ) ))
710 WARN("Could not allocate %08lx bytes\n", totalSize );
711 return NULL;
715 /* Initialize subheap */
717 if (!(ret = HEAP_InitSubHeap( heap, address, flags, commitSize, totalSize )))
719 SIZE_T size = 0;
720 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
722 return ret;
726 /***********************************************************************
727 * HEAP_FindFreeBlock
729 * Find a free block at least as large as the requested size, and make sure
730 * the requested size is committed.
732 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
733 SUBHEAP **ppSubHeap )
735 SUBHEAP *subheap;
736 struct list *ptr;
737 SIZE_T total_size;
738 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
740 /* Find a suitable free list, and in it find a block large enough */
742 ptr = &pEntry->arena.entry;
743 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
745 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
746 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
747 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
748 if (arena_size >= size)
750 subheap = HEAP_FindSubHeap( heap, pArena );
751 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
752 *ppSubHeap = subheap;
753 return pArena;
757 /* If no block was found, attempt to grow the heap */
759 if (!(heap->flags & HEAP_GROWABLE))
761 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
762 return NULL;
764 /* make sure that we have a big enough size *committed* to fit another
765 * last free arena in !
766 * So just one heap struct, one first free arena which will eventually
767 * get used, and a second free arena that might get assigned all remaining
768 * free space in HEAP_ShrinkBlock() */
769 total_size = size + ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
770 if (total_size < size) return NULL; /* overflow */
772 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, total_size,
773 max( HEAP_DEF_SIZE, total_size ) )))
774 return NULL;
776 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
777 subheap, total_size, heap );
779 *ppSubHeap = subheap;
780 return (ARENA_FREE *)((char *)subheap->base + subheap->headerSize);
784 /***********************************************************************
785 * HEAP_IsValidArenaPtr
787 * Check that the pointer is inside the range possible for arenas.
789 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const ARENA_FREE *ptr )
791 int i;
792 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
793 if (!subheap) return FALSE;
794 if ((const char *)ptr >= (const char *)subheap->base + subheap->headerSize) return TRUE;
795 if (subheap != &heap->subheap) return FALSE;
796 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
797 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
798 return FALSE;
802 /***********************************************************************
803 * HEAP_ValidateFreeArena
805 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
807 ARENA_FREE *prev, *next;
808 char *heapEnd = (char *)subheap->base + subheap->size;
810 /* Check for unaligned pointers */
811 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
813 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
814 return FALSE;
817 /* Check magic number */
818 if (pArena->magic != ARENA_FREE_MAGIC)
820 ERR("Heap %p: invalid free arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
821 return FALSE;
823 /* Check size flags */
824 if (!(pArena->size & ARENA_FLAG_FREE) ||
825 (pArena->size & ARENA_FLAG_PREV_FREE))
827 ERR("Heap %p: bad flags %08x for free arena %p\n",
828 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
829 return FALSE;
831 /* Check arena size */
832 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
834 ERR("Heap %p: bad size %08x for free arena %p\n",
835 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
836 return FALSE;
838 /* Check that next pointer is valid */
839 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
840 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
842 ERR("Heap %p: bad next ptr %p for arena %p\n",
843 subheap->heap, next, pArena );
844 return FALSE;
846 /* Check that next arena is free */
847 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
849 ERR("Heap %p: next arena %p invalid for %p\n",
850 subheap->heap, next, pArena );
851 return FALSE;
853 /* Check that prev pointer is valid */
854 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
855 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
857 ERR("Heap %p: bad prev ptr %p for arena %p\n",
858 subheap->heap, prev, pArena );
859 return FALSE;
861 /* Check that prev arena is free */
862 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
864 /* this often means that the prev arena got overwritten
865 * by a memory write before that prev arena */
866 ERR("Heap %p: prev arena %p invalid for %p\n",
867 subheap->heap, prev, pArena );
868 return FALSE;
870 /* Check that next block has PREV_FREE flag */
871 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
873 if (!(*(DWORD *)((char *)(pArena + 1) +
874 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
876 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
877 subheap->heap, pArena );
878 return FALSE;
880 /* Check next block back pointer */
881 if (*((ARENA_FREE **)((char *)(pArena + 1) +
882 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
884 ERR("Heap %p: arena %p has wrong back ptr %p\n",
885 subheap->heap, pArena,
886 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
887 return FALSE;
890 return TRUE;
894 /***********************************************************************
895 * HEAP_ValidateInUseArena
897 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
899 const char *heapEnd = (const char *)subheap->base + subheap->size;
901 /* Check for unaligned pointers */
902 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
904 if ( quiet == NOISY )
906 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
907 if ( TRACE_ON(heap) )
908 HEAP_Dump( subheap->heap );
910 else if ( WARN_ON(heap) )
912 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
913 if ( TRACE_ON(heap) )
914 HEAP_Dump( subheap->heap );
916 return FALSE;
919 /* Check magic number */
920 if (pArena->magic != ARENA_INUSE_MAGIC)
922 if (quiet == NOISY) {
923 ERR("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
924 if (TRACE_ON(heap))
925 HEAP_Dump( subheap->heap );
926 } else if (WARN_ON(heap)) {
927 WARN("Heap %p: invalid in-use arena magic %08x for %p\n", subheap->heap, pArena->magic, pArena );
928 if (TRACE_ON(heap))
929 HEAP_Dump( subheap->heap );
931 return FALSE;
933 /* Check size flags */
934 if (pArena->size & ARENA_FLAG_FREE)
936 ERR("Heap %p: bad flags %08x for in-use arena %p\n",
937 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
938 return FALSE;
940 /* Check arena size */
941 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
943 ERR("Heap %p: bad size %08x for in-use arena %p\n",
944 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
945 return FALSE;
947 /* Check next arena PREV_FREE flag */
948 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
949 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
951 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
952 subheap->heap, pArena );
953 return FALSE;
955 /* Check prev free arena */
956 if (pArena->size & ARENA_FLAG_PREV_FREE)
958 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
959 /* Check prev pointer */
960 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
962 ERR("Heap %p: bad back ptr %p for arena %p\n",
963 subheap->heap, pPrev, pArena );
964 return FALSE;
966 /* Check that prev arena is free */
967 if (!(pPrev->size & ARENA_FLAG_FREE) ||
968 (pPrev->magic != ARENA_FREE_MAGIC))
970 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
971 subheap->heap, pPrev, pArena );
972 return FALSE;
974 /* Check that prev arena is really the previous block */
975 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
977 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
978 subheap->heap, pPrev, pArena );
979 return FALSE;
982 return TRUE;
986 /***********************************************************************
987 * HEAP_IsRealArena [Internal]
988 * Validates a block is a valid arena.
990 * RETURNS
991 * TRUE: Success
992 * FALSE: Failure
994 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
995 DWORD flags, /* [in] Bit flags that control access during operation */
996 LPCVOID block, /* [in] Optional pointer to memory block to validate */
997 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
998 * does not complain */
1000 SUBHEAP *subheap;
1001 BOOL ret = TRUE;
1003 flags &= HEAP_NO_SERIALIZE;
1004 flags |= heapPtr->flags;
1005 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1006 if (!(flags & HEAP_NO_SERIALIZE))
1007 RtlEnterCriticalSection( &heapPtr->critSection );
1009 if (block) /* only check this single memory block */
1011 const ARENA_INUSE *arena = (const ARENA_INUSE *)block - 1;
1013 if (!(subheap = HEAP_FindSubHeap( heapPtr, arena )) ||
1014 ((const char *)arena < (char *)subheap->base + subheap->headerSize))
1016 if (quiet == NOISY)
1017 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
1018 else if (WARN_ON(heap))
1019 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
1020 ret = FALSE;
1021 } else
1022 ret = HEAP_ValidateInUseArena( subheap, arena, quiet );
1024 if (!(flags & HEAP_NO_SERIALIZE))
1025 RtlLeaveCriticalSection( &heapPtr->critSection );
1026 return ret;
1029 LIST_FOR_EACH_ENTRY( subheap, &heapPtr->subheap_list, SUBHEAP, entry )
1031 char *ptr = (char *)subheap->base + subheap->headerSize;
1032 while (ptr < (char *)subheap->base + subheap->size)
1034 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1036 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1037 ret = FALSE;
1038 break;
1040 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1042 else
1044 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1045 ret = FALSE;
1046 break;
1048 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1051 if (!ret) break;
1054 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1055 return ret;
1059 /***********************************************************************
1060 * RtlCreateHeap (NTDLL.@)
1062 * Create a new Heap.
1064 * PARAMS
1065 * flags [I] HEAP_ flags from "winnt.h"
1066 * addr [I] Desired base address
1067 * totalSize [I] Total size of the heap, or 0 for a growable heap
1068 * commitSize [I] Amount of heap space to commit
1069 * unknown [I] Not yet understood
1070 * definition [I] Heap definition
1072 * RETURNS
1073 * Success: A HANDLE to the newly created heap.
1074 * Failure: a NULL HANDLE.
1076 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1077 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1079 SUBHEAP *subheap;
1081 /* Allocate the heap block */
1083 if (!totalSize)
1085 totalSize = HEAP_DEF_SIZE;
1086 flags |= HEAP_GROWABLE;
1089 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1091 /* link it into the per-process heap list */
1092 if (processHeap)
1094 HEAP *heapPtr = subheap->heap;
1095 RtlEnterCriticalSection( &processHeap->critSection );
1096 list_add_head( &processHeap->entry, &heapPtr->entry );
1097 RtlLeaveCriticalSection( &processHeap->critSection );
1099 else
1101 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1102 list_init( &processHeap->entry );
1103 /* make sure structure alignment is correct */
1104 assert( (ULONG_PTR)&processHeap->freeList % ALIGNMENT == 0 );
1107 return (HANDLE)subheap->heap;
1111 /***********************************************************************
1112 * RtlDestroyHeap (NTDLL.@)
1114 * Destroy a Heap created with RtlCreateHeap().
1116 * PARAMS
1117 * heap [I] Heap to destroy.
1119 * RETURNS
1120 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1121 * Failure: The Heap handle, if heap is the process heap.
1123 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1125 HEAP *heapPtr = HEAP_GetPtr( heap );
1126 SUBHEAP *subheap, *next;
1127 SIZE_T size;
1128 void *addr;
1130 TRACE("%p\n", heap );
1131 if (!heapPtr) return heap;
1133 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1135 /* remove it from the per-process list */
1136 RtlEnterCriticalSection( &processHeap->critSection );
1137 list_remove( &heapPtr->entry );
1138 RtlLeaveCriticalSection( &processHeap->critSection );
1140 heapPtr->critSection.DebugInfo->Spare[0] = 0;
1141 RtlDeleteCriticalSection( &heapPtr->critSection );
1143 LIST_FOR_EACH_ENTRY_SAFE( subheap, next, &heapPtr->subheap_list, SUBHEAP, entry )
1145 if (subheap == &heapPtr->subheap) continue; /* do this one last */
1146 list_remove( &subheap->entry );
1147 size = 0;
1148 addr = subheap->base;
1149 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1151 size = 0;
1152 addr = heapPtr->subheap.base;
1153 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1154 return 0;
1158 /***********************************************************************
1159 * RtlAllocateHeap (NTDLL.@)
1161 * Allocate a memory block from a Heap.
1163 * PARAMS
1164 * heap [I] Heap to allocate block from
1165 * flags [I] HEAP_ flags from "winnt.h"
1166 * size [I] Size of the memory block to allocate
1168 * RETURNS
1169 * Success: A pointer to the newly allocated block
1170 * Failure: NULL.
1172 * NOTES
1173 * This call does not SetLastError().
1175 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1177 ARENA_FREE *pArena;
1178 ARENA_INUSE *pInUse;
1179 SUBHEAP *subheap;
1180 HEAP *heapPtr = HEAP_GetPtr( heap );
1181 SIZE_T rounded_size;
1183 /* Validate the parameters */
1185 if (!heapPtr) return NULL;
1186 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1187 flags |= heapPtr->flags;
1188 rounded_size = ROUND_SIZE(size);
1189 if (rounded_size < size) /* overflow */
1191 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1192 return NULL;
1194 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1196 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1197 /* Locate a suitable free block */
1199 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1201 TRACE("(%p,%08x,%08lx): returning NULL\n",
1202 heap, flags, size );
1203 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1204 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1205 return NULL;
1208 /* Remove the arena from the free list */
1210 list_remove( &pArena->entry );
1212 /* Build the in-use arena */
1214 pInUse = (ARENA_INUSE *)pArena;
1216 /* in-use arena is smaller than free arena,
1217 * so we have to add the difference to the size */
1218 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1219 pInUse->magic = ARENA_INUSE_MAGIC;
1221 /* Shrink the block */
1223 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1224 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1226 notify_alloc( pInUse + 1, size, flags & HEAP_ZERO_MEMORY );
1228 if (flags & HEAP_ZERO_MEMORY)
1229 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1230 else
1231 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1233 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1235 TRACE("(%p,%08x,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1236 return (LPVOID)(pInUse + 1);
1240 /***********************************************************************
1241 * RtlFreeHeap (NTDLL.@)
1243 * Free a memory block allocated with RtlAllocateHeap().
1245 * PARAMS
1246 * heap [I] Heap that block was allocated from
1247 * flags [I] HEAP_ flags from "winnt.h"
1248 * ptr [I] Block to free
1250 * RETURNS
1251 * Success: TRUE, if ptr is NULL or was freed successfully.
1252 * Failure: FALSE.
1254 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1256 ARENA_INUSE *pInUse;
1257 SUBHEAP *subheap;
1258 HEAP *heapPtr;
1260 /* Validate the parameters */
1262 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1264 heapPtr = HEAP_GetPtr( heap );
1265 if (!heapPtr)
1267 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1268 return FALSE;
1271 flags &= HEAP_NO_SERIALIZE;
1272 flags |= heapPtr->flags;
1273 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1275 /* Some sanity checks */
1277 pInUse = (ARENA_INUSE *)ptr - 1;
1278 if (!(subheap = HEAP_FindSubHeap( heapPtr, pInUse ))) goto error;
1279 if ((char *)pInUse < (char *)subheap->base + subheap->headerSize) goto error;
1280 if (!HEAP_ValidateInUseArena( subheap, pInUse, QUIET )) goto error;
1282 /* Turn the block into a free block */
1284 notify_free( ptr );
1286 HEAP_MakeInUseBlockFree( subheap, pInUse );
1288 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1290 TRACE("(%p,%08x,%p): returning TRUE\n", heap, flags, ptr );
1291 return TRUE;
1293 error:
1294 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1295 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1296 TRACE("(%p,%08x,%p): returning FALSE\n", heap, flags, ptr );
1297 return FALSE;
1301 /***********************************************************************
1302 * RtlReAllocateHeap (NTDLL.@)
1304 * Change the size of a memory block allocated with RtlAllocateHeap().
1306 * PARAMS
1307 * heap [I] Heap that block was allocated from
1308 * flags [I] HEAP_ flags from "winnt.h"
1309 * ptr [I] Block to resize
1310 * size [I] Size of the memory block to allocate
1312 * RETURNS
1313 * Success: A pointer to the resized block (which may be different).
1314 * Failure: NULL.
1316 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1318 ARENA_INUSE *pArena;
1319 HEAP *heapPtr;
1320 SUBHEAP *subheap;
1321 SIZE_T oldSize, rounded_size;
1323 if (!ptr) return NULL;
1324 if (!(heapPtr = HEAP_GetPtr( heap )))
1326 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1327 return NULL;
1330 /* Validate the parameters */
1332 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1333 HEAP_REALLOC_IN_PLACE_ONLY;
1334 flags |= heapPtr->flags;
1335 rounded_size = ROUND_SIZE(size);
1336 if (rounded_size < size) /* overflow */
1338 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1339 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1340 return NULL;
1342 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1344 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1346 pArena = (ARENA_INUSE *)ptr - 1;
1347 if (!(subheap = HEAP_FindSubHeap( heapPtr, pArena ))) goto error;
1348 if ((char *)pArena < (char *)subheap->base + subheap->headerSize) goto error;
1349 if (!HEAP_ValidateInUseArena( subheap, pArena, QUIET )) goto error;
1351 /* Check if we need to grow the block */
1353 oldSize = (pArena->size & ARENA_SIZE_MASK);
1354 if (rounded_size > oldSize)
1356 char *pNext = (char *)(pArena + 1) + oldSize;
1357 if ((pNext < (char *)subheap->base + subheap->size) &&
1358 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1359 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1361 /* The next block is free and large enough */
1362 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1363 list_remove( &pFree->entry );
1364 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1365 if (!HEAP_Commit( subheap, pArena, rounded_size ))
1367 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1368 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1369 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1370 return NULL;
1372 notify_free( pArena + 1 );
1373 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1374 notify_alloc( pArena + 1, size, FALSE );
1375 /* FIXME: this is wrong as we may lose old VBits settings */
1376 mark_block_initialized( pArena + 1, oldSize );
1378 else /* Do it the hard way */
1380 ARENA_FREE *pNew;
1381 ARENA_INUSE *pInUse;
1382 SUBHEAP *newsubheap;
1384 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1385 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1387 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1388 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1389 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1390 return NULL;
1393 /* Build the in-use arena */
1395 list_remove( &pNew->entry );
1396 pInUse = (ARENA_INUSE *)pNew;
1397 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1398 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1399 pInUse->magic = ARENA_INUSE_MAGIC;
1400 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1401 mark_block_initialized( pInUse + 1, oldSize );
1402 notify_alloc( pInUse + 1, size, FALSE );
1403 memcpy( pInUse + 1, pArena + 1, oldSize );
1405 /* Free the previous block */
1407 notify_free( pArena + 1 );
1408 HEAP_MakeInUseBlockFree( subheap, pArena );
1409 subheap = newsubheap;
1410 pArena = pInUse;
1413 else
1415 /* Shrink the block */
1416 notify_free( pArena + 1 );
1417 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1418 notify_alloc( pArena + 1, size, FALSE );
1419 /* FIXME: this is wrong as we may lose old VBits settings */
1420 mark_block_initialized( pArena + 1, size );
1423 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1425 /* Clear the extra bytes if needed */
1427 if (rounded_size > oldSize)
1429 if (flags & HEAP_ZERO_MEMORY)
1430 clear_block( (char *)(pArena + 1) + oldSize,
1431 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1432 else
1433 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1434 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1437 /* Return the new arena */
1439 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1441 TRACE("(%p,%08x,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1442 return (LPVOID)(pArena + 1);
1444 error:
1445 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1446 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1447 TRACE("(%p,%08x,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1448 return NULL;
1452 /***********************************************************************
1453 * RtlCompactHeap (NTDLL.@)
1455 * Compact the free space in a Heap.
1457 * PARAMS
1458 * heap [I] Heap that block was allocated from
1459 * flags [I] HEAP_ flags from "winnt.h"
1461 * RETURNS
1462 * The number of bytes compacted.
1464 * NOTES
1465 * This function is a harmless stub.
1467 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1469 static BOOL reported;
1470 if (!reported++) FIXME( "(%p, 0x%x) stub\n", heap, flags );
1471 return 0;
1475 /***********************************************************************
1476 * RtlLockHeap (NTDLL.@)
1478 * Lock a Heap.
1480 * PARAMS
1481 * heap [I] Heap to lock
1483 * RETURNS
1484 * Success: TRUE. The Heap is locked.
1485 * Failure: FALSE, if heap is invalid.
1487 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1489 HEAP *heapPtr = HEAP_GetPtr( heap );
1490 if (!heapPtr) return FALSE;
1491 RtlEnterCriticalSection( &heapPtr->critSection );
1492 return TRUE;
1496 /***********************************************************************
1497 * RtlUnlockHeap (NTDLL.@)
1499 * Unlock a Heap.
1501 * PARAMS
1502 * heap [I] Heap to unlock
1504 * RETURNS
1505 * Success: TRUE. The Heap is unlocked.
1506 * Failure: FALSE, if heap is invalid.
1508 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1510 HEAP *heapPtr = HEAP_GetPtr( heap );
1511 if (!heapPtr) return FALSE;
1512 RtlLeaveCriticalSection( &heapPtr->critSection );
1513 return TRUE;
1517 /***********************************************************************
1518 * RtlSizeHeap (NTDLL.@)
1520 * Get the actual size of a memory block allocated from a Heap.
1522 * PARAMS
1523 * heap [I] Heap that block was allocated from
1524 * flags [I] HEAP_ flags from "winnt.h"
1525 * ptr [I] Block to get the size of
1527 * RETURNS
1528 * Success: The size of the block.
1529 * Failure: -1, heap or ptr are invalid.
1531 * NOTES
1532 * The size may be bigger than what was passed to RtlAllocateHeap().
1534 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, const void *ptr )
1536 SIZE_T ret;
1537 HEAP *heapPtr = HEAP_GetPtr( heap );
1539 if (!heapPtr)
1541 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1542 return ~0UL;
1544 flags &= HEAP_NO_SERIALIZE;
1545 flags |= heapPtr->flags;
1546 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1547 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1549 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1550 ret = ~0UL;
1552 else
1554 const ARENA_INUSE *pArena = (const ARENA_INUSE *)ptr - 1;
1555 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1557 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1559 TRACE("(%p,%08x,%p): returning %08lx\n", heap, flags, ptr, ret );
1560 return ret;
1564 /***********************************************************************
1565 * RtlValidateHeap (NTDLL.@)
1567 * Determine if a block is a valid allocation from a heap.
1569 * PARAMS
1570 * heap [I] Heap that block was allocated from
1571 * flags [I] HEAP_ flags from "winnt.h"
1572 * ptr [I] Block to check
1574 * RETURNS
1575 * Success: TRUE. The block was allocated from heap.
1576 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1578 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1580 HEAP *heapPtr = HEAP_GetPtr( heap );
1581 if (!heapPtr) return FALSE;
1582 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1586 /***********************************************************************
1587 * RtlWalkHeap (NTDLL.@)
1589 * FIXME
1590 * The PROCESS_HEAP_ENTRY flag values seem different between this
1591 * function and HeapWalk(). To be checked.
1593 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1595 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1596 HEAP *heapPtr = HEAP_GetPtr(heap);
1597 SUBHEAP *sub, *currentheap = NULL;
1598 NTSTATUS ret;
1599 char *ptr;
1600 int region_index = 0;
1602 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1604 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1606 /* set ptr to the next arena to be examined */
1608 if (!entry->lpData) /* first call (init) ? */
1610 TRACE("begin walking of heap %p.\n", heap);
1611 currentheap = &heapPtr->subheap;
1612 ptr = (char*)currentheap->base + currentheap->headerSize;
1614 else
1616 ptr = entry->lpData;
1617 LIST_FOR_EACH_ENTRY( sub, &heapPtr->subheap_list, SUBHEAP, entry )
1619 if (((char *)ptr >= (char *)sub->base) &&
1620 ((char *)ptr < (char *)sub->base + sub->size))
1622 currentheap = sub;
1623 break;
1625 region_index++;
1627 if (currentheap == NULL)
1629 ERR("no matching subheap found, shouldn't happen !\n");
1630 ret = STATUS_NO_MORE_ENTRIES;
1631 goto HW_end;
1634 if (((ARENA_INUSE *)ptr - 1)->magic == ARENA_INUSE_MAGIC)
1636 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1637 ptr += pArena->size & ARENA_SIZE_MASK;
1639 else if (((ARENA_FREE *)ptr - 1)->magic == ARENA_FREE_MAGIC)
1641 ARENA_FREE *pArena = (ARENA_FREE *)ptr - 1;
1642 ptr += pArena->size & ARENA_SIZE_MASK;
1644 else
1645 ptr += entry->cbData; /* point to next arena */
1647 if (ptr > (char *)currentheap->base + currentheap->size - 1)
1648 { /* proceed with next subheap */
1649 struct list *next = list_next( &heapPtr->subheap_list, &currentheap->entry );
1650 if (!next)
1651 { /* successfully finished */
1652 TRACE("end reached.\n");
1653 ret = STATUS_NO_MORE_ENTRIES;
1654 goto HW_end;
1656 currentheap = LIST_ENTRY( next, SUBHEAP, entry );
1657 ptr = (char *)currentheap->base + currentheap->headerSize;
1661 entry->wFlags = 0;
1662 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1664 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1666 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1668 entry->lpData = pArena + 1;
1669 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1670 entry->cbOverhead = sizeof(ARENA_FREE);
1671 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1673 else
1675 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1677 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1679 entry->lpData = pArena + 1;
1680 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1681 entry->cbOverhead = sizeof(ARENA_INUSE);
1682 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1683 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1684 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1687 entry->iRegionIndex = region_index;
1689 /* first element of heap ? */
1690 if (ptr == (char *)currentheap->base + currentheap->headerSize)
1692 entry->wFlags |= PROCESS_HEAP_REGION;
1693 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1694 entry->u.Region.dwUnCommittedSize =
1695 currentheap->size - currentheap->commitSize;
1696 entry->u.Region.lpFirstBlock = /* first valid block */
1697 (char *)currentheap->base + currentheap->headerSize;
1698 entry->u.Region.lpLastBlock = /* first invalid block */
1699 (char *)currentheap->base + currentheap->size;
1701 ret = STATUS_SUCCESS;
1702 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1704 HW_end:
1705 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1706 return ret;
1710 /***********************************************************************
1711 * RtlGetProcessHeaps (NTDLL.@)
1713 * Get the Heaps belonging to the current process.
1715 * PARAMS
1716 * count [I] size of heaps
1717 * heaps [O] Destination array for heap HANDLE's
1719 * RETURNS
1720 * Success: The number of Heaps allocated by the process.
1721 * Failure: 0.
1723 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1725 ULONG total = 1; /* main heap */
1726 struct list *ptr;
1728 RtlEnterCriticalSection( &processHeap->critSection );
1729 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1730 if (total <= count)
1732 *heaps++ = processHeap;
1733 LIST_FOR_EACH( ptr, &processHeap->entry )
1734 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1736 RtlLeaveCriticalSection( &processHeap->critSection );
1737 return total;