Avoid referencing stackframe.h from outside kernel32.
[wine/testsucceed.git] / dlls / ntdll / heap.c
blob85978d48cf5bed5230f510703853f9bdb056f5cf
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 "winbase.h"
38 #include "winreg.h"
39 #include "winternl.h"
40 #include "wine/winbase16.h"
41 #include "winerror.h"
42 #include "winnt.h"
43 #include "thread.h"
44 #include "wine/debug.h"
45 #include "winternl.h"
46 #include "wine/server_protocol.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(heap);
50 /* Note: the heap data structures are based on what Pietrek describes in his
51 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
52 * the same, but could be easily adapted if it turns out some programs
53 * require it.
56 typedef struct tagARENA_INUSE
58 DWORD size; /* Block size; must be the first field */
59 DWORD magic; /* Magic number */
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 0x44455355 /* 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 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 /***********************************************************************
176 * HEAP_Dump
178 void HEAP_Dump( HEAP *heap )
180 int i;
181 SUBHEAP *subheap;
182 char *ptr;
184 DPRINTF( "Heap: %08lx\n", (DWORD)heap );
185 DPRINTF( "Next: %08lx Sub-heaps: %08lx",
186 (DWORD)heap->next, (DWORD)&heap->subheap );
187 subheap = &heap->subheap;
188 while (subheap->next)
190 DPRINTF( " -> %08lx", (DWORD)subheap->next );
191 subheap = subheap->next;
194 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
195 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
196 DPRINTF( "%08lx free %08lx prev=%08lx next=%08lx\n",
197 (DWORD)&heap->freeList[i].arena, heap->freeList[i].size,
198 (DWORD)heap->freeList[i].arena.prev,
199 (DWORD)heap->freeList[i].arena.next );
201 subheap = &heap->subheap;
202 while (subheap)
204 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
205 DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
206 (DWORD)subheap, subheap->size, subheap->commitSize );
208 DPRINTF( "\n Block Stat Size Id\n" );
209 ptr = (char*)subheap + subheap->headerSize;
210 while (ptr < (char *)subheap + subheap->size)
212 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
214 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
215 DPRINTF( "%08lx free %08lx prev=%08lx next=%08lx\n",
216 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
217 (DWORD)pArena->prev, (DWORD)pArena->next);
218 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
219 arenaSize += sizeof(ARENA_FREE);
220 freeSize += pArena->size & ARENA_SIZE_MASK;
222 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
224 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
225 DPRINTF( "%08lx Used %08lx back=%08lx\n",
226 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK, *((DWORD *)pArena - 1) );
227 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
228 arenaSize += sizeof(ARENA_INUSE);
229 usedSize += pArena->size & ARENA_SIZE_MASK;
231 else
233 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
234 DPRINTF( "%08lx used %08lx\n",
235 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK );
236 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
237 arenaSize += sizeof(ARENA_INUSE);
238 usedSize += pArena->size & ARENA_SIZE_MASK;
241 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
242 subheap->size, subheap->commitSize, freeSize, usedSize,
243 arenaSize, (arenaSize * 100) / subheap->size );
244 subheap = subheap->next;
249 void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry )
251 WORD rem_flags;
252 TRACE( "Dumping entry %p\n", entry );
253 TRACE( "lpData\t\t: %p\n", entry->lpData );
254 TRACE( "cbData\t\t: %08lx\n", entry->cbData);
255 TRACE( "cbOverhead\t: %08x\n", entry->cbOverhead);
256 TRACE( "iRegionIndex\t: %08x\n", entry->iRegionIndex);
257 TRACE( "WFlags\t\t: ");
258 if (entry->wFlags & PROCESS_HEAP_REGION)
259 TRACE( "PROCESS_HEAP_REGION ");
260 if (entry->wFlags & PROCESS_HEAP_UNCOMMITTED_RANGE)
261 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
262 if (entry->wFlags & PROCESS_HEAP_ENTRY_BUSY)
263 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
264 if (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE)
265 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
266 if (entry->wFlags & PROCESS_HEAP_ENTRY_DDESHARE)
267 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
268 rem_flags = entry->wFlags &
269 ~(PROCESS_HEAP_REGION | PROCESS_HEAP_UNCOMMITTED_RANGE |
270 PROCESS_HEAP_ENTRY_BUSY | PROCESS_HEAP_ENTRY_MOVEABLE|
271 PROCESS_HEAP_ENTRY_DDESHARE);
272 if (rem_flags)
273 TRACE( "Unknown %08x", rem_flags);
274 TRACE( "\n");
275 if ((entry->wFlags & PROCESS_HEAP_ENTRY_BUSY )
276 && (entry->wFlags & PROCESS_HEAP_ENTRY_MOVEABLE))
278 /* Treat as block */
279 TRACE( "BLOCK->hMem\t\t:%p\n", entry->u.Block.hMem);
281 if (entry->wFlags & PROCESS_HEAP_REGION)
283 TRACE( "Region.dwCommittedSize\t:%08lx\n",entry->u.Region.dwCommittedSize);
284 TRACE( "Region.dwUnCommittedSize\t:%08lx\n",entry->u.Region.dwUnCommittedSize);
285 TRACE( "Region.lpFirstBlock\t:%p\n",entry->u.Region.lpFirstBlock);
286 TRACE( "Region.lpLastBlock\t:%p\n",entry->u.Region.lpLastBlock);
290 /***********************************************************************
291 * HEAP_GetPtr
292 * RETURNS
293 * Pointer to the heap
294 * NULL: Failure
296 static HEAP *HEAP_GetPtr(
297 HANDLE heap /* [in] Handle to the heap */
299 HEAP *heapPtr = (HEAP *)heap;
300 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
302 ERR("Invalid heap %p!\n", heap );
303 return NULL;
305 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
307 HEAP_Dump( heapPtr );
308 assert( FALSE );
309 return NULL;
311 return heapPtr;
315 /***********************************************************************
316 * HEAP_InsertFreeBlock
318 * Insert a free block into the free list.
320 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
322 FREE_LIST_ENTRY *pEntry = heap->freeList;
323 while (pEntry->size < pArena->size) pEntry++;
324 if (last)
326 /* insert at end of free list, i.e. before the next free list entry */
327 pEntry++;
328 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
329 pArena->prev = pEntry->arena.prev;
330 pArena->prev->next = pArena;
331 pArena->next = &pEntry->arena;
332 pEntry->arena.prev = pArena;
334 else
336 /* insert at head of free list */
337 pArena->next = pEntry->arena.next;
338 pArena->next->prev = pArena;
339 pArena->prev = &pEntry->arena;
340 pEntry->arena.next = pArena;
342 pArena->size |= ARENA_FLAG_FREE;
346 /***********************************************************************
347 * HEAP_FindSubHeap
348 * Find the sub-heap containing a given address.
350 * RETURNS
351 * Pointer: Success
352 * NULL: Failure
354 static SUBHEAP *HEAP_FindSubHeap(
355 const HEAP *heap, /* [in] Heap pointer */
356 LPCVOID ptr /* [in] Address */
358 const SUBHEAP *sub = &heap->subheap;
359 while (sub)
361 if (((const char *)ptr >= (const char *)sub) &&
362 ((const char *)ptr < (const char *)sub + sub->size)) return (SUBHEAP*)sub;
363 sub = sub->next;
365 return NULL;
369 /***********************************************************************
370 * HEAP_Commit
372 * Make sure the heap storage is committed up to (not including) ptr.
374 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
376 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
377 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
378 if (size > subheap->size) size = subheap->size;
379 if (size <= subheap->commitSize) return TRUE;
380 size -= subheap->commitSize;
381 ptr = (char *)subheap + subheap->commitSize;
382 if (NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0,
383 &size, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
385 WARN("Could not commit %08lx bytes at %p for heap %p\n",
386 size, ptr, subheap->heap );
387 return FALSE;
389 subheap->commitSize += size;
390 return TRUE;
394 /***********************************************************************
395 * HEAP_Decommit
397 * If possible, decommit the heap storage from (including) 'ptr'.
399 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
401 void *addr;
402 ULONG decommit_size;
404 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
405 /* round to next block and add one full block */
406 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
407 if (size >= subheap->commitSize) return TRUE;
408 decommit_size = subheap->commitSize - size;
409 addr = (char *)subheap + size;
411 if (NtFreeVirtualMemory( NtCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
413 WARN("Could not decommit %08lx bytes at %08lx for heap %p\n",
414 decommit_size, (DWORD)((char *)subheap + size), subheap->heap );
415 return FALSE;
417 subheap->commitSize -= decommit_size;
418 return TRUE;
422 /***********************************************************************
423 * HEAP_CreateFreeBlock
425 * Create a free block at a specified address. 'size' is the size of the
426 * whole block, including the new arena.
428 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
430 ARENA_FREE *pFree;
431 char *pEnd;
432 BOOL last;
434 /* Create a free arena */
435 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
436 pFree = (ARENA_FREE *)ptr;
437 pFree->magic = ARENA_FREE_MAGIC;
439 /* If debugging, erase the freed block content */
441 pEnd = (char *)ptr + size;
442 if (pEnd > (char *)subheap + subheap->commitSize) pEnd = (char *)subheap + subheap->commitSize;
443 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
445 /* Check if next block is free also */
447 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
448 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
450 /* Remove the next arena from the free list */
451 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
452 pNext->next->prev = pNext->prev;
453 pNext->prev->next = pNext->next;
454 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
455 mark_block_free( pNext, sizeof(ARENA_FREE) );
458 /* Set the next block PREV_FREE flag and pointer */
460 last = ((char *)ptr + size >= (char *)subheap + subheap->size);
461 if (!last)
463 DWORD *pNext = (DWORD *)((char *)ptr + size);
464 *pNext |= ARENA_FLAG_PREV_FREE;
465 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
466 *(ARENA_FREE **)(pNext - 1) = pFree;
469 /* Last, insert the new block into the free list */
471 pFree->size = size - sizeof(*pFree);
472 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
476 /***********************************************************************
477 * HEAP_MakeInUseBlockFree
479 * Turn an in-use block into a free block. Can also decommit the end of
480 * the heap, and possibly even free the sub-heap altogether.
482 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
484 ARENA_FREE *pFree;
485 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
487 /* Check if we can merge with previous block */
489 if (pArena->size & ARENA_FLAG_PREV_FREE)
491 pFree = *((ARENA_FREE **)pArena - 1);
492 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
493 /* Remove it from the free list */
494 pFree->next->prev = pFree->prev;
495 pFree->prev->next = pFree->next;
497 else pFree = (ARENA_FREE *)pArena;
499 /* Create a free block */
501 HEAP_CreateFreeBlock( subheap, pFree, size );
502 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
503 if ((char *)pFree + size < (char *)subheap + subheap->size)
504 return; /* Not the last block, so nothing more to do */
506 /* Free the whole sub-heap if it's empty and not the original one */
508 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
509 (subheap != &subheap->heap->subheap))
511 ULONG size = 0;
512 SUBHEAP *pPrev = &subheap->heap->subheap;
513 /* Remove the free block from the list */
514 pFree->next->prev = pFree->prev;
515 pFree->prev->next = pFree->next;
516 /* Remove the subheap from the list */
517 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
518 if (pPrev) pPrev->next = subheap->next;
519 /* Free the memory */
520 subheap->magic = 0;
521 NtFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap, &size, MEM_RELEASE );
522 return;
525 /* Decommit the end of the heap */
527 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
531 /***********************************************************************
532 * HEAP_ShrinkBlock
534 * Shrink an in-use block.
536 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
538 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
540 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
541 (pArena->size & ARENA_SIZE_MASK) - size );
542 /* assign size plus previous arena flags */
543 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
545 else
547 /* Turn off PREV_FREE flag in next block */
548 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
549 if (pNext < (char *)subheap + subheap->size)
550 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
554 /***********************************************************************
555 * HEAP_InitSubHeap
557 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
558 DWORD commitSize, DWORD totalSize )
560 SUBHEAP *subheap;
561 FREE_LIST_ENTRY *pEntry;
562 int i;
564 /* Commit memory */
566 if (flags & HEAP_SHARED)
567 commitSize = totalSize; /* always commit everything in a shared heap */
568 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0,
569 &commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
571 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
572 return FALSE;
575 /* Fill the sub-heap structure */
577 subheap = (SUBHEAP *)address;
578 subheap->heap = heap;
579 subheap->size = totalSize;
580 subheap->commitSize = commitSize;
581 subheap->magic = SUBHEAP_MAGIC;
583 if ( subheap != (SUBHEAP *)heap )
585 /* If this is a secondary subheap, insert it into list */
587 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
588 subheap->next = heap->subheap.next;
589 heap->subheap.next = subheap;
591 else
593 /* If this is a primary subheap, initialize main heap */
595 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
596 subheap->next = NULL;
597 heap->next = NULL;
598 heap->flags = flags;
599 heap->magic = HEAP_MAGIC;
601 /* Build the free lists */
603 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
605 pEntry->size = HEAP_freeListSizes[i];
606 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
607 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
608 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
609 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
610 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
611 pEntry->arena.magic = ARENA_FREE_MAGIC;
614 /* Initialize critical section */
616 RtlInitializeCriticalSection( &heap->critSection );
617 if (flags & HEAP_SHARED)
619 /* let's assume that only one thread at a time will try to do this */
620 HANDLE sem = heap->critSection.LockSemaphore;
621 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
623 NtDuplicateObject( NtCurrentProcess(), sem, NtCurrentProcess(), &sem, 0, 0,
624 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
625 heap->critSection.LockSemaphore = sem;
629 /* Create the first free block */
631 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
632 subheap->size - subheap->headerSize );
634 return TRUE;
637 /***********************************************************************
638 * HEAP_CreateSubHeap
640 * Create a sub-heap of the given size.
641 * If heap == NULL, creates a main heap.
643 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
644 DWORD commitSize, DWORD totalSize )
646 LPVOID address = base;
648 /* round-up sizes on a 64K boundary */
649 totalSize = (totalSize + 0xffff) & 0xffff0000;
650 commitSize = (commitSize + 0xffff) & 0xffff0000;
651 if (!commitSize) commitSize = 0x10000;
652 if (totalSize < commitSize) totalSize = commitSize;
654 if (!address)
656 /* allocate the memory block */
657 if (NtAllocateVirtualMemory( NtCurrentProcess(), &address, 0, &totalSize,
658 MEM_RESERVE, PAGE_EXECUTE_READWRITE ))
660 WARN("Could not allocate %08lx bytes\n", totalSize );
661 return NULL;
665 /* Initialize subheap */
667 if (!HEAP_InitSubHeap( heap ? heap : (HEAP *)address,
668 address, flags, commitSize, totalSize ))
670 ULONG size = 0;
671 if (!base) NtFreeVirtualMemory( NtCurrentProcess(), &address, &size, MEM_RELEASE );
672 return NULL;
675 return (SUBHEAP *)address;
679 /***********************************************************************
680 * HEAP_FindFreeBlock
682 * Find a free block at least as large as the requested size, and make sure
683 * the requested size is committed.
685 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
686 SUBHEAP **ppSubHeap )
688 SUBHEAP *subheap;
689 ARENA_FREE *pArena;
690 FREE_LIST_ENTRY *pEntry = heap->freeList;
692 /* Find a suitable free list, and in it find a block large enough */
694 while (pEntry->size < size) pEntry++;
695 pArena = pEntry->arena.next;
696 while (pArena != &heap->freeList[0].arena)
698 DWORD arena_size = (pArena->size & ARENA_SIZE_MASK) +
699 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
700 if (arena_size >= size)
702 subheap = HEAP_FindSubHeap( heap, pArena );
703 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
704 + size + HEAP_MIN_BLOCK_SIZE))
705 return NULL;
706 *ppSubHeap = subheap;
707 return pArena;
709 pArena = pArena->next;
712 /* If no block was found, attempt to grow the heap */
714 if (!(heap->flags & HEAP_GROWABLE))
716 WARN("Not enough space in heap %08lx for %08lx bytes\n",
717 (DWORD)heap, size );
718 return NULL;
720 /* make sure that we have a big enough size *committed* to fit another
721 * last free arena in !
722 * So just one heap struct, one first free arena which will eventually
723 * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
724 * might get assigned all remaining free space in HEAP_ShrinkBlock() */
725 size += ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
726 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, size,
727 max( HEAP_DEF_SIZE, size ) )))
728 return NULL;
730 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
731 (DWORD)subheap, size, (DWORD)heap );
733 *ppSubHeap = subheap;
734 return (ARENA_FREE *)(subheap + 1);
738 /***********************************************************************
739 * HEAP_IsValidArenaPtr
741 * Check that the pointer is inside the range possible for arenas.
743 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const void *ptr )
745 int i;
746 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
747 if (!subheap) return FALSE;
748 if ((const char *)ptr >= (const char *)subheap + subheap->headerSize) return TRUE;
749 if (subheap != &heap->subheap) return FALSE;
750 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
751 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
752 return FALSE;
756 /***********************************************************************
757 * HEAP_ValidateFreeArena
759 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
761 char *heapEnd = (char *)subheap + subheap->size;
763 /* Check for unaligned pointers */
764 if ( (long)pArena % ALIGNMENT != 0 )
766 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
767 (DWORD)subheap->heap, (DWORD)pArena );
768 return FALSE;
771 /* Check magic number */
772 if (pArena->magic != ARENA_FREE_MAGIC)
774 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
775 (DWORD)subheap->heap, (DWORD)pArena );
776 return FALSE;
778 /* Check size flags */
779 if (!(pArena->size & ARENA_FLAG_FREE) ||
780 (pArena->size & ARENA_FLAG_PREV_FREE))
782 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
783 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
785 /* Check arena size */
786 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
788 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
789 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
790 return FALSE;
792 /* Check that next pointer is valid */
793 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
795 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
796 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
797 return FALSE;
799 /* Check that next arena is free */
800 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
801 (pArena->next->magic != ARENA_FREE_MAGIC))
803 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
804 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
805 return FALSE;
807 /* Check that prev pointer is valid */
808 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
810 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
811 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
812 return FALSE;
814 /* Check that prev arena is free */
815 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
816 (pArena->prev->magic != ARENA_FREE_MAGIC))
818 /* this often means that the prev arena got overwritten
819 * by a memory write before that prev arena */
820 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
821 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
822 return FALSE;
824 /* Check that next block has PREV_FREE flag */
825 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
827 if (!(*(DWORD *)((char *)(pArena + 1) +
828 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
830 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
831 (DWORD)subheap->heap, (DWORD)pArena );
832 return FALSE;
834 /* Check next block back pointer */
835 if (*((ARENA_FREE **)((char *)(pArena + 1) +
836 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
838 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
839 (DWORD)subheap->heap, (DWORD)pArena,
840 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
841 return FALSE;
844 return TRUE;
848 /***********************************************************************
849 * HEAP_ValidateInUseArena
851 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
853 const char *heapEnd = (const char *)subheap + subheap->size;
855 /* Check for unaligned pointers */
856 if ( (long)pArena % ALIGNMENT != 0 )
858 if ( quiet == NOISY )
860 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
861 (DWORD)subheap->heap, (DWORD)pArena );
862 if ( TRACE_ON(heap) )
863 HEAP_Dump( subheap->heap );
865 else if ( WARN_ON(heap) )
867 WARN( "Heap %08lx: unaligned arena pointer %08lx\n",
868 (DWORD)subheap->heap, (DWORD)pArena );
869 if ( TRACE_ON(heap) )
870 HEAP_Dump( subheap->heap );
872 return FALSE;
875 /* Check magic number */
876 if (pArena->magic != ARENA_INUSE_MAGIC)
878 if (quiet == NOISY) {
879 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
880 (DWORD)subheap->heap, (DWORD)pArena );
881 if (TRACE_ON(heap))
882 HEAP_Dump( subheap->heap );
883 } else if (WARN_ON(heap)) {
884 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
885 (DWORD)subheap->heap, (DWORD)pArena );
886 if (TRACE_ON(heap))
887 HEAP_Dump( subheap->heap );
889 return FALSE;
891 /* Check size flags */
892 if (pArena->size & ARENA_FLAG_FREE)
894 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
895 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
896 return FALSE;
898 /* Check arena size */
899 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
901 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
902 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
903 return FALSE;
905 /* Check next arena PREV_FREE flag */
906 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
907 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
909 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
910 (DWORD)subheap->heap, (DWORD)pArena );
911 return FALSE;
913 /* Check prev free arena */
914 if (pArena->size & ARENA_FLAG_PREV_FREE)
916 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
917 /* Check prev pointer */
918 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
920 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
921 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
922 return FALSE;
924 /* Check that prev arena is free */
925 if (!(pPrev->size & ARENA_FLAG_FREE) ||
926 (pPrev->magic != ARENA_FREE_MAGIC))
928 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
929 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
930 return FALSE;
932 /* Check that prev arena is really the previous block */
933 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
935 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
936 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
937 return FALSE;
940 return TRUE;
944 /***********************************************************************
945 * HEAP_IsRealArena [Internal]
946 * Validates a block is a valid arena.
948 * RETURNS
949 * TRUE: Success
950 * FALSE: Failure
952 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
953 DWORD flags, /* [in] Bit flags that control access during operation */
954 LPCVOID block, /* [in] Optional pointer to memory block to validate */
955 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
956 * does not complain */
958 SUBHEAP *subheap;
959 BOOL ret = TRUE;
961 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
963 ERR("Invalid heap %p!\n", heapPtr );
964 return FALSE;
967 flags &= HEAP_NO_SERIALIZE;
968 flags |= heapPtr->flags;
969 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
970 if (!(flags & HEAP_NO_SERIALIZE))
971 RtlEnterCriticalSection( &heapPtr->critSection );
973 if (block)
975 /* Only check this single memory block */
977 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
978 ((const char *)block < (char *)subheap + subheap->headerSize
979 + sizeof(ARENA_INUSE)))
981 if (quiet == NOISY)
982 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
983 else if (WARN_ON(heap))
984 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
985 ret = FALSE;
986 } else
987 ret = HEAP_ValidateInUseArena( subheap, (const ARENA_INUSE *)block - 1, quiet );
989 if (!(flags & HEAP_NO_SERIALIZE))
990 RtlLeaveCriticalSection( &heapPtr->critSection );
991 return ret;
994 subheap = &heapPtr->subheap;
995 while (subheap && ret)
997 char *ptr = (char *)subheap + subheap->headerSize;
998 while (ptr < (char *)subheap + subheap->size)
1000 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1002 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
1003 ret = FALSE;
1004 break;
1006 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1008 else
1010 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
1011 ret = FALSE;
1012 break;
1014 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
1017 subheap = subheap->next;
1020 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1021 return ret;
1025 /***********************************************************************
1026 * RtlCreateHeap (NTDLL.@)
1028 * Create a new Heap.
1030 * PARAMS
1031 * flags [I] HEAP_ flags from "winnt.h"
1032 * addr [I] Desired base address
1033 * totalSize [I] Total size of the heap, or 0 for a growable heap
1034 * commitSize [I] Amount of heap space to commit
1035 * unknown [I] Not yet understood
1036 * definition [I] Heap definition
1038 * RETURNS
1039 * Success: A HANDLE to the newly created heap.
1040 * Failure: a NULL HANDLE.
1042 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, ULONG totalSize, ULONG commitSize,
1043 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1045 SUBHEAP *subheap;
1047 /* Allocate the heap block */
1049 if (!totalSize)
1051 totalSize = HEAP_DEF_SIZE;
1052 flags |= HEAP_GROWABLE;
1055 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1057 /* link it into the per-process heap list */
1058 if (processHeap)
1060 HEAP *heapPtr = subheap->heap;
1061 RtlLockHeap( processHeap );
1062 heapPtr->next = firstHeap;
1063 firstHeap = heapPtr;
1064 RtlUnlockHeap( processHeap );
1066 else processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1068 return (HANDLE)subheap;
1072 /***********************************************************************
1073 * RtlDestroyHeap (NTDLL.@)
1075 * Destroy a Heap created with RtlCreateHeap().
1077 * PARAMS
1078 * heap [I] Heap to destroy.
1080 * RETURNS
1081 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1082 * Failure: The Heap handle, if heap is the process heap.
1084 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1086 HEAP *heapPtr = HEAP_GetPtr( heap );
1087 SUBHEAP *subheap;
1089 TRACE("%p\n", heap );
1090 if (!heapPtr) return heap;
1092 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1093 else /* remove it from the per-process list */
1095 HEAP **pptr;
1096 RtlLockHeap( processHeap );
1097 pptr = &firstHeap;
1098 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1099 if (*pptr) *pptr = (*pptr)->next;
1100 RtlUnlockHeap( processHeap );
1103 RtlDeleteCriticalSection( &heapPtr->critSection );
1104 subheap = &heapPtr->subheap;
1105 while (subheap)
1107 SUBHEAP *next = subheap->next;
1108 ULONG size = 0;
1109 void *addr = subheap;
1110 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
1111 subheap = next;
1113 return 0;
1117 /***********************************************************************
1118 * RtlAllocateHeap (NTDLL.@)
1120 * Allocate a memory block from a Heap.
1122 * PARAMS
1123 * heap [I] Heap to allocate block from
1124 * flags [I] HEAP_ flags from "winnt.h"
1125 * size [I] Size of the memory block to allocate
1127 * RETURNS
1128 * Success: A pointer to the newly allocated block
1129 * Failure: NULL.
1131 * NOTES
1132 * This call does not SetLastError().
1134 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, ULONG size )
1136 ARENA_FREE *pArena;
1137 ARENA_INUSE *pInUse;
1138 SUBHEAP *subheap;
1139 HEAP *heapPtr = HEAP_GetPtr( heap );
1141 /* Validate the parameters */
1143 if (!heapPtr) return NULL;
1144 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1145 flags |= heapPtr->flags;
1146 size = ROUND_SIZE(size);
1147 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1149 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1150 /* Locate a suitable free block */
1152 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1154 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1155 heap, flags, size );
1156 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1157 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1158 return NULL;
1161 /* Remove the arena from the free list */
1163 pArena->next->prev = pArena->prev;
1164 pArena->prev->next = pArena->next;
1166 /* Build the in-use arena */
1168 pInUse = (ARENA_INUSE *)pArena;
1170 /* in-use arena is smaller than free arena,
1171 * so we have to add the difference to the size */
1172 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1173 pInUse->magic = ARENA_INUSE_MAGIC;
1175 /* Shrink the block */
1177 HEAP_ShrinkBlock( subheap, pInUse, size );
1179 if (flags & HEAP_ZERO_MEMORY)
1180 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1181 else
1182 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1184 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1186 TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1187 heap, flags, size, (DWORD)(pInUse + 1) );
1188 return (LPVOID)(pInUse + 1);
1192 /***********************************************************************
1193 * RtlFreeHeap (NTDLL.@)
1195 * Free a memory block allocated with RtlAllocateHeap().
1197 * PARAMS
1198 * heap [I] Heap that block was allocated from
1199 * flags [I] HEAP_ flags from "winnt.h"
1200 * ptr [I] Block to free
1202 * RETURNS
1203 * Success: TRUE, if ptr is NULL or was freed successfully.
1204 * Failure: FALSE.
1206 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1208 ARENA_INUSE *pInUse;
1209 SUBHEAP *subheap;
1210 HEAP *heapPtr;
1212 /* Validate the parameters */
1214 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1216 heapPtr = HEAP_GetPtr( heap );
1217 if (!heapPtr)
1219 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1220 return FALSE;
1223 flags &= HEAP_NO_SERIALIZE;
1224 flags |= heapPtr->flags;
1225 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1226 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1228 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1229 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1230 TRACE("(%p,%08lx,%08lx): returning FALSE\n",
1231 heap, flags, (DWORD)ptr );
1232 return FALSE;
1235 /* Turn the block into a free block */
1237 pInUse = (ARENA_INUSE *)ptr - 1;
1238 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1239 HEAP_MakeInUseBlockFree( subheap, pInUse );
1241 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1243 TRACE("(%p,%08lx,%08lx): returning TRUE\n",
1244 heap, flags, (DWORD)ptr );
1245 return TRUE;
1249 /***********************************************************************
1250 * RtlReAllocateHeap (NTDLL.@)
1252 * Change the size of a memory block allocated with RtlAllocateHeap().
1254 * PARAMS
1255 * heap [I] Heap that block was allocated from
1256 * flags [I] HEAP_ flags from "winnt.h"
1257 * ptr [I] Block to resize
1258 * size [I] Size of the memory block to allocate
1260 * RETURNS
1261 * Success: A pointer to the resized block (which may be different).
1262 * Failure: NULL.
1264 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, ULONG size )
1266 ARENA_INUSE *pArena;
1267 DWORD oldSize;
1268 HEAP *heapPtr;
1269 SUBHEAP *subheap;
1271 if (!ptr) return NULL;
1272 if (!(heapPtr = HEAP_GetPtr( heap )))
1274 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1275 return NULL;
1278 /* Validate the parameters */
1280 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1281 HEAP_REALLOC_IN_PLACE_ONLY;
1282 flags |= heapPtr->flags;
1283 size = ROUND_SIZE(size);
1284 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1286 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1287 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1289 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1290 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1291 TRACE("(%p,%08lx,%08lx,%08lx): returning NULL\n",
1292 heap, flags, (DWORD)ptr, size );
1293 return NULL;
1296 /* Check if we need to grow the block */
1298 pArena = (ARENA_INUSE *)ptr - 1;
1299 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1300 oldSize = (pArena->size & ARENA_SIZE_MASK);
1301 if (size > oldSize)
1303 char *pNext = (char *)(pArena + 1) + oldSize;
1304 if ((pNext < (char *)subheap + subheap->size) &&
1305 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1306 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1308 /* The next block is free and large enough */
1309 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1310 pFree->next->prev = pFree->prev;
1311 pFree->prev->next = pFree->next;
1312 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1313 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1314 + size + HEAP_MIN_BLOCK_SIZE))
1316 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1317 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1318 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1319 return NULL;
1321 HEAP_ShrinkBlock( subheap, pArena, size );
1323 else /* Do it the hard way */
1325 ARENA_FREE *pNew;
1326 ARENA_INUSE *pInUse;
1327 SUBHEAP *newsubheap;
1329 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1330 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1332 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1333 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1334 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1335 return NULL;
1338 /* Build the in-use arena */
1340 pNew->next->prev = pNew->prev;
1341 pNew->prev->next = pNew->next;
1342 pInUse = (ARENA_INUSE *)pNew;
1343 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1344 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1345 pInUse->magic = ARENA_INUSE_MAGIC;
1346 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1347 mark_block_initialized( pInUse + 1, oldSize );
1348 memcpy( pInUse + 1, pArena + 1, oldSize );
1350 /* Free the previous block */
1352 HEAP_MakeInUseBlockFree( subheap, pArena );
1353 subheap = newsubheap;
1354 pArena = pInUse;
1357 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1359 /* Clear the extra bytes if needed */
1361 if (size > oldSize)
1363 if (flags & HEAP_ZERO_MEMORY)
1364 clear_block( (char *)(pArena + 1) + oldSize,
1365 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1366 else
1367 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1368 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1371 /* Return the new arena */
1373 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1375 TRACE("(%p,%08lx,%08lx,%08lx): returning %08lx\n",
1376 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1377 return (LPVOID)(pArena + 1);
1381 /***********************************************************************
1382 * RtlCompactHeap (NTDLL.@)
1384 * Compact the free space in a Heap.
1386 * PARAMS
1387 * heap [I] Heap that block was allocated from
1388 * flags [I] HEAP_ flags from "winnt.h"
1390 * RETURNS
1391 * The number of bytes compacted.
1393 * NOTES
1394 * This function is a harmless stub.
1396 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1398 FIXME( "stub\n" );
1399 return 0;
1403 /***********************************************************************
1404 * RtlLockHeap (NTDLL.@)
1406 * Lock a Heap.
1408 * PARAMS
1409 * heap [I] Heap to lock
1411 * RETURNS
1412 * Success: TRUE. The Heap is locked.
1413 * Failure: FALSE, if heap is invalid.
1415 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1417 HEAP *heapPtr = HEAP_GetPtr( heap );
1418 if (!heapPtr) return FALSE;
1419 RtlEnterCriticalSection( &heapPtr->critSection );
1420 return TRUE;
1424 /***********************************************************************
1425 * RtlUnlockHeap (NTDLL.@)
1427 * Unlock a Heap.
1429 * PARAMS
1430 * heap [I] Heap to unlock
1432 * RETURNS
1433 * Success: TRUE. The Heap is unlocked.
1434 * Failure: FALSE, if heap is invalid.
1436 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1438 HEAP *heapPtr = HEAP_GetPtr( heap );
1439 if (!heapPtr) return FALSE;
1440 RtlLeaveCriticalSection( &heapPtr->critSection );
1441 return TRUE;
1445 /***********************************************************************
1446 * RtlSizeHeap (NTDLL.@)
1448 * Get the actual size of a memory block allocated from a Heap.
1450 * PARAMS
1451 * heap [I] Heap that block was allocated from
1452 * flags [I] HEAP_ flags from "winnt.h"
1453 * ptr [I] Block to get the size of
1455 * RETURNS
1456 * Success: The size of the block.
1457 * Failure: -1, heap or ptr are invalid.
1459 * NOTES
1460 * The size may be bigger than what was passed to RtlAllocateHeap().
1462 ULONG WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1464 DWORD ret;
1465 HEAP *heapPtr = HEAP_GetPtr( heap );
1467 if (!heapPtr)
1469 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1470 return (ULONG)-1;
1472 flags &= HEAP_NO_SERIALIZE;
1473 flags |= heapPtr->flags;
1474 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1475 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1477 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1478 ret = (ULONG)-1;
1480 else
1482 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1483 ret = pArena->size & ARENA_SIZE_MASK;
1485 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1487 TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1488 heap, flags, (DWORD)ptr, ret );
1489 return ret;
1493 /***********************************************************************
1494 * RtlValidateHeap (NTDLL.@)
1496 * Determine if a block is a valid allocation from a heap.
1498 * PARAMS
1499 * heap [I] Heap that block was allocated from
1500 * flags [I] HEAP_ flags from "winnt.h"
1501 * ptr [I] Block to check
1503 * RETURNS
1504 * Success: TRUE. The block was allocated from heap.
1505 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1507 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1509 HEAP *heapPtr = HEAP_GetPtr( heap );
1510 if (!heapPtr) return FALSE;
1511 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1515 /***********************************************************************
1516 * RtlWalkHeap (NTDLL.@)
1518 * FIXME
1519 * The PROCESS_HEAP_ENTRY flag values seem different between this
1520 * function and HeapWalk(). To be checked.
1522 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1524 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1525 HEAP *heapPtr = HEAP_GetPtr(heap);
1526 SUBHEAP *sub, *currentheap = NULL;
1527 NTSTATUS ret;
1528 char *ptr;
1529 int region_index = 0;
1531 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1533 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1535 /* set ptr to the next arena to be examined */
1537 if (!entry->lpData) /* first call (init) ? */
1539 TRACE("begin walking of heap %p.\n", heap);
1540 currentheap = &heapPtr->subheap;
1541 ptr = (char*)currentheap + currentheap->headerSize;
1543 else
1545 ptr = entry->lpData;
1546 sub = &heapPtr->subheap;
1547 while (sub)
1549 if (((char *)ptr >= (char *)sub) &&
1550 ((char *)ptr < (char *)sub + sub->size))
1552 currentheap = sub;
1553 break;
1555 sub = sub->next;
1556 region_index++;
1558 if (currentheap == NULL)
1560 ERR("no matching subheap found, shouldn't happen !\n");
1561 ret = STATUS_NO_MORE_ENTRIES;
1562 goto HW_end;
1565 ptr += entry->cbData; /* point to next arena */
1566 if (ptr > (char *)currentheap + currentheap->size - 1)
1567 { /* proceed with next subheap */
1568 if (!(currentheap = currentheap->next))
1569 { /* successfully finished */
1570 TRACE("end reached.\n");
1571 ret = STATUS_NO_MORE_ENTRIES;
1572 goto HW_end;
1574 ptr = (char*)currentheap + currentheap->headerSize;
1578 entry->wFlags = 0;
1579 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1581 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1583 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1585 entry->lpData = pArena + 1;
1586 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1587 entry->cbOverhead = sizeof(ARENA_FREE);
1588 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1590 else
1592 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1594 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1596 entry->lpData = pArena + 1;
1597 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1598 entry->cbOverhead = sizeof(ARENA_INUSE);
1599 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1600 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1601 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1604 entry->iRegionIndex = region_index;
1606 /* first element of heap ? */
1607 if (ptr == (char *)(currentheap + currentheap->headerSize))
1609 entry->wFlags |= PROCESS_HEAP_REGION;
1610 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1611 entry->u.Region.dwUnCommittedSize =
1612 currentheap->size - currentheap->commitSize;
1613 entry->u.Region.lpFirstBlock = /* first valid block */
1614 currentheap + currentheap->headerSize;
1615 entry->u.Region.lpLastBlock = /* first invalid block */
1616 currentheap + currentheap->size;
1618 ret = STATUS_SUCCESS;
1619 if (TRACE_ON(heap)) HEAP_DumpEntry(entry);
1621 HW_end:
1622 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1623 return ret;
1627 /***********************************************************************
1628 * RtlGetProcessHeaps (NTDLL.@)
1630 * Get the Heaps belonging to the current process.
1632 * PARAMS
1633 * count [I] size of heaps
1634 * heaps [O] Destination array for heap HANDLE's
1636 * RETURNS
1637 * Success: The number of Heaps allocated by the process.
1638 * Failure: 0.
1640 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1642 DWORD total;
1643 HEAP *ptr;
1645 if (!processHeap) return 0; /* should never happen */
1646 total = 1; /* main heap */
1647 RtlLockHeap( processHeap );
1648 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1649 if (total <= count)
1651 *heaps++ = (HANDLE)processHeap;
1652 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1654 RtlUnlockHeap( processHeap );
1655 return total;