Release 20030408.
[wine/gsoc-2012-control.git] / dlls / ntdll / heap.c
blobcc5c6d48865b3dfd2ef1f5373707fed9a5949c57
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 <stdio.h>
27 #include <string.h>
28 #ifdef HAVE_VALGRIND_MEMCHECK_H
29 #include <valgrind/memcheck.h>
30 #endif
32 #define NONAMELESSUNION
33 #define NONAMELESSSTRUCT
34 #include "winternl.h"
35 #include "wine/winbase16.h"
36 #include "winbase.h"
37 #include "winerror.h"
38 #include "winnt.h"
39 #include "thread.h"
40 #include "wine/debug.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(heap);
44 /* Note: the heap data structures are based on what Pietrek describes in his
45 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
46 * the same, but could be easily adapted if it turns out some programs
47 * require it.
50 typedef struct tagARENA_INUSE
52 DWORD size; /* Block size; must be the first field */
53 DWORD magic; /* Magic number */
54 } ARENA_INUSE;
56 typedef struct tagARENA_FREE
58 DWORD size; /* Block size; must be the first field */
59 DWORD magic; /* Magic number */
60 struct tagARENA_FREE *next; /* Next free arena */
61 struct tagARENA_FREE *prev; /* Prev free arena */
62 } ARENA_FREE;
64 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
65 #define ARENA_FLAG_PREV_FREE 0x00000002
66 #define ARENA_SIZE_MASK (~3)
67 #define ARENA_INUSE_MAGIC 0x44455355 /* Value for arena 'magic' field */
68 #define ARENA_FREE_MAGIC 0x45455246 /* Value for arena 'magic' field */
70 #define ARENA_INUSE_FILLER 0x55
71 #define ARENA_FREE_FILLER 0xaa
73 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
74 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
76 #define QUIET 1 /* Suppress messages */
77 #define NOISY 0 /* Report all errors */
79 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
81 /* Max size of the blocks on the free lists */
82 static const DWORD HEAP_freeListSizes[HEAP_NB_FREE_LISTS] =
84 0x20, 0x80, 0x200, ~0UL
87 typedef struct
89 DWORD size;
90 ARENA_FREE arena;
91 } FREE_LIST_ENTRY;
93 struct tagHEAP;
95 typedef struct tagSUBHEAP
97 DWORD size; /* Size of the whole sub-heap */
98 DWORD commitSize; /* Committed size of the sub-heap */
99 DWORD headerSize; /* Size of the heap header */
100 struct tagSUBHEAP *next; /* Next sub-heap */
101 struct tagHEAP *heap; /* Main heap structure */
102 DWORD magic; /* Magic number */
103 } SUBHEAP;
105 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
107 typedef struct tagHEAP
109 SUBHEAP subheap; /* First sub-heap */
110 struct tagHEAP *next; /* Next heap for this process */
111 CRITICAL_SECTION critSection; /* Critical section for serialization */
112 FREE_LIST_ENTRY freeList[HEAP_NB_FREE_LISTS]; /* Free lists */
113 DWORD flags; /* Heap flags */
114 DWORD magic; /* Magic number */
115 } HEAP;
117 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
119 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
120 #define HEAP_MIN_BLOCK_SIZE (8+sizeof(ARENA_FREE)) /* Min. heap block size */
121 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
123 static HANDLE processHeap; /* main process heap */
125 static HEAP *firstHeap; /* head of secondary heaps list */
127 static BOOL HEAP_IsRealArena( HEAP *heapPtr, DWORD flags, LPCVOID block, BOOL quiet );
129 /* SetLastError for ntdll */
130 inline static void set_status( NTSTATUS status )
132 #if defined(__i386__) && defined(__GNUC__)
133 /* in this case SetLastError is an inline function so we can use it */
134 SetLastError( RtlNtStatusToDosError( status ) );
135 #else
136 /* cannot use SetLastError, do it manually */
137 NtCurrentTeb()->last_error = RtlNtStatusToDosError( status );
138 #endif
141 /* set the process main heap */
142 static void set_process_heap( HANDLE heap )
144 HANDLE *pdb = (HANDLE *)NtCurrentTeb()->process;
145 pdb[0x18 / sizeof(HANDLE)] = heap; /* heap is at offset 0x18 in pdb */
146 processHeap = heap;
149 /* mark a block of memory as free for debugging purposes */
150 static inline void mark_block_free( void *ptr, size_t size )
152 if (TRACE_ON(heap)) memset( ptr, ARENA_FREE_FILLER, size );
153 #ifdef VALGRIND_MAKE_NOACCESS
154 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr, size ));
155 #endif
158 /* mark a block of memory as initialized for debugging purposes */
159 static inline void mark_block_initialized( void *ptr, size_t size )
161 #ifdef VALGRIND_MAKE_READABLE
162 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr, size ));
163 #endif
166 /* mark a block of memory as uninitialized for debugging purposes */
167 static inline void mark_block_uninitialized( void *ptr, size_t size )
169 #ifdef VALGRIND_MAKE_WRITABLE
170 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
171 #endif
172 if (TRACE_ON(heap))
174 memset( ptr, ARENA_INUSE_FILLER, size );
175 #ifdef VALGRIND_MAKE_WRITABLE
176 /* make it uninitialized to valgrind again */
177 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr, size ));
178 #endif
182 /* clear contents of a block of memory */
183 static inline void clear_block( void *ptr, size_t size )
185 mark_block_initialized( ptr, size );
186 memset( ptr, 0, size );
189 /***********************************************************************
190 * HEAP_Dump
192 void HEAP_Dump( HEAP *heap )
194 int i;
195 SUBHEAP *subheap;
196 char *ptr;
198 DPRINTF( "Heap: %08lx\n", (DWORD)heap );
199 DPRINTF( "Next: %08lx Sub-heaps: %08lx",
200 (DWORD)heap->next, (DWORD)&heap->subheap );
201 subheap = &heap->subheap;
202 while (subheap->next)
204 DPRINTF( " -> %08lx", (DWORD)subheap->next );
205 subheap = subheap->next;
208 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
209 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
210 DPRINTF( "%08lx free %08lx prev=%08lx next=%08lx\n",
211 (DWORD)&heap->freeList[i].arena, heap->freeList[i].arena.size,
212 (DWORD)heap->freeList[i].arena.prev,
213 (DWORD)heap->freeList[i].arena.next );
215 subheap = &heap->subheap;
216 while (subheap)
218 DWORD freeSize = 0, usedSize = 0, arenaSize = subheap->headerSize;
219 DPRINTF( "\n\nSub-heap %08lx: size=%08lx committed=%08lx\n",
220 (DWORD)subheap, subheap->size, subheap->commitSize );
222 DPRINTF( "\n Block Stat Size Id\n" );
223 ptr = (char*)subheap + subheap->headerSize;
224 while (ptr < (char *)subheap + subheap->size)
226 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
228 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
229 DPRINTF( "%08lx free %08lx prev=%08lx next=%08lx\n",
230 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK,
231 (DWORD)pArena->prev, (DWORD)pArena->next);
232 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
233 arenaSize += sizeof(ARENA_FREE);
234 freeSize += pArena->size & ARENA_SIZE_MASK;
236 else if (*(DWORD *)ptr & ARENA_FLAG_PREV_FREE)
238 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
239 DPRINTF( "%08lx Used %08lx back=%08lx\n",
240 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK, *((DWORD *)pArena - 1) );
241 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
242 arenaSize += sizeof(ARENA_INUSE);
243 usedSize += pArena->size & ARENA_SIZE_MASK;
245 else
247 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
248 DPRINTF( "%08lx used %08lx\n",
249 (DWORD)pArena, pArena->size & ARENA_SIZE_MASK );
250 ptr += sizeof(*pArena) + (pArena->size & ARENA_SIZE_MASK);
251 arenaSize += sizeof(ARENA_INUSE);
252 usedSize += pArena->size & ARENA_SIZE_MASK;
255 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
256 subheap->size, subheap->commitSize, freeSize, usedSize,
257 arenaSize, (arenaSize * 100) / subheap->size );
258 subheap = subheap->next;
263 /***********************************************************************
264 * HEAP_GetPtr
265 * RETURNS
266 * Pointer to the heap
267 * NULL: Failure
269 static HEAP *HEAP_GetPtr(
270 HANDLE heap /* [in] Handle to the heap */
272 HEAP *heapPtr = (HEAP *)heap;
273 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
275 ERR("Invalid heap %p!\n", heap );
276 return NULL;
278 if (TRACE_ON(heap) && !HEAP_IsRealArena( heapPtr, 0, NULL, NOISY ))
280 HEAP_Dump( heapPtr );
281 assert( FALSE );
282 return NULL;
284 return heapPtr;
288 /***********************************************************************
289 * HEAP_InsertFreeBlock
291 * Insert a free block into the free list.
293 static void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena )
295 FREE_LIST_ENTRY *pEntry = heap->freeList;
296 while (pEntry->size < pArena->size) pEntry++;
297 pArena->size |= ARENA_FLAG_FREE;
298 pArena->next = pEntry->arena.next;
299 pArena->next->prev = pArena;
300 pArena->prev = &pEntry->arena;
301 pEntry->arena.next = pArena;
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 HEAP *heap, /* [in] Heap pointer */
315 LPCVOID ptr /* [in] Address */
317 SUBHEAP *sub = &heap->subheap;
318 while (sub)
320 if (((char *)ptr >= (char *)sub) &&
321 ((char *)ptr < (char *)sub + sub->size)) return 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 if (NtAllocateVirtualMemory( GetCurrentProcess(), &ptr, (char *)subheap + subheap->commitSize,
341 &size, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
343 WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
344 size, (DWORD)((char *)subheap + subheap->commitSize),
345 (DWORD)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;
392 /* Create a free arena */
393 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
394 pFree = (ARENA_FREE *)ptr;
395 pFree->magic = ARENA_FREE_MAGIC;
397 /* If debugging, erase the freed block content */
399 pEnd = (char *)ptr + size;
400 if (pEnd > (char *)subheap + subheap->commitSize) pEnd = (char *)subheap + subheap->commitSize;
401 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
403 /* Check if next block is free also */
405 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
406 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
408 /* Remove the next arena from the free list */
409 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
410 pNext->next->prev = pNext->prev;
411 pNext->prev->next = pNext->next;
412 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
413 mark_block_free( pNext, sizeof(ARENA_FREE) );
416 /* Set the next block PREV_FREE flag and pointer */
418 if ((char *)ptr + size < (char *)subheap + subheap->size)
420 DWORD *pNext = (DWORD *)((char *)ptr + size);
421 *pNext |= ARENA_FLAG_PREV_FREE;
422 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
423 *(ARENA_FREE **)(pNext - 1) = pFree;
426 /* Last, insert the new block into the free list */
428 pFree->size = size - sizeof(*pFree);
429 HEAP_InsertFreeBlock( subheap->heap, pFree );
433 /***********************************************************************
434 * HEAP_MakeInUseBlockFree
436 * Turn an in-use block into a free block. Can also decommit the end of
437 * the heap, and possibly even free the sub-heap altogether.
439 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
441 ARENA_FREE *pFree;
442 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
444 /* Check if we can merge with previous block */
446 if (pArena->size & ARENA_FLAG_PREV_FREE)
448 pFree = *((ARENA_FREE **)pArena - 1);
449 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
450 /* Remove it from the free list */
451 pFree->next->prev = pFree->prev;
452 pFree->prev->next = pFree->next;
454 else pFree = (ARENA_FREE *)pArena;
456 /* Create a free block */
458 HEAP_CreateFreeBlock( subheap, pFree, size );
459 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
460 if ((char *)pFree + size < (char *)subheap + subheap->size)
461 return; /* Not the last block, so nothing more to do */
463 /* Free the whole sub-heap if it's empty and not the original one */
465 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
466 (subheap != &subheap->heap->subheap))
468 ULONG size = 0;
469 SUBHEAP *pPrev = &subheap->heap->subheap;
470 /* Remove the free block from the list */
471 pFree->next->prev = pFree->prev;
472 pFree->prev->next = pFree->next;
473 /* Remove the subheap from the list */
474 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
475 if (pPrev) pPrev->next = subheap->next;
476 /* Free the memory */
477 subheap->magic = 0;
478 NtFreeVirtualMemory( GetCurrentProcess(), (void **)&subheap, &size, MEM_RELEASE );
479 return;
482 /* Decommit the end of the heap */
484 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
488 /***********************************************************************
489 * HEAP_ShrinkBlock
491 * Shrink an in-use block.
493 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
495 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
497 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
498 (pArena->size & ARENA_SIZE_MASK) - size );
499 /* assign size plus previous arena flags */
500 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
502 else
504 /* Turn off PREV_FREE flag in next block */
505 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
506 if (pNext < (char *)subheap + subheap->size)
507 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
511 /***********************************************************************
512 * HEAP_InitSubHeap
514 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
515 DWORD commitSize, DWORD totalSize )
517 SUBHEAP *subheap;
518 FREE_LIST_ENTRY *pEntry;
519 int i;
521 /* Commit memory */
523 if (flags & HEAP_SHARED)
524 commitSize = totalSize; /* always commit everything in a shared heap */
525 if (NtAllocateVirtualMemory( GetCurrentProcess(), &address, address,
526 &commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
528 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
529 return FALSE;
532 /* Fill the sub-heap structure */
534 subheap = (SUBHEAP *)address;
535 subheap->heap = heap;
536 subheap->size = totalSize;
537 subheap->commitSize = commitSize;
538 subheap->magic = SUBHEAP_MAGIC;
540 if ( subheap != (SUBHEAP *)heap )
542 /* If this is a secondary subheap, insert it into list */
544 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
545 subheap->next = heap->subheap.next;
546 heap->subheap.next = subheap;
548 else
550 /* If this is a primary subheap, initialize main heap */
552 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
553 subheap->next = NULL;
554 heap->next = NULL;
555 heap->flags = flags;
556 heap->magic = HEAP_MAGIC;
558 /* Build the free lists */
560 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
562 pEntry->size = HEAP_freeListSizes[i];
563 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
564 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
565 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
566 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
567 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
568 pEntry->arena.magic = ARENA_FREE_MAGIC;
571 /* Initialize critical section */
573 RtlInitializeCriticalSection( &heap->critSection );
574 if (flags & HEAP_SHARED)
575 MakeCriticalSectionGlobal( &heap->critSection ); /* FIXME: dll separation */
578 /* Create the first free block */
580 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
581 subheap->size - subheap->headerSize );
583 return TRUE;
586 /***********************************************************************
587 * HEAP_CreateSubHeap
589 * Create a sub-heap of the given size.
590 * If heap == NULL, creates a main heap.
592 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
593 DWORD commitSize, DWORD totalSize )
595 LPVOID address = base;
597 /* round-up sizes on a 64K boundary */
598 totalSize = (totalSize + 0xffff) & 0xffff0000;
599 commitSize = (commitSize + 0xffff) & 0xffff0000;
600 if (!commitSize) commitSize = 0x10000;
601 if (totalSize < commitSize) totalSize = commitSize;
603 if (!address)
605 /* allocate the memory block */
606 if (NtAllocateVirtualMemory( GetCurrentProcess(), &address, NULL, &totalSize,
607 MEM_RESERVE, PAGE_EXECUTE_READWRITE ))
609 WARN("Could not allocate %08lx bytes\n", totalSize );
610 return NULL;
614 /* Initialize subheap */
616 if (!HEAP_InitSubHeap( heap ? heap : (HEAP *)address,
617 address, flags, commitSize, totalSize ))
619 ULONG size = 0;
620 if (!base) NtFreeVirtualMemory( GetCurrentProcess(), &address, &size, MEM_RELEASE );
621 return NULL;
624 return (SUBHEAP *)address;
628 /***********************************************************************
629 * HEAP_FindFreeBlock
631 * Find a free block at least as large as the requested size, and make sure
632 * the requested size is committed.
634 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
635 SUBHEAP **ppSubHeap )
637 SUBHEAP *subheap;
638 ARENA_FREE *pArena;
639 FREE_LIST_ENTRY *pEntry = heap->freeList;
641 /* Find a suitable free list, and in it find a block large enough */
643 while (pEntry->size < size) pEntry++;
644 pArena = pEntry->arena.next;
645 while (pArena != &heap->freeList[0].arena)
647 DWORD arena_size = (pArena->size & ARENA_SIZE_MASK) +
648 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
649 if (arena_size >= size)
651 subheap = HEAP_FindSubHeap( heap, pArena );
652 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
653 + size + HEAP_MIN_BLOCK_SIZE))
654 return NULL;
655 *ppSubHeap = subheap;
656 return pArena;
658 pArena = pArena->next;
661 /* If no block was found, attempt to grow the heap */
663 if (!(heap->flags & HEAP_GROWABLE))
665 WARN("Not enough space in heap %08lx for %08lx bytes\n",
666 (DWORD)heap, size );
667 return NULL;
669 /* make sure that we have a big enough size *committed* to fit another
670 * last free arena in !
671 * So just one heap struct, one first free arena which will eventually
672 * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
673 * might get assigned all remaining free space in HEAP_ShrinkBlock() */
674 size += ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
675 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, size,
676 max( HEAP_DEF_SIZE, size ) )))
677 return NULL;
679 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
680 (DWORD)subheap, size, (DWORD)heap );
682 *ppSubHeap = subheap;
683 return (ARENA_FREE *)(subheap + 1);
687 /***********************************************************************
688 * HEAP_IsValidArenaPtr
690 * Check that the pointer is inside the range possible for arenas.
692 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
694 int i;
695 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
696 if (!subheap) return FALSE;
697 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
698 if (subheap != &heap->subheap) return FALSE;
699 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
700 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
701 return FALSE;
705 /***********************************************************************
706 * HEAP_ValidateFreeArena
708 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
710 char *heapEnd = (char *)subheap + subheap->size;
712 /* Check for unaligned pointers */
713 if ( (long)pArena % ALIGNMENT != 0 )
715 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
716 (DWORD)subheap->heap, (DWORD)pArena );
717 return FALSE;
720 /* Check magic number */
721 if (pArena->magic != ARENA_FREE_MAGIC)
723 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
724 (DWORD)subheap->heap, (DWORD)pArena );
725 return FALSE;
727 /* Check size flags */
728 if (!(pArena->size & ARENA_FLAG_FREE) ||
729 (pArena->size & ARENA_FLAG_PREV_FREE))
731 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
732 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
734 /* Check arena size */
735 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
737 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
738 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
739 return FALSE;
741 /* Check that next pointer is valid */
742 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
744 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
745 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
746 return FALSE;
748 /* Check that next arena is free */
749 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
750 (pArena->next->magic != ARENA_FREE_MAGIC))
752 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
753 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
754 return FALSE;
756 /* Check that prev pointer is valid */
757 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
759 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
760 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
761 return FALSE;
763 /* Check that prev arena is free */
764 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
765 (pArena->prev->magic != ARENA_FREE_MAGIC))
767 /* this often means that the prev arena got overwritten
768 * by a memory write before that prev arena */
769 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
770 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
771 return FALSE;
773 /* Check that next block has PREV_FREE flag */
774 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
776 if (!(*(DWORD *)((char *)(pArena + 1) +
777 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
779 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
780 (DWORD)subheap->heap, (DWORD)pArena );
781 return FALSE;
783 /* Check next block back pointer */
784 if (*((ARENA_FREE **)((char *)(pArena + 1) +
785 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
787 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
788 (DWORD)subheap->heap, (DWORD)pArena,
789 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
790 return FALSE;
793 return TRUE;
797 /***********************************************************************
798 * HEAP_ValidateInUseArena
800 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
802 char *heapEnd = (char *)subheap + subheap->size;
804 /* Check for unaligned pointers */
805 if ( (long)pArena % ALIGNMENT != 0 )
807 if ( quiet == NOISY )
809 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
810 (DWORD)subheap->heap, (DWORD)pArena );
811 if ( TRACE_ON(heap) )
812 HEAP_Dump( subheap->heap );
814 else if ( WARN_ON(heap) )
816 WARN( "Heap %08lx: unaligned arena pointer %08lx\n",
817 (DWORD)subheap->heap, (DWORD)pArena );
818 if ( TRACE_ON(heap) )
819 HEAP_Dump( subheap->heap );
821 return FALSE;
824 /* Check magic number */
825 if (pArena->magic != ARENA_INUSE_MAGIC)
827 if (quiet == NOISY) {
828 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
829 (DWORD)subheap->heap, (DWORD)pArena );
830 if (TRACE_ON(heap))
831 HEAP_Dump( subheap->heap );
832 } else if (WARN_ON(heap)) {
833 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
834 (DWORD)subheap->heap, (DWORD)pArena );
835 if (TRACE_ON(heap))
836 HEAP_Dump( subheap->heap );
838 return FALSE;
840 /* Check size flags */
841 if (pArena->size & ARENA_FLAG_FREE)
843 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
844 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
846 /* Check arena size */
847 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
849 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
850 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
851 return FALSE;
853 /* Check next arena PREV_FREE flag */
854 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
855 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
857 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
858 (DWORD)subheap->heap, (DWORD)pArena );
859 return FALSE;
861 /* Check prev free arena */
862 if (pArena->size & ARENA_FLAG_PREV_FREE)
864 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
865 /* Check prev pointer */
866 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
868 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
869 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
870 return FALSE;
872 /* Check that prev arena is free */
873 if (!(pPrev->size & ARENA_FLAG_FREE) ||
874 (pPrev->magic != ARENA_FREE_MAGIC))
876 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
877 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
878 return FALSE;
880 /* Check that prev arena is really the previous block */
881 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
883 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
884 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
885 return FALSE;
888 return TRUE;
892 /***********************************************************************
893 * HEAP_IsRealArena [Internal]
894 * Validates a block is a valid arena.
896 * RETURNS
897 * TRUE: Success
898 * FALSE: Failure
900 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
901 DWORD flags, /* [in] Bit flags that control access during operation */
902 LPCVOID block, /* [in] Optional pointer to memory block to validate */
903 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
904 * does not complain */
906 SUBHEAP *subheap;
907 BOOL ret = TRUE;
909 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
911 ERR("Invalid heap %p!\n", heapPtr );
912 return FALSE;
915 flags &= HEAP_NO_SERIALIZE;
916 flags |= heapPtr->flags;
917 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
918 if (!(flags & HEAP_NO_SERIALIZE))
919 RtlEnterCriticalSection( &heapPtr->critSection );
921 if (block)
923 /* Only check this single memory block */
925 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
926 ((char *)block < (char *)subheap + subheap->headerSize
927 + sizeof(ARENA_INUSE)))
929 if (quiet == NOISY)
930 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
931 else if (WARN_ON(heap))
932 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
933 ret = FALSE;
934 } else
935 ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
937 if (!(flags & HEAP_NO_SERIALIZE))
938 RtlLeaveCriticalSection( &heapPtr->critSection );
939 return ret;
942 subheap = &heapPtr->subheap;
943 while (subheap && ret)
945 char *ptr = (char *)subheap + subheap->headerSize;
946 while (ptr < (char *)subheap + subheap->size)
948 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
950 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
951 ret = FALSE;
952 break;
954 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
956 else
958 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
959 ret = FALSE;
960 break;
962 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
965 subheap = subheap->next;
968 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
969 return ret;
973 /***********************************************************************
974 * RtlCreateHeap (NTDLL.@)
976 * Create a new Heap.
978 * PARAMS
979 * flags [I] HEAP_ flags from "winnt.h"
980 * addr [I] Desired base address
981 * totalSize [I] Total size of the heap, or 0 for a growable heap
982 * commitSize [I] Amount of heap space to commit
983 * unknown [I] Not yet understood
984 * definition [I] Heap definition
986 * RETURNS
987 * Success: A HANDLE to the newly created heap.
988 * Failure: a NULL HANDLE.
990 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, ULONG totalSize, ULONG commitSize,
991 PVOID unknown, PRTL_HEAP_DEFINITION definition )
993 SUBHEAP *subheap;
995 /* Allocate the heap block */
997 if (!totalSize)
999 totalSize = HEAP_DEF_SIZE;
1000 flags |= HEAP_GROWABLE;
1003 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1005 /* link it into the per-process heap list */
1006 if (processHeap)
1008 HEAP *heapPtr = subheap->heap;
1009 RtlLockHeap( processHeap );
1010 heapPtr->next = firstHeap;
1011 firstHeap = heapPtr;
1012 RtlUnlockHeap( processHeap );
1014 else /* assume the first heap we create is the process main heap */
1016 set_process_heap( (HANDLE)subheap->heap );
1018 return (HANDLE)subheap;
1022 /***********************************************************************
1023 * RtlDestroyHeap (NTDLL.@)
1025 * Destroy a Heap created with RtlCreateHeap().
1027 * PARAMS
1028 * heap [I] Heap to destroy.
1030 * RETURNS
1031 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1032 * Failure: The Heap handle, if heap is the process heap.
1034 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1036 HEAP *heapPtr = HEAP_GetPtr( heap );
1037 SUBHEAP *subheap;
1039 TRACE("%p\n", heap );
1040 if (!heapPtr) return heap;
1042 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1043 else /* remove it from the per-process list */
1045 HEAP **pptr;
1046 RtlLockHeap( processHeap );
1047 pptr = &firstHeap;
1048 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1049 if (*pptr) *pptr = (*pptr)->next;
1050 RtlUnlockHeap( processHeap );
1053 RtlDeleteCriticalSection( &heapPtr->critSection );
1054 subheap = &heapPtr->subheap;
1055 while (subheap)
1057 SUBHEAP *next = subheap->next;
1058 ULONG size = 0;
1059 void *addr = subheap;
1060 NtFreeVirtualMemory( GetCurrentProcess(), &addr, &size, MEM_RELEASE );
1061 subheap = next;
1063 return 0;
1067 /***********************************************************************
1068 * RtlAllocateHeap (NTDLL.@)
1070 * Allocate a memory block from a Heap.
1072 * PARAMS
1073 * heap [I] Heap to allocate block from
1074 * flags [I] HEAP_ flags from "winnt.h"
1075 * size [I] Size of the memory block to allocate
1077 * RETURNS
1078 * Success: A pointer to the newly allocated block
1079 * Failure: NULL.
1081 * NOTES
1082 * This call does not SetLastError().
1084 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, ULONG size )
1086 ARENA_FREE *pArena;
1087 ARENA_INUSE *pInUse;
1088 SUBHEAP *subheap;
1089 HEAP *heapPtr = HEAP_GetPtr( heap );
1091 /* Validate the parameters */
1093 if (!heapPtr) return NULL;
1094 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1095 flags |= heapPtr->flags;
1096 size = ROUND_SIZE(size);
1097 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1099 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1100 /* Locate a suitable free block */
1102 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1104 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1105 heap, flags, size );
1106 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1107 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1108 return NULL;
1111 /* Remove the arena from the free list */
1113 pArena->next->prev = pArena->prev;
1114 pArena->prev->next = pArena->next;
1116 /* Build the in-use arena */
1118 pInUse = (ARENA_INUSE *)pArena;
1120 /* in-use arena is smaller than free arena,
1121 * so we have to add the difference to the size */
1122 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1123 pInUse->magic = ARENA_INUSE_MAGIC;
1125 /* Shrink the block */
1127 HEAP_ShrinkBlock( subheap, pInUse, size );
1129 if (flags & HEAP_ZERO_MEMORY)
1130 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1131 else
1132 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1134 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1136 TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1137 heap, flags, size, (DWORD)(pInUse + 1) );
1138 return (LPVOID)(pInUse + 1);
1142 /***********************************************************************
1143 * RtlFreeHeap (NTDLL.@)
1145 * Free a memory block allocated with RtlAllocateHeap().
1147 * PARAMS
1148 * heap [I] Heap that block was allocated from
1149 * flags [I] HEAP_ flags from "winnt.h"
1150 * ptr [I] Block to free
1152 * RETURNS
1153 * Success: TRUE, if ptr is NULL or was freed successfully.
1154 * Failure: FALSE.
1156 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1158 ARENA_INUSE *pInUse;
1159 SUBHEAP *subheap;
1160 HEAP *heapPtr = HEAP_GetPtr( heap );
1162 /* Validate the parameters */
1164 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1165 if (!heapPtr)
1167 set_status( STATUS_INVALID_HANDLE );
1168 return FALSE;
1171 flags &= HEAP_NO_SERIALIZE;
1172 flags |= heapPtr->flags;
1173 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1174 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1176 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1177 set_status( STATUS_INVALID_PARAMETER );
1178 TRACE("(%p,%08lx,%08lx): returning FALSE\n",
1179 heap, flags, (DWORD)ptr );
1180 return FALSE;
1183 /* Turn the block into a free block */
1185 pInUse = (ARENA_INUSE *)ptr - 1;
1186 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1187 HEAP_MakeInUseBlockFree( subheap, pInUse );
1189 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1191 TRACE("(%p,%08lx,%08lx): returning TRUE\n",
1192 heap, flags, (DWORD)ptr );
1193 return TRUE;
1197 /***********************************************************************
1198 * RtlReAllocateHeap (NTDLL.@)
1200 * Change the size of a memory block allocated with RtlAllocateHeap().
1202 * PARAMS
1203 * heap [I] Heap that block was allocated from
1204 * flags [I] HEAP_ flags from "winnt.h"
1205 * ptr [I] Block to resize
1206 * size [I] Size of the memory block to allocate
1208 * RETURNS
1209 * Success: A pointer to the resized block (which may be different).
1210 * Failure: NULL.
1212 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, ULONG size )
1214 ARENA_INUSE *pArena;
1215 DWORD oldSize;
1216 HEAP *heapPtr;
1217 SUBHEAP *subheap;
1219 if (!ptr) return RtlAllocateHeap( heap, flags, size ); /* FIXME: correct? */
1220 if (!(heapPtr = HEAP_GetPtr( heap )))
1222 set_status( STATUS_INVALID_HANDLE );
1223 return FALSE;
1226 /* Validate the parameters */
1228 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1229 HEAP_REALLOC_IN_PLACE_ONLY;
1230 flags |= heapPtr->flags;
1231 size = ROUND_SIZE(size);
1232 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1234 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1235 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1237 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1238 set_status( STATUS_INVALID_PARAMETER );
1239 TRACE("(%p,%08lx,%08lx,%08lx): returning NULL\n",
1240 heap, flags, (DWORD)ptr, size );
1241 return NULL;
1244 /* Check if we need to grow the block */
1246 pArena = (ARENA_INUSE *)ptr - 1;
1247 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1248 oldSize = (pArena->size & ARENA_SIZE_MASK);
1249 if (size > oldSize)
1251 char *pNext = (char *)(pArena + 1) + oldSize;
1252 if ((pNext < (char *)subheap + subheap->size) &&
1253 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1254 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1256 /* The next block is free and large enough */
1257 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1258 pFree->next->prev = pFree->prev;
1259 pFree->prev->next = pFree->next;
1260 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1261 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1262 + size + HEAP_MIN_BLOCK_SIZE))
1264 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1265 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1266 set_status( STATUS_NO_MEMORY );
1267 return NULL;
1269 HEAP_ShrinkBlock( subheap, pArena, size );
1271 else /* Do it the hard way */
1273 ARENA_FREE *pNew;
1274 ARENA_INUSE *pInUse;
1275 SUBHEAP *newsubheap;
1277 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1278 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1280 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1281 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1282 set_status( STATUS_NO_MEMORY );
1283 return NULL;
1286 /* Build the in-use arena */
1288 pNew->next->prev = pNew->prev;
1289 pNew->prev->next = pNew->next;
1290 pInUse = (ARENA_INUSE *)pNew;
1291 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1292 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1293 pInUse->magic = ARENA_INUSE_MAGIC;
1294 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1295 mark_block_initialized( pInUse + 1, oldSize );
1296 memcpy( pInUse + 1, pArena + 1, oldSize );
1298 /* Free the previous block */
1300 HEAP_MakeInUseBlockFree( subheap, pArena );
1301 subheap = newsubheap;
1302 pArena = pInUse;
1305 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1307 /* Clear the extra bytes if needed */
1309 if (size > oldSize)
1311 if (flags & HEAP_ZERO_MEMORY)
1312 clear_block( (char *)(pArena + 1) + oldSize,
1313 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1314 else
1315 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1316 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1319 /* Return the new arena */
1321 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1323 TRACE("(%p,%08lx,%08lx,%08lx): returning %08lx\n",
1324 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1325 return (LPVOID)(pArena + 1);
1329 /***********************************************************************
1330 * RtlCompactHeap (NTDLL.@)
1332 * Compact the free space in a Heap.
1334 * PARAMS
1335 * heap [I] Heap that block was allocated from
1336 * flags [I] HEAP_ flags from "winnt.h"
1338 * RETURNS
1339 * The number of bytes compacted.
1341 * NOTES
1342 * This function is a harmless stub.
1344 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1346 FIXME( "stub\n" );
1347 return 0;
1351 /***********************************************************************
1352 * RtlLockHeap (NTDLL.@)
1354 * Lock a Heap.
1356 * PARAMS
1357 * heap [I] Heap to lock
1359 * RETURNS
1360 * Success: TRUE. The Heap is locked.
1361 * Failure: FALSE, if heap is invalid.
1363 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1365 HEAP *heapPtr = HEAP_GetPtr( heap );
1366 if (!heapPtr) return FALSE;
1367 RtlEnterCriticalSection( &heapPtr->critSection );
1368 return TRUE;
1372 /***********************************************************************
1373 * RtlUnlockHeap (NTDLL.@)
1375 * Unlock a Heap.
1377 * PARAMS
1378 * heap [I] Heap to unlock
1380 * RETURNS
1381 * Success: TRUE. The Heap is unlocked.
1382 * Failure: FALSE, if heap is invalid.
1384 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1386 HEAP *heapPtr = HEAP_GetPtr( heap );
1387 if (!heapPtr) return FALSE;
1388 RtlLeaveCriticalSection( &heapPtr->critSection );
1389 return TRUE;
1393 /***********************************************************************
1394 * RtlSizeHeap (NTDLL.@)
1396 * Get the actual size of a memory block allocated from a Heap.
1398 * PARAMS
1399 * heap [I] Heap that block was allocated from
1400 * flags [I] HEAP_ flags from "winnt.h"
1401 * ptr [I] Block to get the size of
1403 * RETURNS
1404 * Success: The size of the block.
1405 * Failure: -1, heap or ptr are invalid.
1407 * NOTES
1408 * The size may be bigger than what was passed to RtlAllocateHeap().
1410 ULONG WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1412 DWORD ret;
1413 HEAP *heapPtr = HEAP_GetPtr( heap );
1415 if (!heapPtr)
1417 set_status( STATUS_INVALID_HANDLE );
1418 return (ULONG)-1;
1420 flags &= HEAP_NO_SERIALIZE;
1421 flags |= heapPtr->flags;
1422 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1423 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1425 set_status( STATUS_INVALID_PARAMETER );
1426 ret = (ULONG)-1;
1428 else
1430 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1431 ret = pArena->size & ARENA_SIZE_MASK;
1433 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1435 TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1436 heap, flags, (DWORD)ptr, ret );
1437 return ret;
1441 /***********************************************************************
1442 * RtlValidateHeap (NTDLL.@)
1444 * Determine if a block is a valid alloction from a heap.
1446 * PARAMS
1447 * heap [I] Heap that block was allocated from
1448 * flags [I] HEAP_ flags from "winnt.h"
1449 * ptr [I] Block to check
1451 * RETURNS
1452 * Success: TRUE. The block was allocated from heap.
1453 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1455 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1457 HEAP *heapPtr = HEAP_GetPtr( heap );
1458 if (!heapPtr) return FALSE;
1459 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1463 /***********************************************************************
1464 * RtlWalkHeap (NTDLL.@)
1466 * FIXME
1467 * The PROCESS_HEAP_ENTRY flag values seem different between this
1468 * function and HeapWalk(). To be checked.
1470 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1472 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1473 HEAP *heapPtr = HEAP_GetPtr(heap);
1474 SUBHEAP *sub, *currentheap = NULL;
1475 NTSTATUS ret;
1476 char *ptr;
1477 int region_index = 0;
1479 FIXME( "not fully compatible\n" );
1481 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1483 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1485 /* set ptr to the next arena to be examined */
1487 if (!entry->lpData) /* first call (init) ? */
1489 TRACE("begin walking of heap %p.\n", heap);
1490 currentheap = &heapPtr->subheap;
1491 ptr = (char*)currentheap + currentheap->headerSize;
1493 else
1495 ptr = entry->lpData;
1496 sub = &heapPtr->subheap;
1497 while (sub)
1499 if (((char *)ptr >= (char *)sub) &&
1500 ((char *)ptr < (char *)sub + sub->size))
1502 currentheap = sub;
1503 break;
1505 sub = sub->next;
1506 region_index++;
1508 if (currentheap == NULL)
1510 ERR("no matching subheap found, shouldn't happen !\n");
1511 ret = STATUS_NO_MORE_ENTRIES;
1512 goto HW_end;
1515 ptr += entry->cbData; /* point to next arena */
1516 if (ptr > (char *)currentheap + currentheap->size - 1)
1517 { /* proceed with next subheap */
1518 if (!(currentheap = currentheap->next))
1519 { /* successfully finished */
1520 TRACE("end reached.\n");
1521 ret = STATUS_NO_MORE_ENTRIES;
1522 goto HW_end;
1524 ptr = (char*)currentheap + currentheap->headerSize;
1528 entry->wFlags = 0;
1529 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1531 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1533 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1535 entry->lpData = pArena + 1;
1536 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1537 entry->cbOverhead = sizeof(ARENA_FREE);
1538 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1540 else
1542 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1544 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1546 entry->lpData = pArena + 1;
1547 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1548 entry->cbOverhead = sizeof(ARENA_INUSE);
1549 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1550 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1551 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1554 entry->iRegionIndex = region_index;
1556 /* first element of heap ? */
1557 if (ptr == (char *)(currentheap + currentheap->headerSize))
1559 entry->wFlags |= PROCESS_HEAP_REGION;
1560 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1561 entry->u.Region.dwUnCommittedSize =
1562 currentheap->size - currentheap->commitSize;
1563 entry->u.Region.lpFirstBlock = /* first valid block */
1564 currentheap + currentheap->headerSize;
1565 entry->u.Region.lpLastBlock = /* first invalid block */
1566 currentheap + currentheap->size;
1568 ret = STATUS_SUCCESS;
1570 HW_end:
1571 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1572 return ret;
1576 /***********************************************************************
1577 * RtlGetProcessHeaps (NTDLL.@)
1579 * Get the Heaps belonging to the current process.
1581 * PARAMS
1582 * count [I] size of heaps
1583 * heaps [O] Destination array for heap HANDLE's
1585 * RETURNS
1586 * Success: The number of Heaps allocated by the process.
1587 * Failure: 0.
1589 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1591 DWORD total;
1592 HEAP *ptr;
1594 if (!processHeap) return 0; /* should never happen */
1595 total = 1; /* main heap */
1596 RtlLockHeap( processHeap );
1597 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1598 if (total <= count)
1600 *heaps++ = (HANDLE)processHeap;
1601 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1603 RtlUnlockHeap( processHeap );
1604 return total;