Use Interlocked* functions in AddRef and Release.
[wine/multimedia.git] / dlls / ntdll / heap.c
blob1d6b9c9b6604f6bb5849ba1de2f35a057c3c1425
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 /***********************************************************************
250 * HEAP_GetPtr
251 * RETURNS
252 * Pointer to the heap
253 * NULL: Failure
255 static HEAP *HEAP_GetPtr(
256 HANDLE heap /* [in] Handle to the heap */
258 HEAP *heapPtr = (HEAP *)heap;
259 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
261 ERR("Invalid heap %p!\n", heap );
262 return NULL;
264 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
266 HEAP_Dump( heapPtr );
267 assert( FALSE );
268 return NULL;
270 return heapPtr;
274 /***********************************************************************
275 * HEAP_InsertFreeBlock
277 * Insert a free block into the free list.
279 static inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
281 FREE_LIST_ENTRY *pEntry = heap->freeList;
282 while (pEntry->size < pArena->size) pEntry++;
283 if (last)
285 /* insert at end of free list, i.e. before the next free list entry */
286 pEntry++;
287 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
288 pArena->prev = pEntry->arena.prev;
289 pArena->prev->next = pArena;
290 pArena->next = &pEntry->arena;
291 pEntry->arena.prev = pArena;
293 else
295 /* insert at head of free list */
296 pArena->next = pEntry->arena.next;
297 pArena->next->prev = pArena;
298 pArena->prev = &pEntry->arena;
299 pEntry->arena.next = pArena;
301 pArena->size |= ARENA_FLAG_FREE;
305 /***********************************************************************
306 * HEAP_FindSubHeap
307 * Find the sub-heap containing a given address.
309 * RETURNS
310 * Pointer: Success
311 * NULL: Failure
313 static SUBHEAP *HEAP_FindSubHeap(
314 const HEAP *heap, /* [in] Heap pointer */
315 LPCVOID ptr /* [in] Address */
317 const SUBHEAP *sub = &heap->subheap;
318 while (sub)
320 if (((const char *)ptr >= (const char *)sub) &&
321 ((const char *)ptr < (const char *)sub + sub->size)) return (SUBHEAP*)sub;
322 sub = sub->next;
324 return NULL;
328 /***********************************************************************
329 * HEAP_Commit
331 * Make sure the heap storage is committed up to (not including) ptr.
333 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
335 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
336 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
337 if (size > subheap->size) size = subheap->size;
338 if (size <= subheap->commitSize) return TRUE;
339 size -= subheap->commitSize;
340 ptr = (char *)subheap + subheap->commitSize;
341 if (NtAllocateVirtualMemory( GetCurrentProcess(), &ptr, 0,
342 &size, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
344 WARN("Could not commit %08lx bytes at %p for heap %p\n",
345 size, ptr, subheap->heap );
346 return FALSE;
348 subheap->commitSize += size;
349 return TRUE;
353 /***********************************************************************
354 * HEAP_Decommit
356 * If possible, decommit the heap storage from (including) 'ptr'.
358 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
360 void *addr;
361 ULONG decommit_size;
363 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
364 /* round to next block and add one full block */
365 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
366 if (size >= subheap->commitSize) return TRUE;
367 decommit_size = subheap->commitSize - size;
368 addr = (char *)subheap + size;
370 if (NtFreeVirtualMemory( GetCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
372 WARN("Could not decommit %08lx bytes at %08lx for heap %p\n",
373 decommit_size, (DWORD)((char *)subheap + size), subheap->heap );
374 return FALSE;
376 subheap->commitSize -= decommit_size;
377 return TRUE;
381 /***********************************************************************
382 * HEAP_CreateFreeBlock
384 * Create a free block at a specified address. 'size' is the size of the
385 * whole block, including the new arena.
387 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
389 ARENA_FREE *pFree;
390 char *pEnd;
391 BOOL last;
393 /* Create a free arena */
394 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
395 pFree = (ARENA_FREE *)ptr;
396 pFree->magic = ARENA_FREE_MAGIC;
398 /* If debugging, erase the freed block content */
400 pEnd = (char *)ptr + size;
401 if (pEnd > (char *)subheap + subheap->commitSize) pEnd = (char *)subheap + subheap->commitSize;
402 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
404 /* Check if next block is free also */
406 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
407 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
409 /* Remove the next arena from the free list */
410 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
411 pNext->next->prev = pNext->prev;
412 pNext->prev->next = pNext->next;
413 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
414 mark_block_free( pNext, sizeof(ARENA_FREE) );
417 /* Set the next block PREV_FREE flag and pointer */
419 last = ((char *)ptr + size >= (char *)subheap + subheap->size);
420 if (!last)
422 DWORD *pNext = (DWORD *)((char *)ptr + size);
423 *pNext |= ARENA_FLAG_PREV_FREE;
424 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
425 *(ARENA_FREE **)(pNext - 1) = pFree;
428 /* Last, insert the new block into the free list */
430 pFree->size = size - sizeof(*pFree);
431 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
435 /***********************************************************************
436 * HEAP_MakeInUseBlockFree
438 * Turn an in-use block into a free block. Can also decommit the end of
439 * the heap, and possibly even free the sub-heap altogether.
441 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
443 ARENA_FREE *pFree;
444 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
446 /* Check if we can merge with previous block */
448 if (pArena->size & ARENA_FLAG_PREV_FREE)
450 pFree = *((ARENA_FREE **)pArena - 1);
451 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
452 /* Remove it from the free list */
453 pFree->next->prev = pFree->prev;
454 pFree->prev->next = pFree->next;
456 else pFree = (ARENA_FREE *)pArena;
458 /* Create a free block */
460 HEAP_CreateFreeBlock( subheap, pFree, size );
461 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
462 if ((char *)pFree + size < (char *)subheap + subheap->size)
463 return; /* Not the last block, so nothing more to do */
465 /* Free the whole sub-heap if it's empty and not the original one */
467 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
468 (subheap != &subheap->heap->subheap))
470 ULONG size = 0;
471 SUBHEAP *pPrev = &subheap->heap->subheap;
472 /* Remove the free block from the list */
473 pFree->next->prev = pFree->prev;
474 pFree->prev->next = pFree->next;
475 /* Remove the subheap from the list */
476 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
477 if (pPrev) pPrev->next = subheap->next;
478 /* Free the memory */
479 subheap->magic = 0;
480 NtFreeVirtualMemory( GetCurrentProcess(), (void **)&subheap, &size, MEM_RELEASE );
481 return;
484 /* Decommit the end of the heap */
486 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
490 /***********************************************************************
491 * HEAP_ShrinkBlock
493 * Shrink an in-use block.
495 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
497 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
499 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
500 (pArena->size & ARENA_SIZE_MASK) - size );
501 /* assign size plus previous arena flags */
502 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
504 else
506 /* Turn off PREV_FREE flag in next block */
507 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
508 if (pNext < (char *)subheap + subheap->size)
509 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
513 /***********************************************************************
514 * HEAP_InitSubHeap
516 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
517 DWORD commitSize, DWORD totalSize )
519 SUBHEAP *subheap;
520 FREE_LIST_ENTRY *pEntry;
521 int i;
523 /* Commit memory */
525 if (flags & HEAP_SHARED)
526 commitSize = totalSize; /* always commit everything in a shared heap */
527 if (NtAllocateVirtualMemory( GetCurrentProcess(), &address, 0,
528 &commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
530 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
531 return FALSE;
534 /* Fill the sub-heap structure */
536 subheap = (SUBHEAP *)address;
537 subheap->heap = heap;
538 subheap->size = totalSize;
539 subheap->commitSize = commitSize;
540 subheap->magic = SUBHEAP_MAGIC;
542 if ( subheap != (SUBHEAP *)heap )
544 /* If this is a secondary subheap, insert it into list */
546 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
547 subheap->next = heap->subheap.next;
548 heap->subheap.next = subheap;
550 else
552 /* If this is a primary subheap, initialize main heap */
554 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
555 subheap->next = NULL;
556 heap->next = NULL;
557 heap->flags = flags;
558 heap->magic = HEAP_MAGIC;
560 /* Build the free lists */
562 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
564 pEntry->size = HEAP_freeListSizes[i];
565 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
566 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
567 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
568 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
569 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
570 pEntry->arena.magic = ARENA_FREE_MAGIC;
573 /* Initialize critical section */
575 RtlInitializeCriticalSection( &heap->critSection );
576 if (flags & HEAP_SHARED)
578 /* let's assume that only one thread at a time will try to do this */
579 HANDLE sem = heap->critSection.LockSemaphore;
580 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
582 NtDuplicateObject( GetCurrentProcess(), sem, GetCurrentProcess(), &sem, 0, 0,
583 DUP_HANDLE_MAKE_GLOBAL | DUP_HANDLE_SAME_ACCESS | DUP_HANDLE_CLOSE_SOURCE );
584 heap->critSection.LockSemaphore = sem;
588 /* Create the first free block */
590 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
591 subheap->size - subheap->headerSize );
593 return TRUE;
596 /***********************************************************************
597 * HEAP_CreateSubHeap
599 * Create a sub-heap of the given size.
600 * If heap == NULL, creates a main heap.
602 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
603 DWORD commitSize, DWORD totalSize )
605 LPVOID address = base;
607 /* round-up sizes on a 64K boundary */
608 totalSize = (totalSize + 0xffff) & 0xffff0000;
609 commitSize = (commitSize + 0xffff) & 0xffff0000;
610 if (!commitSize) commitSize = 0x10000;
611 if (totalSize < commitSize) totalSize = commitSize;
613 if (!address)
615 /* allocate the memory block */
616 if (NtAllocateVirtualMemory( GetCurrentProcess(), &address, 0, &totalSize,
617 MEM_RESERVE, PAGE_EXECUTE_READWRITE ))
619 WARN("Could not allocate %08lx bytes\n", totalSize );
620 return NULL;
624 /* Initialize subheap */
626 if (!HEAP_InitSubHeap( heap ? heap : (HEAP *)address,
627 address, flags, commitSize, totalSize ))
629 ULONG size = 0;
630 if (!base) NtFreeVirtualMemory( GetCurrentProcess(), &address, &size, MEM_RELEASE );
631 return NULL;
634 return (SUBHEAP *)address;
638 /***********************************************************************
639 * HEAP_FindFreeBlock
641 * Find a free block at least as large as the requested size, and make sure
642 * the requested size is committed.
644 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
645 SUBHEAP **ppSubHeap )
647 SUBHEAP *subheap;
648 ARENA_FREE *pArena;
649 FREE_LIST_ENTRY *pEntry = heap->freeList;
651 /* Find a suitable free list, and in it find a block large enough */
653 while (pEntry->size < size) pEntry++;
654 pArena = pEntry->arena.next;
655 while (pArena != &heap->freeList[0].arena)
657 DWORD arena_size = (pArena->size & ARENA_SIZE_MASK) +
658 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
659 if (arena_size >= size)
661 subheap = HEAP_FindSubHeap( heap, pArena );
662 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
663 + size + HEAP_MIN_BLOCK_SIZE))
664 return NULL;
665 *ppSubHeap = subheap;
666 return pArena;
668 pArena = pArena->next;
671 /* If no block was found, attempt to grow the heap */
673 if (!(heap->flags & HEAP_GROWABLE))
675 WARN("Not enough space in heap %08lx for %08lx bytes\n",
676 (DWORD)heap, size );
677 return NULL;
679 /* make sure that we have a big enough size *committed* to fit another
680 * last free arena in !
681 * So just one heap struct, one first free arena which will eventually
682 * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
683 * might get assigned all remaining free space in HEAP_ShrinkBlock() */
684 size += ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
685 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, size,
686 max( HEAP_DEF_SIZE, size ) )))
687 return NULL;
689 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
690 (DWORD)subheap, size, (DWORD)heap );
692 *ppSubHeap = subheap;
693 return (ARENA_FREE *)(subheap + 1);
697 /***********************************************************************
698 * HEAP_IsValidArenaPtr
700 * Check that the pointer is inside the range possible for arenas.
702 static BOOL HEAP_IsValidArenaPtr( const HEAP *heap, const void *ptr )
704 int i;
705 const SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
706 if (!subheap) return FALSE;
707 if ((const char *)ptr >= (const char *)subheap + subheap->headerSize) return TRUE;
708 if (subheap != &heap->subheap) return FALSE;
709 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
710 if (ptr == (const void *)&heap->freeList[i].arena) return TRUE;
711 return FALSE;
715 /***********************************************************************
716 * HEAP_ValidateFreeArena
718 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
720 char *heapEnd = (char *)subheap + subheap->size;
722 /* Check for unaligned pointers */
723 if ( (long)pArena % ALIGNMENT != 0 )
725 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
726 (DWORD)subheap->heap, (DWORD)pArena );
727 return FALSE;
730 /* Check magic number */
731 if (pArena->magic != ARENA_FREE_MAGIC)
733 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
734 (DWORD)subheap->heap, (DWORD)pArena );
735 return FALSE;
737 /* Check size flags */
738 if (!(pArena->size & ARENA_FLAG_FREE) ||
739 (pArena->size & ARENA_FLAG_PREV_FREE))
741 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
742 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
744 /* Check arena size */
745 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
747 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
748 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
749 return FALSE;
751 /* Check that next pointer is valid */
752 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
754 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
755 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
756 return FALSE;
758 /* Check that next arena is free */
759 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
760 (pArena->next->magic != ARENA_FREE_MAGIC))
762 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
763 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
764 return FALSE;
766 /* Check that prev pointer is valid */
767 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
769 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
770 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
771 return FALSE;
773 /* Check that prev arena is free */
774 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
775 (pArena->prev->magic != ARENA_FREE_MAGIC))
777 /* this often means that the prev arena got overwritten
778 * by a memory write before that prev arena */
779 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
780 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
781 return FALSE;
783 /* Check that next block has PREV_FREE flag */
784 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
786 if (!(*(DWORD *)((char *)(pArena + 1) +
787 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
789 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
790 (DWORD)subheap->heap, (DWORD)pArena );
791 return FALSE;
793 /* Check next block back pointer */
794 if (*((ARENA_FREE **)((char *)(pArena + 1) +
795 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
797 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
798 (DWORD)subheap->heap, (DWORD)pArena,
799 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
800 return FALSE;
803 return TRUE;
807 /***********************************************************************
808 * HEAP_ValidateInUseArena
810 static BOOL HEAP_ValidateInUseArena( const SUBHEAP *subheap, const ARENA_INUSE *pArena, BOOL quiet )
812 const char *heapEnd = (const char *)subheap + subheap->size;
814 /* Check for unaligned pointers */
815 if ( (long)pArena % ALIGNMENT != 0 )
817 if ( quiet == NOISY )
819 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
820 (DWORD)subheap->heap, (DWORD)pArena );
821 if ( TRACE_ON(heap) )
822 HEAP_Dump( subheap->heap );
824 else if ( WARN_ON(heap) )
826 WARN( "Heap %08lx: unaligned arena pointer %08lx\n",
827 (DWORD)subheap->heap, (DWORD)pArena );
828 if ( TRACE_ON(heap) )
829 HEAP_Dump( subheap->heap );
831 return FALSE;
834 /* Check magic number */
835 if (pArena->magic != ARENA_INUSE_MAGIC)
837 if (quiet == NOISY) {
838 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
839 (DWORD)subheap->heap, (DWORD)pArena );
840 if (TRACE_ON(heap))
841 HEAP_Dump( subheap->heap );
842 } else if (WARN_ON(heap)) {
843 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
844 (DWORD)subheap->heap, (DWORD)pArena );
845 if (TRACE_ON(heap))
846 HEAP_Dump( subheap->heap );
848 return FALSE;
850 /* Check size flags */
851 if (pArena->size & ARENA_FLAG_FREE)
853 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
854 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
855 return FALSE;
857 /* Check arena size */
858 if ((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
860 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
861 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
862 return FALSE;
864 /* Check next arena PREV_FREE flag */
865 if (((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
866 (*(const DWORD *)((const char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
868 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
869 (DWORD)subheap->heap, (DWORD)pArena );
870 return FALSE;
872 /* Check prev free arena */
873 if (pArena->size & ARENA_FLAG_PREV_FREE)
875 const ARENA_FREE *pPrev = *((const ARENA_FREE * const*)pArena - 1);
876 /* Check prev pointer */
877 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
879 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
880 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
881 return FALSE;
883 /* Check that prev arena is free */
884 if (!(pPrev->size & ARENA_FLAG_FREE) ||
885 (pPrev->magic != ARENA_FREE_MAGIC))
887 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
888 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
889 return FALSE;
891 /* Check that prev arena is really the previous block */
892 if ((const char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (const char *)pArena)
894 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
895 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
896 return FALSE;
899 return TRUE;
903 /***********************************************************************
904 * HEAP_IsRealArena [Internal]
905 * Validates a block is a valid arena.
907 * RETURNS
908 * TRUE: Success
909 * FALSE: Failure
911 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
912 DWORD flags, /* [in] Bit flags that control access during operation */
913 LPCVOID block, /* [in] Optional pointer to memory block to validate */
914 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
915 * does not complain */
917 SUBHEAP *subheap;
918 BOOL ret = TRUE;
920 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
922 ERR("Invalid heap %p!\n", heapPtr );
923 return FALSE;
926 flags &= HEAP_NO_SERIALIZE;
927 flags |= heapPtr->flags;
928 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
929 if (!(flags & HEAP_NO_SERIALIZE))
930 RtlEnterCriticalSection( &heapPtr->critSection );
932 if (block)
934 /* Only check this single memory block */
936 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
937 ((const char *)block < (char *)subheap + subheap->headerSize
938 + sizeof(ARENA_INUSE)))
940 if (quiet == NOISY)
941 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
942 else if (WARN_ON(heap))
943 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
944 ret = FALSE;
945 } else
946 ret = HEAP_ValidateInUseArena( subheap, (const ARENA_INUSE *)block - 1, quiet );
948 if (!(flags & HEAP_NO_SERIALIZE))
949 RtlLeaveCriticalSection( &heapPtr->critSection );
950 return ret;
953 subheap = &heapPtr->subheap;
954 while (subheap && ret)
956 char *ptr = (char *)subheap + subheap->headerSize;
957 while (ptr < (char *)subheap + subheap->size)
959 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
961 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
962 ret = FALSE;
963 break;
965 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
967 else
969 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
970 ret = FALSE;
971 break;
973 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
976 subheap = subheap->next;
979 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
980 return ret;
984 /***********************************************************************
985 * RtlCreateHeap (NTDLL.@)
987 * Create a new Heap.
989 * PARAMS
990 * flags [I] HEAP_ flags from "winnt.h"
991 * addr [I] Desired base address
992 * totalSize [I] Total size of the heap, or 0 for a growable heap
993 * commitSize [I] Amount of heap space to commit
994 * unknown [I] Not yet understood
995 * definition [I] Heap definition
997 * RETURNS
998 * Success: A HANDLE to the newly created heap.
999 * Failure: a NULL HANDLE.
1001 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, ULONG totalSize, ULONG commitSize,
1002 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1004 SUBHEAP *subheap;
1006 /* Allocate the heap block */
1008 if (!totalSize)
1010 totalSize = HEAP_DEF_SIZE;
1011 flags |= HEAP_GROWABLE;
1014 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1016 /* link it into the per-process heap list */
1017 if (processHeap)
1019 HEAP *heapPtr = subheap->heap;
1020 RtlLockHeap( processHeap );
1021 heapPtr->next = firstHeap;
1022 firstHeap = heapPtr;
1023 RtlUnlockHeap( processHeap );
1025 else processHeap = subheap->heap; /* assume the first heap we create is the process main heap */
1027 return (HANDLE)subheap;
1031 /***********************************************************************
1032 * RtlDestroyHeap (NTDLL.@)
1034 * Destroy a Heap created with RtlCreateHeap().
1036 * PARAMS
1037 * heap [I] Heap to destroy.
1039 * RETURNS
1040 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1041 * Failure: The Heap handle, if heap is the process heap.
1043 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1045 HEAP *heapPtr = HEAP_GetPtr( heap );
1046 SUBHEAP *subheap;
1048 TRACE("%p\n", heap );
1049 if (!heapPtr) return heap;
1051 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1052 else /* remove it from the per-process list */
1054 HEAP **pptr;
1055 RtlLockHeap( processHeap );
1056 pptr = &firstHeap;
1057 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1058 if (*pptr) *pptr = (*pptr)->next;
1059 RtlUnlockHeap( processHeap );
1062 RtlDeleteCriticalSection( &heapPtr->critSection );
1063 subheap = &heapPtr->subheap;
1064 while (subheap)
1066 SUBHEAP *next = subheap->next;
1067 ULONG size = 0;
1068 void *addr = subheap;
1069 NtFreeVirtualMemory( GetCurrentProcess(), &addr, &size, MEM_RELEASE );
1070 subheap = next;
1072 return 0;
1076 /***********************************************************************
1077 * RtlAllocateHeap (NTDLL.@)
1079 * Allocate a memory block from a Heap.
1081 * PARAMS
1082 * heap [I] Heap to allocate block from
1083 * flags [I] HEAP_ flags from "winnt.h"
1084 * size [I] Size of the memory block to allocate
1086 * RETURNS
1087 * Success: A pointer to the newly allocated block
1088 * Failure: NULL.
1090 * NOTES
1091 * This call does not SetLastError().
1093 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, ULONG size )
1095 ARENA_FREE *pArena;
1096 ARENA_INUSE *pInUse;
1097 SUBHEAP *subheap;
1098 HEAP *heapPtr = HEAP_GetPtr( heap );
1100 /* Validate the parameters */
1102 if (!heapPtr) return NULL;
1103 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1104 flags |= heapPtr->flags;
1105 size = ROUND_SIZE(size);
1106 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1108 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1109 /* Locate a suitable free block */
1111 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1113 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1114 heap, flags, size );
1115 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1116 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1117 return NULL;
1120 /* Remove the arena from the free list */
1122 pArena->next->prev = pArena->prev;
1123 pArena->prev->next = pArena->next;
1125 /* Build the in-use arena */
1127 pInUse = (ARENA_INUSE *)pArena;
1129 /* in-use arena is smaller than free arena,
1130 * so we have to add the difference to the size */
1131 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1132 pInUse->magic = ARENA_INUSE_MAGIC;
1134 /* Shrink the block */
1136 HEAP_ShrinkBlock( subheap, pInUse, size );
1138 if (flags & HEAP_ZERO_MEMORY)
1139 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1140 else
1141 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1143 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1145 TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1146 heap, flags, size, (DWORD)(pInUse + 1) );
1147 return (LPVOID)(pInUse + 1);
1151 /***********************************************************************
1152 * RtlFreeHeap (NTDLL.@)
1154 * Free a memory block allocated with RtlAllocateHeap().
1156 * PARAMS
1157 * heap [I] Heap that block was allocated from
1158 * flags [I] HEAP_ flags from "winnt.h"
1159 * ptr [I] Block to free
1161 * RETURNS
1162 * Success: TRUE, if ptr is NULL or was freed successfully.
1163 * Failure: FALSE.
1165 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1167 ARENA_INUSE *pInUse;
1168 SUBHEAP *subheap;
1169 HEAP *heapPtr = HEAP_GetPtr( heap );
1171 /* Validate the parameters */
1173 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1174 if (!heapPtr)
1176 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1177 return FALSE;
1180 flags &= HEAP_NO_SERIALIZE;
1181 flags |= heapPtr->flags;
1182 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1183 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1185 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1186 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1187 TRACE("(%p,%08lx,%08lx): returning FALSE\n",
1188 heap, flags, (DWORD)ptr );
1189 return FALSE;
1192 /* Turn the block into a free block */
1194 pInUse = (ARENA_INUSE *)ptr - 1;
1195 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1196 HEAP_MakeInUseBlockFree( subheap, pInUse );
1198 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1200 TRACE("(%p,%08lx,%08lx): returning TRUE\n",
1201 heap, flags, (DWORD)ptr );
1202 return TRUE;
1206 /***********************************************************************
1207 * RtlReAllocateHeap (NTDLL.@)
1209 * Change the size of a memory block allocated with RtlAllocateHeap().
1211 * PARAMS
1212 * heap [I] Heap that block was allocated from
1213 * flags [I] HEAP_ flags from "winnt.h"
1214 * ptr [I] Block to resize
1215 * size [I] Size of the memory block to allocate
1217 * RETURNS
1218 * Success: A pointer to the resized block (which may be different).
1219 * Failure: NULL.
1221 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, ULONG size )
1223 ARENA_INUSE *pArena;
1224 DWORD oldSize;
1225 HEAP *heapPtr;
1226 SUBHEAP *subheap;
1228 if (!ptr) return NULL;
1229 if (!(heapPtr = HEAP_GetPtr( heap )))
1231 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1232 return NULL;
1235 /* Validate the parameters */
1237 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1238 HEAP_REALLOC_IN_PLACE_ONLY;
1239 flags |= heapPtr->flags;
1240 size = ROUND_SIZE(size);
1241 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1243 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1244 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1246 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1247 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1248 TRACE("(%p,%08lx,%08lx,%08lx): returning NULL\n",
1249 heap, flags, (DWORD)ptr, size );
1250 return NULL;
1253 /* Check if we need to grow the block */
1255 pArena = (ARENA_INUSE *)ptr - 1;
1256 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1257 oldSize = (pArena->size & ARENA_SIZE_MASK);
1258 if (size > oldSize)
1260 char *pNext = (char *)(pArena + 1) + oldSize;
1261 if ((pNext < (char *)subheap + subheap->size) &&
1262 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1263 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1265 /* The next block is free and large enough */
1266 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1267 pFree->next->prev = pFree->prev;
1268 pFree->prev->next = pFree->next;
1269 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1270 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1271 + size + HEAP_MIN_BLOCK_SIZE))
1273 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1274 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1275 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1276 return NULL;
1278 HEAP_ShrinkBlock( subheap, pArena, size );
1280 else /* Do it the hard way */
1282 ARENA_FREE *pNew;
1283 ARENA_INUSE *pInUse;
1284 SUBHEAP *newsubheap;
1286 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1287 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1289 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1290 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1291 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY );
1292 return NULL;
1295 /* Build the in-use arena */
1297 pNew->next->prev = pNew->prev;
1298 pNew->prev->next = pNew->next;
1299 pInUse = (ARENA_INUSE *)pNew;
1300 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1301 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1302 pInUse->magic = ARENA_INUSE_MAGIC;
1303 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1304 mark_block_initialized( pInUse + 1, oldSize );
1305 memcpy( pInUse + 1, pArena + 1, oldSize );
1307 /* Free the previous block */
1309 HEAP_MakeInUseBlockFree( subheap, pArena );
1310 subheap = newsubheap;
1311 pArena = pInUse;
1314 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1316 /* Clear the extra bytes if needed */
1318 if (size > oldSize)
1320 if (flags & HEAP_ZERO_MEMORY)
1321 clear_block( (char *)(pArena + 1) + oldSize,
1322 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1323 else
1324 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1325 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1328 /* Return the new arena */
1330 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1332 TRACE("(%p,%08lx,%08lx,%08lx): returning %08lx\n",
1333 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1334 return (LPVOID)(pArena + 1);
1338 /***********************************************************************
1339 * RtlCompactHeap (NTDLL.@)
1341 * Compact the free space in a Heap.
1343 * PARAMS
1344 * heap [I] Heap that block was allocated from
1345 * flags [I] HEAP_ flags from "winnt.h"
1347 * RETURNS
1348 * The number of bytes compacted.
1350 * NOTES
1351 * This function is a harmless stub.
1353 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1355 FIXME( "stub\n" );
1356 return 0;
1360 /***********************************************************************
1361 * RtlLockHeap (NTDLL.@)
1363 * Lock a Heap.
1365 * PARAMS
1366 * heap [I] Heap to lock
1368 * RETURNS
1369 * Success: TRUE. The Heap is locked.
1370 * Failure: FALSE, if heap is invalid.
1372 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1374 HEAP *heapPtr = HEAP_GetPtr( heap );
1375 if (!heapPtr) return FALSE;
1376 RtlEnterCriticalSection( &heapPtr->critSection );
1377 return TRUE;
1381 /***********************************************************************
1382 * RtlUnlockHeap (NTDLL.@)
1384 * Unlock a Heap.
1386 * PARAMS
1387 * heap [I] Heap to unlock
1389 * RETURNS
1390 * Success: TRUE. The Heap is unlocked.
1391 * Failure: FALSE, if heap is invalid.
1393 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1395 HEAP *heapPtr = HEAP_GetPtr( heap );
1396 if (!heapPtr) return FALSE;
1397 RtlLeaveCriticalSection( &heapPtr->critSection );
1398 return TRUE;
1402 /***********************************************************************
1403 * RtlSizeHeap (NTDLL.@)
1405 * Get the actual size of a memory block allocated from a Heap.
1407 * PARAMS
1408 * heap [I] Heap that block was allocated from
1409 * flags [I] HEAP_ flags from "winnt.h"
1410 * ptr [I] Block to get the size of
1412 * RETURNS
1413 * Success: The size of the block.
1414 * Failure: -1, heap or ptr are invalid.
1416 * NOTES
1417 * The size may be bigger than what was passed to RtlAllocateHeap().
1419 ULONG WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1421 DWORD ret;
1422 HEAP *heapPtr = HEAP_GetPtr( heap );
1424 if (!heapPtr)
1426 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE );
1427 return (ULONG)-1;
1429 flags &= HEAP_NO_SERIALIZE;
1430 flags |= heapPtr->flags;
1431 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1432 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1434 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER );
1435 ret = (ULONG)-1;
1437 else
1439 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1440 ret = pArena->size & ARENA_SIZE_MASK;
1442 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1444 TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1445 heap, flags, (DWORD)ptr, ret );
1446 return ret;
1450 /***********************************************************************
1451 * RtlValidateHeap (NTDLL.@)
1453 * Determine if a block is a valid alloction from a heap.
1455 * PARAMS
1456 * heap [I] Heap that block was allocated from
1457 * flags [I] HEAP_ flags from "winnt.h"
1458 * ptr [I] Block to check
1460 * RETURNS
1461 * Success: TRUE. The block was allocated from heap.
1462 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1464 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1466 HEAP *heapPtr = HEAP_GetPtr( heap );
1467 if (!heapPtr) return FALSE;
1468 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1472 /***********************************************************************
1473 * RtlWalkHeap (NTDLL.@)
1475 * FIXME
1476 * The PROCESS_HEAP_ENTRY flag values seem different between this
1477 * function and HeapWalk(). To be checked.
1479 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1481 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1482 HEAP *heapPtr = HEAP_GetPtr(heap);
1483 SUBHEAP *sub, *currentheap = NULL;
1484 NTSTATUS ret;
1485 char *ptr;
1486 int region_index = 0;
1488 FIXME( "not fully compatible\n" );
1490 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1492 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1494 /* set ptr to the next arena to be examined */
1496 if (!entry->lpData) /* first call (init) ? */
1498 TRACE("begin walking of heap %p.\n", heap);
1499 currentheap = &heapPtr->subheap;
1500 ptr = (char*)currentheap + currentheap->headerSize;
1502 else
1504 ptr = entry->lpData;
1505 sub = &heapPtr->subheap;
1506 while (sub)
1508 if (((char *)ptr >= (char *)sub) &&
1509 ((char *)ptr < (char *)sub + sub->size))
1511 currentheap = sub;
1512 break;
1514 sub = sub->next;
1515 region_index++;
1517 if (currentheap == NULL)
1519 ERR("no matching subheap found, shouldn't happen !\n");
1520 ret = STATUS_NO_MORE_ENTRIES;
1521 goto HW_end;
1524 ptr += entry->cbData; /* point to next arena */
1525 if (ptr > (char *)currentheap + currentheap->size - 1)
1526 { /* proceed with next subheap */
1527 if (!(currentheap = currentheap->next))
1528 { /* successfully finished */
1529 TRACE("end reached.\n");
1530 ret = STATUS_NO_MORE_ENTRIES;
1531 goto HW_end;
1533 ptr = (char*)currentheap + currentheap->headerSize;
1537 entry->wFlags = 0;
1538 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1540 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1542 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1544 entry->lpData = pArena + 1;
1545 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1546 entry->cbOverhead = sizeof(ARENA_FREE);
1547 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1549 else
1551 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1553 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1555 entry->lpData = pArena + 1;
1556 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1557 entry->cbOverhead = sizeof(ARENA_INUSE);
1558 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1559 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1560 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1563 entry->iRegionIndex = region_index;
1565 /* first element of heap ? */
1566 if (ptr == (char *)(currentheap + currentheap->headerSize))
1568 entry->wFlags |= PROCESS_HEAP_REGION;
1569 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1570 entry->u.Region.dwUnCommittedSize =
1571 currentheap->size - currentheap->commitSize;
1572 entry->u.Region.lpFirstBlock = /* first valid block */
1573 currentheap + currentheap->headerSize;
1574 entry->u.Region.lpLastBlock = /* first invalid block */
1575 currentheap + currentheap->size;
1577 ret = STATUS_SUCCESS;
1579 HW_end:
1580 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1581 return ret;
1585 /***********************************************************************
1586 * RtlGetProcessHeaps (NTDLL.@)
1588 * Get the Heaps belonging to the current process.
1590 * PARAMS
1591 * count [I] size of heaps
1592 * heaps [O] Destination array for heap HANDLE's
1594 * RETURNS
1595 * Success: The number of Heaps allocated by the process.
1596 * Failure: 0.
1598 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1600 DWORD total;
1601 HEAP *ptr;
1603 if (!processHeap) return 0; /* should never happen */
1604 total = 1; /* main heap */
1605 RtlLockHeap( processHeap );
1606 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1607 if (total <= count)
1609 *heaps++ = (HANDLE)processHeap;
1610 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1612 RtlUnlockHeap( processHeap );
1613 return total;