Fix gcc 4 warnings.
[wine/multimedia.git] / dlls / ntdll / heap.c
blob66d1a89173978febdf98fed45e6b88b46f3806bd
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 #include "windef.h"
37 #include "winternl.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 based on what Pietrek describes in his
47 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
48 * the same, but could be easily adapted if it turns out some programs
49 * require it.
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 #define HEAP_MIN_DATA_SIZE 16
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 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
92 /* Max size of the blocks on the free lists */
93 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
95 0x20, 0x80, 0x200, ~0UL
98 typedef struct
100 ARENA_FREE arena;
101 } FREE_LIST_ENTRY;
103 struct tagHEAP;
105 typedef struct tagSUBHEAP
107 DWORD size; /* Size of the whole sub-heap */
108 DWORD commitSize; /* Committed size of the sub-heap */
109 DWORD headerSize; /* Size of the heap header */
110 struct tagSUBHEAP *next; /* Next sub-heap */
111 struct tagHEAP *heap; /* Main heap structure */
112 DWORD magic; /* Magic number */
113 } SUBHEAP;
115 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
117 typedef struct tagHEAP
119 SUBHEAP subheap; /* First sub-heap */
120 struct list entry; /* Entry in process heap list */
121 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
122 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
123 DWORD flags; /* Heap flags */
124 DWORD magic; /* Magic number */
125 } HEAP;
127 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
129 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
130 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
132 static HEAP *processHeap; /* main process heap */
134 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
136 /* mark a block of memory as free for debugging purposes */
137 static inline void mark_block_free( void *ptr, SIZE_T size )
139 if (TRACE_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
140 #ifdef VALGRIND_MAKE_NOACCESS
141 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
142 #endif
145 /* mark a block of memory as initialized for debugging purposes */
146 static inline void mark_block_initialized( void *ptr, SIZE_T size )
148 #ifdef VALGRIND_MAKE_READABLE
149 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
150 #endif
153 /* mark a block of memory as uninitialized for debugging purposes */
154 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
156 #ifdef VALGRIND_MAKE_WRITABLE
157 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
158 #endif
159 if (TRACE_ON(heap))
161 memset( ptr, ARENA_INUSE_FILLER, size );
162 #ifdef VALGRIND_MAKE_WRITABLE
163 /* make it uninitialized to valgrind again */
164 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
165 #endif
169 /* clear contents of a block of memory */
170 static inline void clear_block( void *ptr, SIZE_T size )
172 mark_block_initialized( ptr, size );
173 memset( ptr, 0, size );
176 /* locate a free list entry of the appropriate size */
177 /* size is the size of the whole block including the arena header */
178 static inline unsigned int get_freelist_index( SIZE_T size )
180 unsigned int i;
182 size -= sizeof(ARENA_FREE);
183 for (i = 0; i < HEAP_NB_FREE_LISTS - 1; i++) if (size <= HEAP_freeListSizes[i]) break;
184 return i;
187 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
189 0, 0, NULL, /* will be set later */
190 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
191 0, 0, { (DWORD_PTR)(__FILE__ ": main process heap section") }
195 /***********************************************************************
196 * HEAP_Dump
198 static void HEAP_Dump( HEAP *heap )
200 int i;
201 SUBHEAP *subheap;
202 char *ptr;
204 DPRINTF( "Heap: %p\n", heap );
205 DPRINTF( "Next: %p Sub-heaps: %p",
206 LIST_ENTRY( heap->entry.next, HEAP, entry ), &heap->subheap );
207 subheap = &heap->subheap;
208 while (subheap->next)
210 DPRINTF( " -> %p", subheap->next );
211 subheap = subheap->next;
214 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
215 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
216 DPRINTF( "%p free %08lx prev=%p next=%p\n",
217 &heap->freeList[i].arena, HEAP_freeListSizes[i],
218 LIST_ENTRY( heap->freeList[i].arena.entry.prev, ARENA_FREE, entry ),
219 LIST_ENTRY( heap->freeList[i].arena.entry.next, ARENA_FREE, entry ));
221 subheap = &heap->subheap;
222 while (subheap)
224 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
225 DPRINTF( "\n\nSub-heap %p: size=%08lx committed=%08lx\n",
226 subheap, subheap->size, subheap->commitSize );
228 DPRINTF( "\n Block Stat Size Id\n" );
229 ptr = (char*)subheap + subheap->headerSize;
230 while (ptr < (char *)subheap + subheap->size)
232 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
234 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
235 DPRINTF( "%p free %08lx prev=%p next=%p\n",
236 pArena, pArena->size & ARENA_SIZE_MASK,
237 LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry ),
238 LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry ) );
239 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
240 arenaSize += sizeof(ARENA_FREE);
241 freeSize += pArena->size & ARENA_SIZE_MASK;
243 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
245 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
246 DPRINTF( "%p Used %08lx back=%p\n",
247 pArena, pArena->size & ARENA_SIZE_MASK, *((ARENA_FREE **)pArena - 1) );
248 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
249 arenaSize += sizeof(ARENA_INUSE);
250 usedSize += pArena->size & ARENA_SIZE_MASK;
252 else
254 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
255 DPRINTF( "%p used %08lx\n", pArena, pArena->size & ARENA_SIZE_MASK );
256 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
257 arenaSize += sizeof(ARENA_INUSE);
258 usedSize += pArena->size & ARENA_SIZE_MASK;
261 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
262 subheap->size, subheap->commitSize, freeSize, usedSize,
263 arenaSize, (arenaSize * 100) / subheap->size );
264 subheap = subheap->next;
269 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
271 WORD rem_flags;
272 TRACE( "Dumping entry %p\n", entry );
273 TRACE( "lpData\t\t: %p\n", entry->lpData );
274 TRACE( "cbData\t\t: %08lx\n", entry->cbData);
275 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
276 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
277 TRACE( "WFlags\t\t: ");
278 if (entry->wFlags & PROCESS_HEAP_REGION)
279 TRACE( "PROCESS_HEAP_REGION ");
280 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
281 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
282 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
283 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
284 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
285 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
286 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
287 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
288 rem_flags = entry->wFlags &
289 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
290 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
291 PROCESS_HEAP_ENTRY_DDESHARE);
292 if (rem_flags)
293 TRACE( "Unknown %08x", rem_flags);
294 TRACE( "\n");
295 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
296 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
298 /* Treat as block */
299 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
301 if (entry->wFlags & PROCESS_HEAP_REGION)
303 TRACE( "Region.dwCommittedSize\t:%08lx\n",entry->u.Region.dwCommittedSize);
304 TRACE( "Region.dwUnCommittedSize\t:%08lx\n",entry->u.Region.dwUnCommittedSize);
305 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
306 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
310 /***********************************************************************
311 * HEAP_GetPtr
312 * RETURNS
313 * Pointer to the heap
314 * NULL: Failure
316 static HEAP *HEAP_GetPtr(
317 HANDLE heap /* [in] Handle to the heap */
319 HEAP *heapPtr = (HEAP *)heap;
320 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
322 ERR("Invalid heap %p!\n", heap );
323 return NULL;
325 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
327 HEAP_Dump( heapPtr );
328 assert( FALSE );
329 return NULL;
331 return heapPtr;
335 /***********************************************************************
336 * HEAP_InsertFreeBlock
338 * Insert a free block into the free list.
340 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
342 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( pArena->size + sizeof(*pArena) );
343 if (last)
345 /* insert at end of free list, i.e. before the next free list entry */
346 pEntry++;
347 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
348 list_add_before( &pEntry->arena.entry, &pArena->entry );
350 else
352 /* insert at head of free list */
353 list_add_after( &pEntry->arena.entry, &pArena->entry );
355 pArena->size |= ARENA_FLAG_FREE;
359 /***********************************************************************
360 * HEAP_FindSubHeap
361 * Find the sub-heap containing a given address.
363 * RETURNS
364 * Pointer: Success
365 * NULL: Failure
367 static SUBHEAP *HEAP_FindSubHeap(
368 const HEAP *heap, /* [in] Heap pointer */
369 LPCVOID ptr /* [in] Address */
371 const SUBHEAP *sub = &heap->subheap;
372 while (sub)
374 if (((const char *)ptr >= (const char *)sub) &&
375 ((const char *)ptr < (const char *)sub + sub->size)) return (SUBHEAP*)sub;
376 sub = sub->next;
378 return NULL;
382 /***********************************************************************
383 * HEAP_Commit
385 * Make sure the heap storage is committed for a given size in the specified arena.
387 static inline BOOL HEAP_Commit( SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T data_size )
389 void *ptr = (char *)(pArena + 1) + data_size + sizeof(ARENA_FREE);
390 SIZE_T size = (char *)ptr - (char *)subheap;
391 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
392 if (size > subheap->size) size = subheap->size;
393 if (size <= subheap->commitSize) return TRUE;
394 size -= subheap->commitSize;
395 ptr = (char *)subheap + subheap->commitSize;
396 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
397 &size, MEM_COMMIT, PAGE_READWRITE ))
399 WARN("Could not commit %08lx bytes at %p for heap %p\n",
400 size, ptr, subheap->heap );
401 return FALSE;
403 subheap->commitSize += size;
404 return TRUE;
408 /***********************************************************************
409 * HEAP_Decommit
411 * If possible, decommit the heap storage from (including) 'ptr'.
413 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
415 void *addr;
416 SIZE_T decommit_size;
417 SIZE_T size = (char *)ptr - (char *)subheap;
419 /* round to next block and add one full block */
420 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
421 if (size >= subheap->commitSize) return TRUE;
422 decommit_size = subheap->commitSize - size;
423 addr = (char *)subheap + size;
425 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
427 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
428 decommit_size, (char *)subheap + size, subheap->heap );
429 return FALSE;
431 subheap->commitSize -= decommit_size;
432 return TRUE;
436 /***********************************************************************
437 * HEAP_CreateFreeBlock
439 * Create a free block at a specified address. 'size' is the size of the
440 * whole block, including the new arena.
442 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
444 ARENA_FREE *pFree;
445 char *pEnd;
446 BOOL last;
448 /* Create a free arena */
449 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
450 pFree = (ARENA_FREE *)ptr;
451 pFree->magic = ARENA_FREE_MAGIC;
453 /* If debugging, erase the freed block content */
455 pEnd = (char *)ptr + size;
456 if (pEnd > (char *)subheap + subheap->commitSize) pEnd = (char *)subheap + subheap->commitSize;
457 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
459 /* Check if next block is free also */
461 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
462 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
464 /* Remove the next arena from the free list */
465 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
466 list_remove( &pNext->entry );
467 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
468 mark_block_free( pNext, sizeof(ARENA_FREE) );
471 /* Set the next block PREV_FREE flag and pointer */
473 last = ((char *)ptr + size >= (char *)subheap + subheap->size);
474 if (!last)
476 DWORD *pNext = (DWORD *)((char *)ptr + size);
477 *pNext |= ARENA_FLAG_PREV_FREE;
478 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
479 *((ARENA_FREE **)pNext - 1) = pFree;
482 /* Last, insert the new block into the free list */
484 pFree->size = size - sizeof(*pFree);
485 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
489 /***********************************************************************
490 * HEAP_MakeInUseBlockFree
492 * Turn an in-use block into a free block. Can also decommit the end of
493 * the heap, and possibly even free the sub-heap altogether.
495 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
497 ARENA_FREE *pFree;
498 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
500 /* Check if we can merge with previous block */
502 if (pArena->size & ARENA_FLAG_PREV_FREE)
504 pFree = *((ARENA_FREE **)pArena - 1);
505 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
506 /* Remove it from the free list */
507 list_remove( &pFree->entry );
509 else pFree = (ARENA_FREE *)pArena;
511 /* Create a free block */
513 HEAP_CreateFreeBlock( subheap, pFree, size );
514 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
515 if ((char *)pFree + size < (char *)subheap + subheap->size)
516 return; /* Not the last block, so nothing more to do */
518 /* Free the whole sub-heap if it's empty and not the original one */
520 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
521 (subheap != &subheap->heap->subheap))
523 SIZE_T size = 0;
524 SUBHEAP *pPrev = &subheap->heap->subheap;
525 /* Remove the free block from the list */
526 list_remove( &pFree->entry );
527 /* Remove the subheap from the list */
528 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
529 if (pPrev) pPrev->next = subheap->next;
530 /* Free the memory */
531 subheap->magic = 0;
532 NtFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap, &size, MEM_RELEASE );
533 return;
536 /* Decommit the end of the heap */
538 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
542 /***********************************************************************
543 * HEAP_ShrinkBlock
545 * Shrink an in-use block.
547 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
549 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_SHRINK_SIZE)
551 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
552 (pArena->size & ARENA_SIZE_MASK) - size );
553 /* assign size plus previous arena flags */
554 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
556 else
558 /* Turn off PREV_FREE flag in next block */
559 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
560 if (pNext < (char *)subheap + subheap->size)
561 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
565 /***********************************************************************
566 * HEAP_InitSubHeap
568 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
569 SIZE_T commitSize, SIZE_T totalSize )
571 SUBHEAP *subheap;
572 FREE_LIST_ENTRY *pEntry;
573 int i;
575 /* Commit memory */
577 if (flags & HEAP_SHARED)
578 commitSize = totalSize; /* always commit everything in a shared heap */
579 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
580 &commitSize, MEM_COMMIT, PAGE_READWRITE ))
582 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
583 return FALSE;
586 /* Fill the sub-heap structure */
588 subheap = (SUBHEAP *)address;
589 subheap->heap = heap;
590 subheap->size = totalSize;
591 subheap->commitSize = commitSize;
592 subheap->magic = SUBHEAP_MAGIC;
594 if ( subheap != (SUBHEAP *)heap )
596 /* If this is a secondary subheap, insert it into list */
598 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
599 subheap->next = heap->subheap.next;
600 heap->subheap.next = subheap;
602 else
604 /* If this is a primary subheap, initialize main heap */
606 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
607 subheap->next = NULL;
608 heap->flags = flags;
609 heap->magic = HEAP_MAGIC;
611 /* Build the free lists */
613 list_init( &heap->freeList[0].arena.entry );
614 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
616 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
617 pEntry->arena.magic = ARENA_FREE_MAGIC;
618 if (i) list_add_after( &pEntry[-1].arena.entry, &pEntry->arena.entry );
621 /* Initialize critical section */
623 if (!processHeap) /* do it by hand to avoid memory allocations */
625 heap->critSection.DebugInfo = &process_heap_critsect_debug;
626 heap->critSection.LockCount = -1;
627 heap->critSection.RecursionCount = 0;
628 heap->critSection.OwningThread = 0;
629 heap->critSection.LockSemaphore = 0;
630 heap->critSection.SpinCount = 0;
631 process_heap_critsect_debug.CriticalSection = &heap->critSection;
633 else RtlInitializeCriticalSection( &heap->critSection );
635 if (flags & HEAP_SHARED)
637 /* let's assume that only one thread at a time will try to do this */
638 HANDLE sem = heap->critSection.LockSemaphore;
639 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
641 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
642 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
643 heap->critSection.LockSemaphore = sem;
647 /* Create the first free block */
649 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
650 subheap->size - subheap->headerSize );
652 return TRUE;
655 /***********************************************************************
656 * HEAP_CreateSubHeap
658 * Create a sub-heap of the given size.
659 * If heap == NULL, creates a main heap.
661 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
662 SIZE_T commitSize, SIZE_T totalSize )
664 LPVOID address = base;
666 /* round-up sizes on a 64K boundary */
667 totalSize = (totalSize + 0xffff) & 0xffff0000;
668 commitSize = (commitSize + 0xffff) & 0xffff0000;
669 if (!commitSize) commitSize = 0x10000;
670 if (totalSize < commitSize) totalSize = commitSize;
672 if (!address)
674 /* allocate the memory block */
675 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
676 MEM_RESERVE, PAGE_READWRITE ))
678 WARN("Could not allocate %08lx bytes\n", totalSize );
679 return NULL;
683 /* Initialize subheap */
685 if (!HEAP_InitSubHeap( heap ? heap : (HEAP *)address,
686 address, flags, commitSize, totalSize ))
688 SIZE_T size = 0;
689 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
690 return NULL;
693 return (SUBHEAP *)address;
697 /***********************************************************************
698 * HEAP_FindFreeBlock
700 * Find a free block at least as large as the requested size, and make sure
701 * the requested size is committed.
703 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
704 SUBHEAP **ppSubHeap )
706 SUBHEAP *subheap;
707 struct list *ptr;
708 FREE_LIST_ENTRY *pEntry = heap->freeList + get_freelist_index( size + sizeof(ARENA_INUSE) );
710 /* Find a suitable free list, and in it find a block large enough */
712 ptr = &pEntry->arena.entry;
713 while ((ptr = list_next( &heap->freeList[0].arena.entry, ptr )))
715 ARENA_FREE *pArena = LIST_ENTRY( ptr, ARENA_FREE, entry );
716 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
717 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
718 if (arena_size >= size)
720 subheap = HEAP_FindSubHeap( heap, pArena );
721 if (!HEAP_Commit( subheap, (ARENA_INUSE *)pArena, size )) return NULL;
722 *ppSubHeap = subheap;
723 return pArena;
727 /* If no block was found, attempt to grow the heap */
729 if (!(heap->flags & HEAP_GROWABLE))
731 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
732 return NULL;
734 /* make sure that we have a big enough size *committed* to fit another
735 * last free arena in !
736 * So just one heap struct, one first free arena which will eventually
737 * get used, and a second free arena that might get assigned all remaining
738 * free space in HEAP_ShrinkBlock() */
739 size += ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + sizeof(ARENA_FREE);
740 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, size,
741 max( HEAP_DEF_SIZE, size ) )))
742 return NULL;
744 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
745 subheap, size, heap );
747 *ppSubHeap = subheap;
748 return (ARENA_FREE *)(subheap + 1);
752 /***********************************************************************
753 * HEAP_IsValidArenaPtr
755 * Check that the pointer is inside the range possible for arenas.
757 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const void *ptr )
759 int i;
760 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
761 if (!subheap) return FALSE;
762 if ((const char *)ptr >= (const char *)subheap + subheap->headerSize) return TRUE;
763 if (subheap != &heap->subheap) return FALSE;
764 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
765 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
766 return FALSE;
770 /***********************************************************************
771 * HEAP_ValidateFreeArena
773 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
775 ARENA_FREE *prev, *next;
776 char *heapEnd = (char *)subheap + subheap->size;
778 /* Check for unaligned pointers */
779 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
781 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
782 return FALSE;
785 /* Check magic number */
786 if (pArena->magic != ARENA_FREE_MAGIC)
788 ERR("Heap %p: invalid free arena magic for %p\n", subheap->heap, pArena );
789 return FALSE;
791 /* Check size flags */
792 if (!(pArena->size & ARENA_FLAG_FREE) ||
793 (pArena->size & ARENA_FLAG_PREV_FREE))
795 ERR("Heap %p: bad flags %08lx for free arena %p\n",
796 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
797 return FALSE;
799 /* Check arena size */
800 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
802 ERR("Heap %p: bad size %08lx for free arena %p\n",
803 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
804 return FALSE;
806 /* Check that next pointer is valid */
807 next = LIST_ENTRY( pArena->entry.next, ARENA_FREE, entry );
808 if (!HEAP_IsValidArenaPtr( subheap->heap, next ))
810 ERR("Heap %p: bad next ptr %p for arena %p\n",
811 subheap->heap, next, pArena );
812 return FALSE;
814 /* Check that next arena is free */
815 if (!(next->size & ARENA_FLAG_FREE) || (next->magic != ARENA_FREE_MAGIC))
817 ERR("Heap %p: next arena %p invalid for %p\n",
818 subheap->heap, next, pArena );
819 return FALSE;
821 /* Check that prev pointer is valid */
822 prev = LIST_ENTRY( pArena->entry.prev, ARENA_FREE, entry );
823 if (!HEAP_IsValidArenaPtr( subheap->heap, prev ))
825 ERR("Heap %p: bad prev ptr %p for arena %p\n",
826 subheap->heap, prev, pArena );
827 return FALSE;
829 /* Check that prev arena is free */
830 if (!(prev->size & ARENA_FLAG_FREE) || (prev->magic != ARENA_FREE_MAGIC))
832 /* this often means that the prev arena got overwritten
833 * by a memory write before that prev arena */
834 ERR("Heap %p: prev arena %p invalid for %p\n",
835 subheap->heap, prev, pArena );
836 return FALSE;
838 /* Check that next block has PREV_FREE flag */
839 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
841 if (!(*(DWORD *)((char *)(pArena + 1) +
842 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
844 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
845 subheap->heap, pArena );
846 return FALSE;
848 /* Check next block back pointer */
849 if (*((ARENA_FREE **)((char *)(pArena + 1) +
850 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
852 ERR("Heap %p: arena %p has wrong back ptr %p\n",
853 subheap->heap, pArena,
854 *((ARENA_FREE **)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
855 return FALSE;
858 return TRUE;
862 /***********************************************************************
863 * HEAP_ValidateInUseArena
865 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
867 const char *heapEnd = (const char *)subheap + subheap->size;
869 /* Check for unaligned pointers */
870 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
872 if ( quiet == NOISY )
874 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
875 if ( TRACE_ON(heap) )
876 HEAP_Dump( subheap->heap );
878 else if ( WARN_ON(heap) )
880 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
881 if ( TRACE_ON(heap) )
882 HEAP_Dump( subheap->heap );
884 return FALSE;
887 /* Check magic number */
888 if (pArena->magic != ARENA_INUSE_MAGIC)
890 if (quiet == NOISY) {
891 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
892 if (TRACE_ON(heap))
893 HEAP_Dump( subheap->heap );
894 } else if (WARN_ON(heap)) {
895 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
896 if (TRACE_ON(heap))
897 HEAP_Dump( subheap->heap );
899 return FALSE;
901 /* Check size flags */
902 if (pArena->size & ARENA_FLAG_FREE)
904 ERR("Heap %p: bad flags %08lx for in-use arena %p\n",
905 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
906 return FALSE;
908 /* Check arena size */
909 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
911 ERR("Heap %p: bad size %08lx for in-use arena %p\n",
912 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
913 return FALSE;
915 /* Check next arena PREV_FREE flag */
916 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
917 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
919 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
920 subheap->heap, pArena );
921 return FALSE;
923 /* Check prev free arena */
924 if (pArena->size & ARENA_FLAG_PREV_FREE)
926 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
927 /* Check prev pointer */
928 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
930 ERR("Heap %p: bad back ptr %p for arena %p\n",
931 subheap->heap, pPrev, pArena );
932 return FALSE;
934 /* Check that prev arena is free */
935 if (!(pPrev->size & ARENA_FLAG_FREE) ||
936 (pPrev->magic != ARENA_FREE_MAGIC))
938 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
939 subheap->heap, pPrev, pArena );
940 return FALSE;
942 /* Check that prev arena is really the previous block */
943 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
945 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
946 subheap->heap, pPrev, pArena );
947 return FALSE;
950 return TRUE;
954 /***********************************************************************
955 * HEAP_IsRealArena [Internal]
956 * Validates a block is a valid arena.
958 * RETURNS
959 * TRUE: Success
960 * FALSE: Failure
962 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
963 DWORD flags, /* [in] Bit flags that control access during operation */
964 LPCVOID block, /* [in] Optional pointer to memory block to validate */
965 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
966 * does not complain */
968 SUBHEAP *subheap;
969 BOOL ret = TRUE;
971 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
973 ERR("Invalid heap %p!\n", heapPtr );
974 return FALSE;
977 flags &= HEAP_NO_SERIALIZE;
978 flags |= heapPtr->flags;
979 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
980 if (!(flags & HEAP_NO_SERIALIZE))
981 RtlEnterCriticalSection( &heapPtr->critSection );
983 if (block)
985 /* Only check this single memory block */
987 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
988 ((const char *)block < (char *)subheap + subheap->headerSize
989 + sizeof(ARENA_INUSE)))
991 if (quiet == NOISY)
992 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
993 else if (WARN_ON(heap))
994 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
995 ret = FALSE;
996 } else
997 ret = HEAP_ValidateInUseArena( subheap, (const ARENA_INUSE *)block - 1, quiet );
999 if (!(flags & HEAP_NO_SERIALIZE))
1000 RtlLeaveCriticalSection( &heapPtr->critSection );
1001 return ret;
1004 subheap = &heapPtr->subheap;
1005 while (subheap && ret)
1007 char *ptr = (char *)subheap + subheap->headerSize;
1008 while (ptr < (char *)subheap + subheap->size)
1010 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1012 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1013 ret = FALSE;
1014 break;
1016 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1018 else
1020 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1021 ret = FALSE;
1022 break;
1024 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1027 subheap = subheap->next;
1030 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1031 return ret;
1035 /***********************************************************************
1036 * RtlCreateHeap (NTDLL.@)
1038 * Create a new Heap.
1040 * PARAMS
1041 * flags [I] HEAP_ flags from "winnt.h"
1042 * addr [I] Desired base address
1043 * totalSize [I] Total size of the heap, or 0 for a growable heap
1044 * commitSize [I] Amount of heap space to commit
1045 * unknown [I] Not yet understood
1046 * definition [I] Heap definition
1048 * RETURNS
1049 * Success: A HANDLE to the newly created heap.
1050 * Failure: a NULL HANDLE.
1052 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1053 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1055 SUBHEAP *subheap;
1057 /* Allocate the heap block */
1059 if (!totalSize)
1061 totalSize = HEAP_DEF_SIZE;
1062 flags |= HEAP_GROWABLE;
1065 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1067 /* link it into the per-process heap list */
1068 if (processHeap)
1070 HEAP *heapPtr = subheap->heap;
1071 RtlEnterCriticalSection( &processHeap->critSection );
1072 list_add_head( &processHeap->entry, &heapPtr->entry );
1073 RtlLeaveCriticalSection( &processHeap->critSection );
1075 else
1077 processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1078 list_init( &processHeap->entry );
1081 return (HANDLE)subheap;
1085 /***********************************************************************
1086 * RtlDestroyHeap (NTDLL.@)
1088 * Destroy a Heap created with RtlCreateHeap().
1090 * PARAMS
1091 * heap [I] Heap to destroy.
1093 * RETURNS
1094 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1095 * Failure: The Heap handle, if heap is the process heap.
1097 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1099 HEAP *heapPtr = HEAP_GetPtr( heap );
1100 SUBHEAP *subheap;
1102 TRACE("%p\n", heap );
1103 if (!heapPtr) return heap;
1105 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1107 /* remove it from the per-process list */
1108 RtlEnterCriticalSection( &processHeap->critSection );
1109 list_remove( &heapPtr->entry );
1110 RtlLeaveCriticalSection( &processHeap->critSection );
1112 RtlDeleteCriticalSection( &heapPtr->critSection );
1113 subheap = &heapPtr->subheap;
1114 while (subheap)
1116 SUBHEAP *next = subheap->next;
1117 SIZE_T size = 0;
1118 void *addr = subheap;
1119 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1120 subheap = next;
1122 return 0;
1126 /***********************************************************************
1127 * RtlAllocateHeap (NTDLL.@)
1129 * Allocate a memory block from a Heap.
1131 * PARAMS
1132 * heap [I] Heap to allocate block from
1133 * flags [I] HEAP_ flags from "winnt.h"
1134 * size [I] Size of the memory block to allocate
1136 * RETURNS
1137 * Success: A pointer to the newly allocated block
1138 * Failure: NULL.
1140 * NOTES
1141 * This call does not SetLastError().
1143 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1145 ARENA_FREE *pArena;
1146 ARENA_INUSE *pInUse;
1147 SUBHEAP *subheap;
1148 HEAP *heapPtr = HEAP_GetPtr( heap );
1149 SIZE_T rounded_size;
1151 /* Validate the parameters */
1153 if (!heapPtr) return NULL;
1154 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1155 flags |= heapPtr->flags;
1156 rounded_size = ROUND_SIZE(size);
1157 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1159 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1160 /* Locate a suitable free block */
1162 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1164 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1165 heap, flags, size );
1166 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1167 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1168 return NULL;
1171 /* Remove the arena from the free list */
1173 list_remove( &pArena->entry );
1175 /* Build the in-use arena */
1177 pInUse = (ARENA_INUSE *)pArena;
1179 /* in-use arena is smaller than free arena,
1180 * so we have to add the difference to the size */
1181 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1182 pInUse->magic = ARENA_INUSE_MAGIC;
1184 /* Shrink the block */
1186 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1187 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1189 if (flags & HEAP_ZERO_MEMORY)
1190 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1191 else
1192 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1194 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1196 TRACE("(%p,%08lx,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1197 return (LPVOID)(pInUse + 1);
1201 /***********************************************************************
1202 * RtlFreeHeap (NTDLL.@)
1204 * Free a memory block allocated with RtlAllocateHeap().
1206 * PARAMS
1207 * heap [I] Heap that block was allocated from
1208 * flags [I] HEAP_ flags from "winnt.h"
1209 * ptr [I] Block to free
1211 * RETURNS
1212 * Success: TRUE, if ptr is NULL or was freed successfully.
1213 * Failure: FALSE.
1215 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1217 ARENA_INUSE *pInUse;
1218 SUBHEAP *subheap;
1219 HEAP *heapPtr;
1221 /* Validate the parameters */
1223 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1225 heapPtr = HEAP_GetPtr( heap );
1226 if (!heapPtr)
1228 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1229 return FALSE;
1232 flags &= HEAP_NO_SERIALIZE;
1233 flags |= heapPtr->flags;
1234 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1235 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1237 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1238 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1239 TRACE("(%p,%08lx,%p): returning FALSE\n", heap, flags, ptr );
1240 return FALSE;
1243 /* Turn the block into a free block */
1245 pInUse = (ARENA_INUSE *)ptr - 1;
1246 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1247 HEAP_MakeInUseBlockFree( subheap, pInUse );
1249 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1251 TRACE("(%p,%08lx,%p): returning TRUE\n", heap, flags, ptr );
1252 return TRUE;
1256 /***********************************************************************
1257 * RtlReAllocateHeap (NTDLL.@)
1259 * Change the size of a memory block allocated with RtlAllocateHeap().
1261 * PARAMS
1262 * heap [I] Heap that block was allocated from
1263 * flags [I] HEAP_ flags from "winnt.h"
1264 * ptr [I] Block to resize
1265 * size [I] Size of the memory block to allocate
1267 * RETURNS
1268 * Success: A pointer to the resized block (which may be different).
1269 * Failure: NULL.
1271 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1273 ARENA_INUSE *pArena;
1274 HEAP *heapPtr;
1275 SUBHEAP *subheap;
1276 SIZE_T oldSize, rounded_size;
1278 if (!ptr) return NULL;
1279 if (!(heapPtr = HEAP_GetPtr( heap )))
1281 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1282 return NULL;
1285 /* Validate the parameters */
1287 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1288 HEAP_REALLOC_IN_PLACE_ONLY;
1289 flags |= heapPtr->flags;
1290 rounded_size = ROUND_SIZE(size);
1291 if (rounded_size < HEAP_MIN_DATA_SIZE) rounded_size = HEAP_MIN_DATA_SIZE;
1293 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1294 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1296 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1297 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1298 TRACE("(%p,%08lx,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1299 return NULL;
1302 /* Check if we need to grow the block */
1304 pArena = (ARENA_INUSE *)ptr - 1;
1305 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1306 oldSize = (pArena->size & ARENA_SIZE_MASK);
1307 if (rounded_size > oldSize)
1309 char *pNext = (char *)(pArena + 1) + oldSize;
1310 if ((pNext < (char *)subheap + subheap->size) &&
1311 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1312 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1314 /* The next block is free and large enough */
1315 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1316 list_remove( &pFree->entry );
1317 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1318 if (!HEAP_Commit( subheap, pArena, rounded_size ))
1320 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1321 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1322 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1323 return NULL;
1325 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1327 else /* Do it the hard way */
1329 ARENA_FREE *pNew;
1330 ARENA_INUSE *pInUse;
1331 SUBHEAP *newsubheap;
1333 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1334 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1336 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1337 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1338 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1339 return NULL;
1342 /* Build the in-use arena */
1344 list_remove( &pNew->entry );
1345 pInUse = (ARENA_INUSE *)pNew;
1346 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1347 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1348 pInUse->magic = ARENA_INUSE_MAGIC;
1349 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1350 mark_block_initialized( pInUse + 1, oldSize );
1351 memcpy( pInUse + 1, pArena + 1, oldSize );
1353 /* Free the previous block */
1355 HEAP_MakeInUseBlockFree( subheap, pArena );
1356 subheap = newsubheap;
1357 pArena = pInUse;
1360 else HEAP_ShrinkBlock( subheap, pArena, rounded_size ); /* Shrink the block */
1362 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1364 /* Clear the extra bytes if needed */
1366 if (rounded_size > oldSize)
1368 if (flags & HEAP_ZERO_MEMORY)
1369 clear_block( (char *)(pArena + 1) + oldSize,
1370 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1371 else
1372 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1373 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1376 /* Return the new arena */
1378 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1380 TRACE("(%p,%08lx,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1381 return (LPVOID)(pArena + 1);
1385 /***********************************************************************
1386 * RtlCompactHeap (NTDLL.@)
1388 * Compact the free space in a Heap.
1390 * PARAMS
1391 * heap [I] Heap that block was allocated from
1392 * flags [I] HEAP_ flags from "winnt.h"
1394 * RETURNS
1395 * The number of bytes compacted.
1397 * NOTES
1398 * This function is a harmless stub.
1400 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1402 FIXME( "stub\n" );
1403 return 0;
1407 /***********************************************************************
1408 * RtlLockHeap (NTDLL.@)
1410 * Lock a Heap.
1412 * PARAMS
1413 * heap [I] Heap to lock
1415 * RETURNS
1416 * Success: TRUE. The Heap is locked.
1417 * Failure: FALSE, if heap is invalid.
1419 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1421 HEAP *heapPtr = HEAP_GetPtr( heap );
1422 if (!heapPtr) return FALSE;
1423 RtlEnterCriticalSection( &heapPtr->critSection );
1424 return TRUE;
1428 /***********************************************************************
1429 * RtlUnlockHeap (NTDLL.@)
1431 * Unlock a Heap.
1433 * PARAMS
1434 * heap [I] Heap to unlock
1436 * RETURNS
1437 * Success: TRUE. The Heap is unlocked.
1438 * Failure: FALSE, if heap is invalid.
1440 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1442 HEAP *heapPtr = HEAP_GetPtr( heap );
1443 if (!heapPtr) return FALSE;
1444 RtlLeaveCriticalSection( &heapPtr->critSection );
1445 return TRUE;
1449 /***********************************************************************
1450 * RtlSizeHeap (NTDLL.@)
1452 * Get the actual size of a memory block allocated from a Heap.
1454 * PARAMS
1455 * heap [I] Heap that block was allocated from
1456 * flags [I] HEAP_ flags from "winnt.h"
1457 * ptr [I] Block to get the size of
1459 * RETURNS
1460 * Success: The size of the block.
1461 * Failure: -1, heap or ptr are invalid.
1463 * NOTES
1464 * The size may be bigger than what was passed to RtlAllocateHeap().
1466 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1468 SIZE_T ret;
1469 HEAP *heapPtr = HEAP_GetPtr( heap );
1471 if (!heapPtr)
1473 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1474 return ~0UL;
1476 flags &= HEAP_NO_SERIALIZE;
1477 flags |= heapPtr->flags;
1478 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1479 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1481 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1482 ret = ~0UL;
1484 else
1486 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1487 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1489 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1491 TRACE("(%p,%08lx,%p): returning %08lx\n", heap, flags, ptr, ret );
1492 return ret;
1496 /***********************************************************************
1497 * RtlValidateHeap (NTDLL.@)
1499 * Determine if a block is a valid allocation from a heap.
1501 * PARAMS
1502 * heap [I] Heap that block was allocated from
1503 * flags [I] HEAP_ flags from "winnt.h"
1504 * ptr [I] Block to check
1506 * RETURNS
1507 * Success: TRUE. The block was allocated from heap.
1508 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1510 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1512 HEAP *heapPtr = HEAP_GetPtr( heap );
1513 if (!heapPtr) return FALSE;
1514 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1518 /***********************************************************************
1519 * RtlWalkHeap (NTDLL.@)
1521 * FIXME
1522 * The PROCESS_HEAP_ENTRY flag values seem different between this
1523 * function and HeapWalk(). To be checked.
1525 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1527 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1528 HEAP *heapPtr = HEAP_GetPtr(heap);
1529 SUBHEAP *sub, *currentheap = NULL;
1530 NTSTATUS ret;
1531 char *ptr;
1532 int region_index = 0;
1534 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1536 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1538 /* set ptr to the next arena to be examined */
1540 if (!entry->lpData) /* first call (init) ? */
1542 TRACE("begin walking of heap %p.\n", heap);
1543 currentheap = &heapPtr->subheap;
1544 ptr = (char*)currentheap + currentheap->headerSize;
1546 else
1548 ptr = entry->lpData;
1549 sub = &heapPtr->subheap;
1550 while (sub)
1552 if (((char *)ptr >= (char *)sub) &&
1553 ((char *)ptr < (char *)sub + sub->size))
1555 currentheap = sub;
1556 break;
1558 sub = sub->next;
1559 region_index++;
1561 if (currentheap == NULL)
1563 ERR("no matching subheap found, shouldn't happen !\n");
1564 ret = STATUS_NO_MORE_ENTRIES;
1565 goto HW_end;
1568 ptr += entry->cbData; /* point to next arena */
1569 if (ptr > (char *)currentheap + currentheap->size - 1)
1570 { /* proceed with next subheap */
1571 if (!(currentheap = currentheap->next))
1572 { /* successfully finished */
1573 TRACE("end reached.\n");
1574 ret = STATUS_NO_MORE_ENTRIES;
1575 goto HW_end;
1577 ptr = (char*)currentheap + currentheap->headerSize;
1581 entry->wFlags = 0;
1582 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1584 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1586 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1588 entry->lpData = pArena + 1;
1589 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1590 entry->cbOverhead = sizeof(ARENA_FREE);
1591 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1593 else
1595 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1597 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1599 entry->lpData = pArena + 1;
1600 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1601 entry->cbOverhead = sizeof(ARENA_INUSE);
1602 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1603 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1604 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1607 entry->iRegionIndex = region_index;
1609 /* first element of heap ? */
1610 if (ptr == (char *)(currentheap + currentheap->headerSize))
1612 entry->wFlags |= PROCESS_HEAP_REGION;
1613 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1614 entry->u.Region.dwUnCommittedSize =
1615 currentheap->size - currentheap->commitSize;
1616 entry->u.Region.lpFirstBlock = /* first valid block */
1617 currentheap + currentheap->headerSize;
1618 entry->u.Region.lpLastBlock = /* first invalid block */
1619 currentheap + currentheap->size;
1621 ret = STATUS_SUCCESS;
1622 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1624 HW_end:
1625 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1626 return ret;
1630 /***********************************************************************
1631 * RtlGetProcessHeaps (NTDLL.@)
1633 * Get the Heaps belonging to the current process.
1635 * PARAMS
1636 * count [I] size of heaps
1637 * heaps [O] Destination array for heap HANDLE's
1639 * RETURNS
1640 * Success: The number of Heaps allocated by the process.
1641 * Failure: 0.
1643 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1645 ULONG total = 1; /* main heap */
1646 struct list *ptr;
1648 RtlEnterCriticalSection( &processHeap->critSection );
1649 LIST_FOR_EACH( ptr, &processHeap->entry ) total++;
1650 if (total <= count)
1652 *heaps++ = processHeap;
1653 LIST_FOR_EACH( ptr, &processHeap->entry )
1654 *heaps++ = LIST_ENTRY( ptr, HEAP, entry );
1656 RtlLeaveCriticalSection( &processHeap->critSection );
1657 return total;