Remove local declarations already in included public headers.
[wine/multimedia.git] / dlls / ntdll / heap.c
blob548df128a48ea7afcc9dcf19a58c44b3e8f3e603
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 "wine/debug.h"
40 #include "winternl.h"
41 #include "wine/server_protocol.h"
43 WINE_DEFAULT_DEBUG_CHANNEL(heap);
45 /* Note: the heap data structures are based on what Pietrek describes in his
46 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
47 * the same, but could be easily adapted if it turns out some programs
48 * require it.
51 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
52 * that there is no unaligned accesses to structure fields.
55 typedef struct tagARENA_INUSE
57 DWORD size; /* Block size; must be the first field */
58 DWORD magic : 27; /* Magic number */
59 DWORD unused_bytes : 5; /* Number of bytes in the block not used by user data (max value is HEAP_MIN_BLOCK_SIZE+ALIGNMENT) */
60 } ARENA_INUSE;
62 typedef struct tagARENA_FREE
64 DWORD size; /* Block size; must be the first field */
65 DWORD magic; /* Magic number */
66 struct tagARENA_FREE *next; /* Next free arena */
67 struct tagARENA_FREE *prev; /* Prev free arena */
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 0x4455355 /* 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 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
87 /* Max size of the blocks on the free lists */
88 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
90 0x20, 0x80, 0x200, ~0UL
93 typedef struct
95 DWORD size;
96 ARENA_FREE arena;
97 } FREE_LIST_ENTRY;
99 struct tagHEAP;
101 typedef struct tagSUBHEAP
103 DWORD size; /* Size of the whole sub-heap */
104 DWORD commitSize; /* Committed size of the sub-heap */
105 DWORD headerSize; /* Size of the heap header */
106 struct tagSUBHEAP *next; /* Next sub-heap */
107 struct tagHEAP *heap; /* Main heap structure */
108 DWORD magic; /* Magic number */
109 } SUBHEAP;
111 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
113 typedef struct tagHEAP
115 SUBHEAP subheap; /* First sub-heap */
116 struct tagHEAP *next; /* Next heap for this process */
117 RTL_CRITICAL_SECTION critSection; /* Critical section for serialization */
118 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
119 DWORD flags; /* Heap flags */
120 DWORD magic; /* Magic number */
121 } HEAP;
123 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
125 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
126 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
127 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
129 static HANDLE processHeap; /* main process heap */
131 static HEAP *firstHeap; /* head of secondary heaps list */
133 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
135 /* mark a block of memory as free for debugging purposes */
136 static inline void mark_block_free( void *ptr, SIZE_T size )
138 if (TRACE_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
139 #ifdef VALGRIND_MAKE_NOACCESS
140 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
141 #endif
144 /* mark a block of memory as initialized for debugging purposes */
145 static inline void mark_block_initialized( void *ptr, SIZE_T size )
147 #ifdef VALGRIND_MAKE_READABLE
148 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
149 #endif
152 /* mark a block of memory as uninitialized for debugging purposes */
153 static inline void mark_block_uninitialized( void *ptr, SIZE_T size )
155 #ifdef VALGRIND_MAKE_WRITABLE
156 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
157 #endif
158 if (TRACE_ON(heap))
160 memset( ptr, ARENA_INUSE_FILLER, size );
161 #ifdef VALGRIND_MAKE_WRITABLE
162 /* make it uninitialized to valgrind again */
163 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
164 #endif
168 /* clear contents of a block of memory */
169 static inline void clear_block( void *ptr, SIZE_T size )
171 mark_block_initialized( ptr, size );
172 memset( ptr, 0, size );
175 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug =
177 0, 0, NULL, /* will be set later */
178 { &process_heap_critsect_debug.ProcessLocksList, &process_heap_critsect_debug.ProcessLocksList },
179 0, 0, { 0, (DWORD)(__FILE__ ": main process heap section") }
183 /***********************************************************************
184 * HEAP_Dump
186 static void HEAP_Dump( HEAP *heap )
188 int i;
189 SUBHEAP *subheap;
190 char *ptr;
192 DPRINTF( "Heap: %p\n", heap );
193 DPRINTF( "Next: %p Sub-heaps: %p", heap->next, &heap->subheap );
194 subheap = &heap->subheap;
195 while (subheap->next)
197 DPRINTF( " -> %p", subheap->next );
198 subheap = subheap->next;
201 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
202 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
203 DPRINTF( "%p free %08lx prev=%p next=%p\n",
204 &heap->freeList[i].arena, heap->freeList[i].size,
205 heap->freeList[i].arena.prev,
206 heap->freeList[i].arena.next );
208 subheap = &heap->subheap;
209 while (subheap)
211 SIZE_T freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
212 DPRINTF( "\n\nSub-heap %p: size=%08lx committed=%08lx\n",
213 subheap, subheap->size, subheap->commitSize );
215 DPRINTF( "\n Block Stat Size Id\n" );
216 ptr = (char*)subheap + subheap->headerSize;
217 while (ptr < (char *)subheap + subheap->size)
219 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
221 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
222 DPRINTF( "%p free %08lx prev=%p next=%p\n",
223 pArena, pArena->size & ARENA_SIZE_MASK,
224 pArena->prev, pArena->next);
225 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
226 arenaSize += sizeof(ARENA_FREE);
227 freeSize += pArena->size & ARENA_SIZE_MASK;
229 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
231 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
232 DPRINTF( "%p Used %08lx back=%08lx\n",
233 pArena, pArena->size & ARENA_SIZE_MASK, *((DWORD *)pArena - 1) );
234 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
235 arenaSize += sizeof(ARENA_INUSE);
236 usedSize += pArena->size & ARENA_SIZE_MASK;
238 else
240 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
241 DPRINTF( "%p used %08lx\n", pArena, pArena->size & ARENA_SIZE_MASK );
242 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
243 arenaSize += sizeof(ARENA_INUSE);
244 usedSize += pArena->size & ARENA_SIZE_MASK;
247 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
248 subheap->size, subheap->commitSize, freeSize, usedSize,
249 arenaSize, (arenaSize * 100) / subheap->size );
250 subheap = subheap->next;
255 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
257 WORD rem_flags;
258 TRACE( "Dumping entry %p\n", entry );
259 TRACE( "lpData\t\t: %p\n", entry->lpData );
260 TRACE( "cbData\t\t: %08lx\n", entry->cbData);
261 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
262 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
263 TRACE( "WFlags\t\t: ");
264 if (entry->wFlags & PROCESS_HEAP_REGION)
265 TRACE( "PROCESS_HEAP_REGION ");
266 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
267 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
268 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
269 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
270 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
271 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
272 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
273 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
274 rem_flags = entry->wFlags &
275 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
276 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
277 PROCESS_HEAP_ENTRY_DDESHARE);
278 if (rem_flags)
279 TRACE( "Unknown %08x", rem_flags);
280 TRACE( "\n");
281 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
282 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
284 /* Treat as block */
285 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
287 if (entry->wFlags & PROCESS_HEAP_REGION)
289 TRACE( "Region.dwCommittedSize\t:%08lx\n",entry->u.Region.dwCommittedSize);
290 TRACE( "Region.dwUnCommittedSize\t:%08lx\n",entry->u.Region.dwUnCommittedSize);
291 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
292 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
296 /***********************************************************************
297 * HEAP_GetPtr
298 * RETURNS
299 * Pointer to the heap
300 * NULL: Failure
302 static HEAP *HEAP_GetPtr(
303 HANDLE heap /* [in] Handle to the heap */
305 HEAP *heapPtr = (HEAP *)heap;
306 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
308 ERR("Invalid heap %p!\n", heap );
309 return NULL;
311 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
313 HEAP_Dump( heapPtr );
314 assert( FALSE );
315 return NULL;
317 return heapPtr;
321 /***********************************************************************
322 * HEAP_InsertFreeBlock
324 * Insert a free block into the free list.
326 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
328 FREE_LIST_ENTRY *pEntry = heap->freeList;
329 while (pEntry->size < pArena->size) pEntry++;
330 if (last)
332 /* insert at end of free list, i.e. before the next free list entry */
333 pEntry++;
334 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
335 pArena->prev = pEntry->arena.prev;
336 pArena->prev->next = pArena;
337 pArena->next = &pEntry->arena;
338 pEntry->arena.prev = pArena;
340 else
342 /* insert at head of free list */
343 pArena->next = pEntry->arena.next;
344 pArena->next->prev = pArena;
345 pArena->prev = &pEntry->arena;
346 pEntry->arena.next = pArena;
348 pArena->size |= ARENA_FLAG_FREE;
352 /***********************************************************************
353 * HEAP_FindSubHeap
354 * Find the sub-heap containing a given address.
356 * RETURNS
357 * Pointer: Success
358 * NULL: Failure
360 static SUBHEAP *HEAP_FindSubHeap(
361 const HEAP *heap, /* [in] Heap pointer */
362 LPCVOID ptr /* [in] Address */
364 const SUBHEAP *sub = &heap->subheap;
365 while (sub)
367 if (((const char *)ptr >= (const char *)sub) &&
368 ((const char *)ptr < (const char *)sub + sub->size)) return (SUBHEAP*)sub;
369 sub = sub->next;
371 return NULL;
375 /***********************************************************************
376 * HEAP_Commit
378 * Make sure the heap storage is committed up to (not including) ptr.
380 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
382 SIZE_T size = (SIZE_T)((char *)ptr - (char *)subheap);
383 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
384 if (size > subheap->size) size = subheap->size;
385 if (size <= subheap->commitSize) return TRUE;
386 size -= subheap->commitSize;
387 ptr = (char *)subheap + subheap->commitSize;
388 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
389 &size, MEM_COMMIT, PAGE_READWRITE ))
391 WARN("Could not commit %08lx bytes at %p for heap %p\n",
392 size, ptr, subheap->heap );
393 return FALSE;
395 subheap->commitSize += size;
396 return TRUE;
400 /***********************************************************************
401 * HEAP_Decommit
403 * If possible, decommit the heap storage from (including) 'ptr'.
405 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
407 void *addr;
408 SIZE_T decommit_size;
409 SIZE_T size = (char *)ptr - (char *)subheap;
411 /* round to next block and add one full block */
412 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
413 if (size >= subheap->commitSize) return TRUE;
414 decommit_size = subheap->commitSize - size;
415 addr = (char *)subheap + size;
417 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
419 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
420 decommit_size, (char *)subheap + size, subheap->heap );
421 return FALSE;
423 subheap->commitSize -= decommit_size;
424 return TRUE;
428 /***********************************************************************
429 * HEAP_CreateFreeBlock
431 * Create a free block at a specified address. 'size' is the size of the
432 * whole block, including the new arena.
434 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, SIZE_T size )
436 ARENA_FREE *pFree;
437 char *pEnd;
438 BOOL last;
440 /* Create a free arena */
441 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
442 pFree = (ARENA_FREE *)ptr;
443 pFree->magic = ARENA_FREE_MAGIC;
445 /* If debugging, erase the freed block content */
447 pEnd = (char *)ptr + size;
448 if (pEnd > (char *)subheap + subheap->commitSize) pEnd = (char *)subheap + subheap->commitSize;
449 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
451 /* Check if next block is free also */
453 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
454 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
456 /* Remove the next arena from the free list */
457 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
458 pNext->next->prev = pNext->prev;
459 pNext->prev->next = pNext->next;
460 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
461 mark_block_free( pNext, sizeof(ARENA_FREE) );
464 /* Set the next block PREV_FREE flag and pointer */
466 last = ((char *)ptr + size >= (char *)subheap + subheap->size);
467 if (!last)
469 DWORD *pNext = (DWORD *)((char *)ptr + size);
470 *pNext |= ARENA_FLAG_PREV_FREE;
471 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
472 *(ARENA_FREE **)(pNext - 1) = pFree;
475 /* Last, insert the new block into the free list */
477 pFree->size = size - sizeof(*pFree);
478 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
482 /***********************************************************************
483 * HEAP_MakeInUseBlockFree
485 * Turn an in-use block into a free block. Can also decommit the end of
486 * the heap, and possibly even free the sub-heap altogether.
488 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
490 ARENA_FREE *pFree;
491 SIZE_T size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
493 /* Check if we can merge with previous block */
495 if (pArena->size & ARENA_FLAG_PREV_FREE)
497 pFree = *((ARENA_FREE **)pArena - 1);
498 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
499 /* Remove it from the free list */
500 pFree->next->prev = pFree->prev;
501 pFree->prev->next = pFree->next;
503 else pFree = (ARENA_FREE *)pArena;
505 /* Create a free block */
507 HEAP_CreateFreeBlock( subheap, pFree, size );
508 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
509 if ((char *)pFree + size < (char *)subheap + subheap->size)
510 return; /* Not the last block, so nothing more to do */
512 /* Free the whole sub-heap if it's empty and not the original one */
514 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
515 (subheap != &subheap->heap->subheap))
517 SIZE_T size = 0;
518 SUBHEAP *pPrev = &subheap->heap->subheap;
519 /* Remove the free block from the list */
520 pFree->next->prev = pFree->prev;
521 pFree->prev->next = pFree->next;
522 /* Remove the subheap from the list */
523 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
524 if (pPrev) pPrev->next = subheap->next;
525 /* Free the memory */
526 subheap->magic = 0;
527 NtFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap, &size, MEM_RELEASE );
528 return;
531 /* Decommit the end of the heap */
533 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
537 /***********************************************************************
538 * HEAP_ShrinkBlock
540 * Shrink an in-use block.
542 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, SIZE_T size)
544 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
546 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
547 (pArena->size & ARENA_SIZE_MASK) - size );
548 /* assign size plus previous arena flags */
549 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
551 else
553 /* Turn off PREV_FREE flag in next block */
554 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
555 if (pNext < (char *)subheap + subheap->size)
556 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
560 /***********************************************************************
561 * HEAP_InitSubHeap
563 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
564 SIZE_T commitSize, SIZE_T totalSize )
566 SUBHEAP *subheap;
567 FREE_LIST_ENTRY *pEntry;
568 int i;
570 /* Commit memory */
572 if (flags & HEAP_SHARED)
573 commitSize = totalSize; /* always commit everything in a shared heap */
574 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
575 &commitSize, MEM_COMMIT, PAGE_READWRITE ))
577 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
578 return FALSE;
581 /* Fill the sub-heap structure */
583 subheap = (SUBHEAP *)address;
584 subheap->heap = heap;
585 subheap->size = totalSize;
586 subheap->commitSize = commitSize;
587 subheap->magic = SUBHEAP_MAGIC;
589 if ( subheap != (SUBHEAP *)heap )
591 /* If this is a secondary subheap, insert it into list */
593 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
594 subheap->next = heap->subheap.next;
595 heap->subheap.next = subheap;
597 else
599 /* If this is a primary subheap, initialize main heap */
601 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
602 subheap->next = NULL;
603 heap->next = NULL;
604 heap->flags = flags;
605 heap->magic = HEAP_MAGIC;
607 /* Build the free lists */
609 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
611 pEntry->size = HEAP_freeListSizes[i];
612 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
613 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
614 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
615 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
616 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
617 pEntry->arena.magic = ARENA_FREE_MAGIC;
620 /* Initialize critical section */
622 if (!processHeap) /* do it by hand to avoid memory allocations */
624 heap->critSection.DebugInfo = &process_heap_critsect_debug;
625 heap->critSection.LockCount = -1;
626 heap->critSection.RecursionCount = 0;
627 heap->critSection.OwningThread = 0;
628 heap->critSection.LockSemaphore = 0;
629 heap->critSection.SpinCount = 0;
630 process_heap_critsect_debug.CriticalSection = &heap->critSection;
632 else RtlInitializeCriticalSection( &heap->critSection );
634 if (flags & HEAP_SHARED)
636 /* let's assume that only one thread at a time will try to do this */
637 HANDLE sem = heap->critSection.LockSemaphore;
638 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
640 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
641 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
642 heap->critSection.LockSemaphore = sem;
646 /* Create the first free block */
648 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
649 subheap->size - subheap->headerSize );
651 return TRUE;
654 /***********************************************************************
655 * HEAP_CreateSubHeap
657 * Create a sub-heap of the given size.
658 * If heap == NULL, creates a main heap.
660 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
661 SIZE_T commitSize, SIZE_T totalSize )
663 LPVOID address = base;
665 /* round-up sizes on a 64K boundary */
666 totalSize = (totalSize + 0xffff) & 0xffff0000;
667 commitSize = (commitSize + 0xffff) & 0xffff0000;
668 if (!commitSize) commitSize = 0x10000;
669 if (totalSize < commitSize) totalSize = commitSize;
671 if (!address)
673 /* allocate the memory block */
674 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
675 MEM_RESERVE, PAGE_READWRITE ))
677 WARN("Could not allocate %08lx bytes\n", totalSize );
678 return NULL;
682 /* Initialize subheap */
684 if (!HEAP_InitSubHeap( heap ? heap : (HEAP *)address,
685 address, flags, commitSize, totalSize ))
687 SIZE_T size = 0;
688 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
689 return NULL;
692 return (SUBHEAP *)address;
696 /***********************************************************************
697 * HEAP_FindFreeBlock
699 * Find a free block at least as large as the requested size, and make sure
700 * the requested size is committed.
702 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, SIZE_T size,
703 SUBHEAP **ppSubHeap )
705 SUBHEAP *subheap;
706 ARENA_FREE *pArena;
707 FREE_LIST_ENTRY *pEntry = heap->freeList;
709 /* Find a suitable free list, and in it find a block large enough */
711 while (pEntry->size < size) pEntry++;
712 pArena = pEntry->arena.next;
713 while (pArena != &heap->freeList[0].arena)
715 SIZE_T arena_size = (pArena->size & ARENA_SIZE_MASK) +
716 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
717 if (arena_size >= size)
719 subheap = HEAP_FindSubHeap( heap, pArena );
720 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
721 + size + HEAP_MIN_BLOCK_SIZE))
722 return NULL;
723 *ppSubHeap = subheap;
724 return pArena;
726 pArena = pArena->next;
729 /* If no block was found, attempt to grow the heap */
731 if (!(heap->flags & HEAP_GROWABLE))
733 WARN("Not enough space in heap %p for %08lx bytes\n", heap, size );
734 return NULL;
736 /* make sure that we have a big enough size *committed* to fit another
737 * last free arena in !
738 * So just one heap struct, one first free arena which will eventually
739 * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
740 * might get assigned all remaining free space in HEAP_ShrinkBlock() */
741 size += ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
742 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, size,
743 max( HEAP_DEF_SIZE, size ) )))
744 return NULL;
746 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
747 subheap, size, heap );
749 *ppSubHeap = subheap;
750 return (ARENA_FREE *)(subheap + 1);
754 /***********************************************************************
755 * HEAP_IsValidArenaPtr
757 * Check that the pointer is inside the range possible for arenas.
759 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const void *ptr )
761 int i;
762 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
763 if (!subheap) return FALSE;
764 if ((const char *)ptr >= (const char *)subheap + subheap->headerSize) return TRUE;
765 if (subheap != &heap->subheap) return FALSE;
766 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
767 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
768 return FALSE;
772 /***********************************************************************
773 * HEAP_ValidateFreeArena
775 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
777 char *heapEnd = (char *)subheap + subheap->size;
779 /* Check for unaligned pointers */
780 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
782 ERR("Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
783 return FALSE;
786 /* Check magic number */
787 if (pArena->magic != ARENA_FREE_MAGIC)
789 ERR("Heap %p: invalid free arena magic for %p\n", subheap->heap, pArena );
790 return FALSE;
792 /* Check size flags */
793 if (!(pArena->size & ARENA_FLAG_FREE) ||
794 (pArena->size & ARENA_FLAG_PREV_FREE))
796 ERR("Heap %p: bad flags %08lx for free arena %p\n",
797 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
798 return FALSE;
800 /* Check arena size */
801 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
803 ERR("Heap %p: bad size %08lx for free arena %p\n",
804 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
805 return FALSE;
807 /* Check that next pointer is valid */
808 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
810 ERR("Heap %p: bad next ptr %p for arena %p\n",
811 subheap->heap, pArena->next, pArena );
812 return FALSE;
814 /* Check that next arena is free */
815 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
816 (pArena->next->magic != ARENA_FREE_MAGIC))
818 ERR("Heap %p: next arena %p invalid for %p\n",
819 subheap->heap, pArena->next, pArena );
820 return FALSE;
822 /* Check that prev pointer is valid */
823 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
825 ERR("Heap %p: bad prev ptr %p for arena %p\n",
826 subheap->heap, pArena->prev, pArena );
827 return FALSE;
829 /* Check that prev arena is free */
830 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
831 (pArena->prev->magic != ARENA_FREE_MAGIC))
833 /* this often means that the prev arena got overwritten
834 * by a memory write before that prev arena */
835 ERR("Heap %p: prev arena %p invalid for %p\n",
836 subheap->heap, pArena->prev, pArena );
837 return FALSE;
839 /* Check that next block has PREV_FREE flag */
840 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
842 if (!(*(DWORD *)((char *)(pArena + 1) +
843 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
845 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
846 subheap->heap, pArena );
847 return FALSE;
849 /* Check next block back pointer */
850 if (*((ARENA_FREE **)((char *)(pArena + 1) +
851 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
853 ERR("Heap %p: arena %p has wrong back ptr %08lx\n",
854 subheap->heap, pArena,
855 *((DWORD *)((char *)(pArena+1) + (pArena->size & ARENA_SIZE_MASK)) - 1));
856 return FALSE;
859 return TRUE;
863 /***********************************************************************
864 * HEAP_ValidateInUseArena
866 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
868 const char *heapEnd = (const char *)subheap + subheap->size;
870 /* Check for unaligned pointers */
871 if ( (ULONG_PTR)pArena % ALIGNMENT != 0 )
873 if ( quiet == NOISY )
875 ERR( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
876 if ( TRACE_ON(heap) )
877 HEAP_Dump( subheap->heap );
879 else if ( WARN_ON(heap) )
881 WARN( "Heap %p: unaligned arena pointer %p\n", subheap->heap, pArena );
882 if ( TRACE_ON(heap) )
883 HEAP_Dump( subheap->heap );
885 return FALSE;
888 /* Check magic number */
889 if (pArena->magic != ARENA_INUSE_MAGIC)
891 if (quiet == NOISY) {
892 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
893 if (TRACE_ON(heap))
894 HEAP_Dump( subheap->heap );
895 } else if (WARN_ON(heap)) {
896 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap->heap, pArena );
897 if (TRACE_ON(heap))
898 HEAP_Dump( subheap->heap );
900 return FALSE;
902 /* Check size flags */
903 if (pArena->size & ARENA_FLAG_FREE)
905 ERR("Heap %p: bad flags %08lx for in-use arena %p\n",
906 subheap->heap, pArena->size & ~ARENA_SIZE_MASK, pArena );
907 return FALSE;
909 /* Check arena size */
910 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
912 ERR("Heap %p: bad size %08lx for in-use arena %p\n",
913 subheap->heap, pArena->size & ARENA_SIZE_MASK, pArena );
914 return FALSE;
916 /* Check next arena PREV_FREE flag */
917 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
918 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
920 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
921 subheap->heap, pArena );
922 return FALSE;
924 /* Check prev free arena */
925 if (pArena->size & ARENA_FLAG_PREV_FREE)
927 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
928 /* Check prev pointer */
929 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
931 ERR("Heap %p: bad back ptr %p for arena %p\n",
932 subheap->heap, pPrev, pArena );
933 return FALSE;
935 /* Check that prev arena is free */
936 if (!(pPrev->size & ARENA_FLAG_FREE) ||
937 (pPrev->magic != ARENA_FREE_MAGIC))
939 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
940 subheap->heap, pPrev, pArena );
941 return FALSE;
943 /* Check that prev arena is really the previous block */
944 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
946 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
947 subheap->heap, pPrev, pArena );
948 return FALSE;
951 return TRUE;
955 /***********************************************************************
956 * HEAP_IsRealArena [Internal]
957 * Validates a block is a valid arena.
959 * RETURNS
960 * TRUE: Success
961 * FALSE: Failure
963 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
964 DWORD flags, /* [in] Bit flags that control access during operation */
965 LPCVOID block, /* [in] Optional pointer to memory block to validate */
966 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
967 * does not complain */
969 SUBHEAP *subheap;
970 BOOL ret = TRUE;
972 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
974 ERR("Invalid heap %p!\n", heapPtr );
975 return FALSE;
978 flags &= HEAP_NO_SERIALIZE;
979 flags |= heapPtr->flags;
980 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
981 if (!(flags & HEAP_NO_SERIALIZE))
982 RtlEnterCriticalSection( &heapPtr->critSection );
984 if (block)
986 /* Only check this single memory block */
988 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
989 ((const char *)block < (char *)subheap + subheap->headerSize
990 + sizeof(ARENA_INUSE)))
992 if (quiet == NOISY)
993 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
994 else if (WARN_ON(heap))
995 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
996 ret = FALSE;
997 } else
998 ret = HEAP_ValidateInUseArena( subheap, (const ARENA_INUSE *)block - 1, quiet );
1000 if (!(flags & HEAP_NO_SERIALIZE))
1001 RtlLeaveCriticalSection( &heapPtr->critSection );
1002 return ret;
1005 subheap = &heapPtr->subheap;
1006 while (subheap && ret)
1008 char *ptr = (char *)subheap + subheap->headerSize;
1009 while (ptr < (char *)subheap + subheap->size)
1011 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1013 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1014 ret = FALSE;
1015 break;
1017 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1019 else
1021 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1022 ret = FALSE;
1023 break;
1025 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1028 subheap = subheap->next;
1031 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1032 return ret;
1036 /***********************************************************************
1037 * RtlCreateHeap (NTDLL.@)
1039 * Create a new Heap.
1041 * PARAMS
1042 * flags [I] HEAP_ flags from "winnt.h"
1043 * addr [I] Desired base address
1044 * totalSize [I] Total size of the heap, or 0 for a growable heap
1045 * commitSize [I] Amount of heap space to commit
1046 * unknown [I] Not yet understood
1047 * definition [I] Heap definition
1049 * RETURNS
1050 * Success: A HANDLE to the newly created heap.
1051 * Failure: a NULL HANDLE.
1053 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, SIZE_T totalSize, SIZE_T commitSize,
1054 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1056 SUBHEAP *subheap;
1058 /* Allocate the heap block */
1060 if (!totalSize)
1062 totalSize = HEAP_DEF_SIZE;
1063 flags |= HEAP_GROWABLE;
1066 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1068 /* link it into the per-process heap list */
1069 if (processHeap)
1071 HEAP *heapPtr = subheap->heap;
1072 RtlLockHeap( processHeap );
1073 heapPtr->next = firstHeap;
1074 firstHeap = heapPtr;
1075 RtlUnlockHeap( processHeap );
1077 else processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1079 return (HANDLE)subheap;
1083 /***********************************************************************
1084 * RtlDestroyHeap (NTDLL.@)
1086 * Destroy a Heap created with RtlCreateHeap().
1088 * PARAMS
1089 * heap [I] Heap to destroy.
1091 * RETURNS
1092 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1093 * Failure: The Heap handle, if heap is the process heap.
1095 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1097 HEAP *heapPtr = HEAP_GetPtr( heap );
1098 SUBHEAP *subheap;
1100 TRACE("%p\n", heap );
1101 if (!heapPtr) return heap;
1103 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1104 else /* remove it from the per-process list */
1106 HEAP **pptr;
1107 RtlLockHeap( processHeap );
1108 pptr = &firstHeap;
1109 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1110 if (*pptr) *pptr = (*pptr)->next;
1111 RtlUnlockHeap( processHeap );
1114 RtlDeleteCriticalSection( &heapPtr->critSection );
1115 subheap = &heapPtr->subheap;
1116 while (subheap)
1118 SUBHEAP *next = subheap->next;
1119 SIZE_T size = 0;
1120 void *addr = subheap;
1121 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1122 subheap = next;
1124 return 0;
1128 /***********************************************************************
1129 * RtlAllocateHeap (NTDLL.@)
1131 * Allocate a memory block from a Heap.
1133 * PARAMS
1134 * heap [I] Heap to allocate block from
1135 * flags [I] HEAP_ flags from "winnt.h"
1136 * size [I] Size of the memory block to allocate
1138 * RETURNS
1139 * Success: A pointer to the newly allocated block
1140 * Failure: NULL.
1142 * NOTES
1143 * This call does not SetLastError().
1145 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, SIZE_T size )
1147 ARENA_FREE *pArena;
1148 ARENA_INUSE *pInUse;
1149 SUBHEAP *subheap;
1150 HEAP *heapPtr = HEAP_GetPtr( heap );
1151 SIZE_T rounded_size;
1153 /* Validate the parameters */
1155 if (!heapPtr) return NULL;
1156 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1157 flags |= heapPtr->flags;
1158 rounded_size = ROUND_SIZE(size);
1159 if (rounded_size < HEAP_MIN_BLOCK_SIZE) rounded_size = HEAP_MIN_BLOCK_SIZE;
1161 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1162 /* Locate a suitable free block */
1164 if (!(pArena = HEAP_FindFreeBlock( heapPtr, rounded_size, &subheap )))
1166 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1167 heap, flags, size );
1168 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1169 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1170 return NULL;
1173 /* Remove the arena from the free list */
1175 pArena->next->prev = pArena->prev;
1176 pArena->prev->next = pArena->next;
1178 /* Build the in-use arena */
1180 pInUse = (ARENA_INUSE *)pArena;
1182 /* in-use arena is smaller than free arena,
1183 * so we have to add the difference to the size */
1184 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1185 pInUse->magic = ARENA_INUSE_MAGIC;
1187 /* Shrink the block */
1189 HEAP_ShrinkBlock( subheap, pInUse, rounded_size );
1190 pInUse->unused_bytes = (pInUse->size & ARENA_SIZE_MASK) - size;
1192 if (flags & HEAP_ZERO_MEMORY)
1193 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1194 else
1195 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1197 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1199 TRACE("(%p,%08lx,%08lx): returning %p\n", heap, flags, size, pInUse + 1 );
1200 return (LPVOID)(pInUse + 1);
1204 /***********************************************************************
1205 * RtlFreeHeap (NTDLL.@)
1207 * Free a memory block allocated with RtlAllocateHeap().
1209 * PARAMS
1210 * heap [I] Heap that block was allocated from
1211 * flags [I] HEAP_ flags from "winnt.h"
1212 * ptr [I] Block to free
1214 * RETURNS
1215 * Success: TRUE, if ptr is NULL or was freed successfully.
1216 * Failure: FALSE.
1218 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1220 ARENA_INUSE *pInUse;
1221 SUBHEAP *subheap;
1222 HEAP *heapPtr;
1224 /* Validate the parameters */
1226 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1228 heapPtr = HEAP_GetPtr( heap );
1229 if (!heapPtr)
1231 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1232 return FALSE;
1235 flags &= HEAP_NO_SERIALIZE;
1236 flags |= heapPtr->flags;
1237 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1238 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1240 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1241 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1242 TRACE("(%p,%08lx,%p): returning FALSE\n", heap, flags, ptr );
1243 return FALSE;
1246 /* Turn the block into a free block */
1248 pInUse = (ARENA_INUSE *)ptr - 1;
1249 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1250 HEAP_MakeInUseBlockFree( subheap, pInUse );
1252 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1254 TRACE("(%p,%08lx,%p): returning TRUE\n", heap, flags, ptr );
1255 return TRUE;
1259 /***********************************************************************
1260 * RtlReAllocateHeap (NTDLL.@)
1262 * Change the size of a memory block allocated with RtlAllocateHeap().
1264 * PARAMS
1265 * heap [I] Heap that block was allocated from
1266 * flags [I] HEAP_ flags from "winnt.h"
1267 * ptr [I] Block to resize
1268 * size [I] Size of the memory block to allocate
1270 * RETURNS
1271 * Success: A pointer to the resized block (which may be different).
1272 * Failure: NULL.
1274 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, SIZE_T size )
1276 ARENA_INUSE *pArena;
1277 HEAP *heapPtr;
1278 SUBHEAP *subheap;
1279 SIZE_T oldSize, rounded_size;
1281 if (!ptr) return NULL;
1282 if (!(heapPtr = HEAP_GetPtr( heap )))
1284 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1285 return NULL;
1288 /* Validate the parameters */
1290 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1291 HEAP_REALLOC_IN_PLACE_ONLY;
1292 flags |= heapPtr->flags;
1293 rounded_size = ROUND_SIZE(size);
1294 if (rounded_size < HEAP_MIN_BLOCK_SIZE) rounded_size = HEAP_MIN_BLOCK_SIZE;
1296 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1297 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1299 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1300 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1301 TRACE("(%p,%08lx,%p,%08lx): returning NULL\n", heap, flags, ptr, size );
1302 return NULL;
1305 /* Check if we need to grow the block */
1307 pArena = (ARENA_INUSE *)ptr - 1;
1308 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1309 oldSize = (pArena->size & ARENA_SIZE_MASK);
1310 if (rounded_size > oldSize)
1312 char *pNext = (char *)(pArena + 1) + oldSize;
1313 if ((pNext < (char *)subheap + subheap->size) &&
1314 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1315 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= rounded_size))
1317 /* The next block is free and large enough */
1318 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1319 pFree->next->prev = pFree->prev;
1320 pFree->prev->next = pFree->next;
1321 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1322 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1323 + rounded_size + HEAP_MIN_BLOCK_SIZE))
1325 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1326 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1327 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1328 return NULL;
1330 HEAP_ShrinkBlock( subheap, pArena, rounded_size );
1332 else /* Do it the hard way */
1334 ARENA_FREE *pNew;
1335 ARENA_INUSE *pInUse;
1336 SUBHEAP *newsubheap;
1338 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1339 !(pNew = HEAP_FindFreeBlock( heapPtr, rounded_size, &newsubheap )))
1341 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1342 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1343 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1344 return NULL;
1347 /* Build the in-use arena */
1349 pNew->next->prev = pNew->prev;
1350 pNew->prev->next = pNew->next;
1351 pInUse = (ARENA_INUSE *)pNew;
1352 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1353 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1354 pInUse->magic = ARENA_INUSE_MAGIC;
1355 HEAP_ShrinkBlock( newsubheap, pInUse, rounded_size );
1356 mark_block_initialized( pInUse + 1, oldSize );
1357 memcpy( pInUse + 1, pArena + 1, oldSize );
1359 /* Free the previous block */
1361 HEAP_MakeInUseBlockFree( subheap, pArena );
1362 subheap = newsubheap;
1363 pArena = pInUse;
1366 else HEAP_ShrinkBlock( subheap, pArena, rounded_size ); /* Shrink the block */
1368 pArena->unused_bytes = (pArena->size & ARENA_SIZE_MASK) - size;
1370 /* Clear the extra bytes if needed */
1372 if (rounded_size > oldSize)
1374 if (flags & HEAP_ZERO_MEMORY)
1375 clear_block( (char *)(pArena + 1) + oldSize,
1376 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1377 else
1378 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1379 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1382 /* Return the new arena */
1384 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1386 TRACE("(%p,%08lx,%p,%08lx): returning %p\n", heap, flags, ptr, size, pArena + 1 );
1387 return (LPVOID)(pArena + 1);
1391 /***********************************************************************
1392 * RtlCompactHeap (NTDLL.@)
1394 * Compact the free space in a Heap.
1396 * PARAMS
1397 * heap [I] Heap that block was allocated from
1398 * flags [I] HEAP_ flags from "winnt.h"
1400 * RETURNS
1401 * The number of bytes compacted.
1403 * NOTES
1404 * This function is a harmless stub.
1406 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1408 FIXME( "stub\n" );
1409 return 0;
1413 /***********************************************************************
1414 * RtlLockHeap (NTDLL.@)
1416 * Lock a Heap.
1418 * PARAMS
1419 * heap [I] Heap to lock
1421 * RETURNS
1422 * Success: TRUE. The Heap is locked.
1423 * Failure: FALSE, if heap is invalid.
1425 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1427 HEAP *heapPtr = HEAP_GetPtr( heap );
1428 if (!heapPtr) return FALSE;
1429 RtlEnterCriticalSection( &heapPtr->critSection );
1430 return TRUE;
1434 /***********************************************************************
1435 * RtlUnlockHeap (NTDLL.@)
1437 * Unlock a Heap.
1439 * PARAMS
1440 * heap [I] Heap to unlock
1442 * RETURNS
1443 * Success: TRUE. The Heap is unlocked.
1444 * Failure: FALSE, if heap is invalid.
1446 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1448 HEAP *heapPtr = HEAP_GetPtr( heap );
1449 if (!heapPtr) return FALSE;
1450 RtlLeaveCriticalSection( &heapPtr->critSection );
1451 return TRUE;
1455 /***********************************************************************
1456 * RtlSizeHeap (NTDLL.@)
1458 * Get the actual size of a memory block allocated from a Heap.
1460 * PARAMS
1461 * heap [I] Heap that block was allocated from
1462 * flags [I] HEAP_ flags from "winnt.h"
1463 * ptr [I] Block to get the size of
1465 * RETURNS
1466 * Success: The size of the block.
1467 * Failure: -1, heap or ptr are invalid.
1469 * NOTES
1470 * The size may be bigger than what was passed to RtlAllocateHeap().
1472 SIZE_T WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1474 SIZE_T ret;
1475 HEAP *heapPtr = HEAP_GetPtr( heap );
1477 if (!heapPtr)
1479 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1480 return ~0UL;
1482 flags &= HEAP_NO_SERIALIZE;
1483 flags |= heapPtr->flags;
1484 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1485 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1487 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1488 ret = ~0UL;
1490 else
1492 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1493 ret = (pArena->size & ARENA_SIZE_MASK) - pArena->unused_bytes;
1495 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1497 TRACE("(%p,%08lx,%p): returning %08lx\n", heap, flags, ptr, ret );
1498 return ret;
1502 /***********************************************************************
1503 * RtlValidateHeap (NTDLL.@)
1505 * Determine if a block is a valid allocation from a heap.
1507 * PARAMS
1508 * heap [I] Heap that block was allocated from
1509 * flags [I] HEAP_ flags from "winnt.h"
1510 * ptr [I] Block to check
1512 * RETURNS
1513 * Success: TRUE. The block was allocated from heap.
1514 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1516 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1518 HEAP *heapPtr = HEAP_GetPtr( heap );
1519 if (!heapPtr) return FALSE;
1520 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1524 /***********************************************************************
1525 * RtlWalkHeap (NTDLL.@)
1527 * FIXME
1528 * The PROCESS_HEAP_ENTRY flag values seem different between this
1529 * function and HeapWalk(). To be checked.
1531 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1533 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1534 HEAP *heapPtr = HEAP_GetPtr(heap);
1535 SUBHEAP *sub, *currentheap = NULL;
1536 NTSTATUS ret;
1537 char *ptr;
1538 int region_index = 0;
1540 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1542 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1544 /* set ptr to the next arena to be examined */
1546 if (!entry->lpData) /* first call (init) ? */
1548 TRACE("begin walking of heap %p.\n", heap);
1549 currentheap = &heapPtr->subheap;
1550 ptr = (char*)currentheap + currentheap->headerSize;
1552 else
1554 ptr = entry->lpData;
1555 sub = &heapPtr->subheap;
1556 while (sub)
1558 if (((char *)ptr >= (char *)sub) &&
1559 ((char *)ptr < (char *)sub + sub->size))
1561 currentheap = sub;
1562 break;
1564 sub = sub->next;
1565 region_index++;
1567 if (currentheap == NULL)
1569 ERR("no matching subheap found, shouldn't happen !\n");
1570 ret = STATUS_NO_MORE_ENTRIES;
1571 goto HW_end;
1574 ptr += entry->cbData; /* point to next arena */
1575 if (ptr > (char *)currentheap + currentheap->size - 1)
1576 { /* proceed with next subheap */
1577 if (!(currentheap = currentheap->next))
1578 { /* successfully finished */
1579 TRACE("end reached.\n");
1580 ret = STATUS_NO_MORE_ENTRIES;
1581 goto HW_end;
1583 ptr = (char*)currentheap + currentheap->headerSize;
1587 entry->wFlags = 0;
1588 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1590 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1592 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1594 entry->lpData = pArena + 1;
1595 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1596 entry->cbOverhead = sizeof(ARENA_FREE);
1597 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1599 else
1601 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1603 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1605 entry->lpData = pArena + 1;
1606 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1607 entry->cbOverhead = sizeof(ARENA_INUSE);
1608 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1609 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1610 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1613 entry->iRegionIndex = region_index;
1615 /* first element of heap ? */
1616 if (ptr == (char *)(currentheap + currentheap->headerSize))
1618 entry->wFlags |= PROCESS_HEAP_REGION;
1619 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1620 entry->u.Region.dwUnCommittedSize =
1621 currentheap->size - currentheap->commitSize;
1622 entry->u.Region.lpFirstBlock = /* first valid block */
1623 currentheap + currentheap->headerSize;
1624 entry->u.Region.lpLastBlock = /* first invalid block */
1625 currentheap + currentheap->size;
1627 ret = STATUS_SUCCESS;
1628 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1630 HW_end:
1631 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1632 return ret;
1636 /***********************************************************************
1637 * RtlGetProcessHeaps (NTDLL.@)
1639 * Get the Heaps belonging to the current process.
1641 * PARAMS
1642 * count [I] size of heaps
1643 * heaps [O] Destination array for heap HANDLE's
1645 * RETURNS
1646 * Success: The number of Heaps allocated by the process.
1647 * Failure: 0.
1649 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1651 ULONG total;
1652 HEAP *ptr;
1654 if (!processHeap) return 0; /* should never happen */
1655 total = 1; /* main heap */
1656 RtlLockHeap( processHeap );
1657 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1658 if (total <= count)
1660 *heaps++ = (HANDLE)processHeap;
1661 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1663 RtlUnlockHeap( processHeap );
1664 return total;