Protect BeginPaint and EndPaint from lps being NULL.
[wine/multimedia.git] / dlls / ntdll / heap.c
blobe06b8b51e53eb973505aa44c02f87809496c3e6f
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 inline void HEAP_InsertFreeBlock( HEAP *heap, ARENA_FREE *pArena, BOOL last )
295 FREE_LIST_ENTRY *pEntry = heap->freeList;
296 while (pEntry->size < pArena->size) pEntry++;
297 if (last)
299 /* insert at end of free list, i.e. before the next free list entry */
300 pEntry++;
301 if (pEntry == &heap->freeList[HEAP_NB_FREE_LISTS]) pEntry = heap->freeList;
302 pArena->prev = pEntry->arena.prev;
303 pArena->prev->next = pArena;
304 pArena->next = &pEntry->arena;
305 pEntry->arena.prev = pArena;
307 else
309 /* insert at head of free list */
310 pArena->next = pEntry->arena.next;
311 pArena->next->prev = pArena;
312 pArena->prev = &pEntry->arena;
313 pEntry->arena.next = pArena;
315 pArena->size |= ARENA_FLAG_FREE;
319 /***********************************************************************
320 * HEAP_FindSubHeap
321 * Find the sub-heap containing a given address.
323 * RETURNS
324 * Pointer: Success
325 * NULL: Failure
327 static SUBHEAP *HEAP_FindSubHeap(
328 HEAP *heap, /* [in] Heap pointer */
329 LPCVOID ptr /* [in] Address */
331 SUBHEAP *sub = &heap->subheap;
332 while (sub)
334 if (((char *)ptr >= (char *)sub) &&
335 ((char *)ptr < (char *)sub + sub->size)) return sub;
336 sub = sub->next;
338 return NULL;
342 /***********************************************************************
343 * HEAP_Commit
345 * Make sure the heap storage is committed up to (not including) ptr.
347 static inline BOOL HEAP_Commit( SUBHEAP *subheap, void *ptr )
349 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
350 size = (size + COMMIT_MASK) & ~COMMIT_MASK;
351 if (size > subheap->size) size = subheap->size;
352 if (size <= subheap->commitSize) return TRUE;
353 size -= subheap->commitSize;
354 if (NtAllocateVirtualMemory( GetCurrentProcess(), &ptr, (char *)subheap + subheap->commitSize,
355 &size, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
357 WARN("Could not commit %08lx bytes at %08lx for heap %08lx\n",
358 size, (DWORD)((char *)subheap + subheap->commitSize),
359 (DWORD)subheap->heap );
360 return FALSE;
362 subheap->commitSize += size;
363 return TRUE;
367 /***********************************************************************
368 * HEAP_Decommit
370 * If possible, decommit the heap storage from (including) 'ptr'.
372 static inline BOOL HEAP_Decommit( SUBHEAP *subheap, void *ptr )
374 void *addr;
375 ULONG decommit_size;
377 DWORD size = (DWORD)((char *)ptr - (char *)subheap);
378 /* round to next block and add one full block */
379 size = ((size + COMMIT_MASK) & ~COMMIT_MASK) + COMMIT_MASK + 1;
380 if (size >= subheap->commitSize) return TRUE;
381 decommit_size = subheap->commitSize - size;
382 addr = (char *)subheap + size;
384 if (NtFreeVirtualMemory( GetCurrentProcess(), &addr, &decommit_size, MEM_DECOMMIT ))
386 WARN("Could not decommit %08lx bytes at %08lx for heap %p\n",
387 decommit_size, (DWORD)((char *)subheap + size), subheap->heap );
388 return FALSE;
390 subheap->commitSize -= decommit_size;
391 return TRUE;
395 /***********************************************************************
396 * HEAP_CreateFreeBlock
398 * Create a free block at a specified address. 'size' is the size of the
399 * whole block, including the new arena.
401 static void HEAP_CreateFreeBlock( SUBHEAP *subheap, void *ptr, DWORD size )
403 ARENA_FREE *pFree;
404 char *pEnd;
405 BOOL last;
407 /* Create a free arena */
408 mark_block_uninitialized( ptr, sizeof( ARENA_FREE ) );
409 pFree = (ARENA_FREE *)ptr;
410 pFree->magic = ARENA_FREE_MAGIC;
412 /* If debugging, erase the freed block content */
414 pEnd = (char *)ptr + size;
415 if (pEnd > (char *)subheap + subheap->commitSize) pEnd = (char *)subheap + subheap->commitSize;
416 if (pEnd > (char *)(pFree + 1)) mark_block_free( pFree + 1, pEnd - (char *)(pFree + 1) );
418 /* Check if next block is free also */
420 if (((char *)ptr + size < (char *)subheap + subheap->size) &&
421 (*(DWORD *)((char *)ptr + size) & ARENA_FLAG_FREE))
423 /* Remove the next arena from the free list */
424 ARENA_FREE *pNext = (ARENA_FREE *)((char *)ptr + size);
425 pNext->next->prev = pNext->prev;
426 pNext->prev->next = pNext->next;
427 size += (pNext->size & ARENA_SIZE_MASK) + sizeof(*pNext);
428 mark_block_free( pNext, sizeof(ARENA_FREE) );
431 /* Set the next block PREV_FREE flag and pointer */
433 last = ((char *)ptr + size >= (char *)subheap + subheap->size);
434 if (!last)
436 DWORD *pNext = (DWORD *)((char *)ptr + size);
437 *pNext |= ARENA_FLAG_PREV_FREE;
438 mark_block_initialized( pNext - 1, sizeof( ARENA_FREE * ) );
439 *(ARENA_FREE **)(pNext - 1) = pFree;
442 /* Last, insert the new block into the free list */
444 pFree->size = size - sizeof(*pFree);
445 HEAP_InsertFreeBlock( subheap->heap, pFree, last );
449 /***********************************************************************
450 * HEAP_MakeInUseBlockFree
452 * Turn an in-use block into a free block. Can also decommit the end of
453 * the heap, and possibly even free the sub-heap altogether.
455 static void HEAP_MakeInUseBlockFree( SUBHEAP *subheap, ARENA_INUSE *pArena )
457 ARENA_FREE *pFree;
458 DWORD size = (pArena->size & ARENA_SIZE_MASK) + sizeof(*pArena);
460 /* Check if we can merge with previous block */
462 if (pArena->size & ARENA_FLAG_PREV_FREE)
464 pFree = *((ARENA_FREE **)pArena - 1);
465 size += (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
466 /* Remove it from the free list */
467 pFree->next->prev = pFree->prev;
468 pFree->prev->next = pFree->next;
470 else pFree = (ARENA_FREE *)pArena;
472 /* Create a free block */
474 HEAP_CreateFreeBlock( subheap, pFree, size );
475 size = (pFree->size & ARENA_SIZE_MASK) + sizeof(ARENA_FREE);
476 if ((char *)pFree + size < (char *)subheap + subheap->size)
477 return; /* Not the last block, so nothing more to do */
479 /* Free the whole sub-heap if it's empty and not the original one */
481 if (((char *)pFree == (char *)subheap + subheap->headerSize) &&
482 (subheap != &subheap->heap->subheap))
484 ULONG size = 0;
485 SUBHEAP *pPrev = &subheap->heap->subheap;
486 /* Remove the free block from the list */
487 pFree->next->prev = pFree->prev;
488 pFree->prev->next = pFree->next;
489 /* Remove the subheap from the list */
490 while (pPrev && (pPrev->next != subheap)) pPrev = pPrev->next;
491 if (pPrev) pPrev->next = subheap->next;
492 /* Free the memory */
493 subheap->magic = 0;
494 NtFreeVirtualMemory( GetCurrentProcess(), (void **)&subheap, &size, MEM_RELEASE );
495 return;
498 /* Decommit the end of the heap */
500 if (!(subheap->heap->flags & HEAP_SHARED)) HEAP_Decommit( subheap, pFree + 1 );
504 /***********************************************************************
505 * HEAP_ShrinkBlock
507 * Shrink an in-use block.
509 static void HEAP_ShrinkBlock(SUBHEAP *subheap, ARENA_INUSE *pArena, DWORD size)
511 if ((pArena->size & ARENA_SIZE_MASK) >= size + HEAP_MIN_BLOCK_SIZE)
513 HEAP_CreateFreeBlock( subheap, (char *)(pArena + 1) + size,
514 (pArena->size & ARENA_SIZE_MASK) - size );
515 /* assign size plus previous arena flags */
516 pArena->size = size | (pArena->size & ~ARENA_SIZE_MASK);
518 else
520 /* Turn off PREV_FREE flag in next block */
521 char *pNext = (char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK);
522 if (pNext < (char *)subheap + subheap->size)
523 *(DWORD *)pNext &= ~ARENA_FLAG_PREV_FREE;
527 /***********************************************************************
528 * HEAP_InitSubHeap
530 static BOOL HEAP_InitSubHeap( HEAP *heap, LPVOID address, DWORD flags,
531 DWORD commitSize, DWORD totalSize )
533 SUBHEAP *subheap;
534 FREE_LIST_ENTRY *pEntry;
535 int i;
537 /* Commit memory */
539 if (flags & HEAP_SHARED)
540 commitSize = totalSize; /* always commit everything in a shared heap */
541 if (NtAllocateVirtualMemory( GetCurrentProcess(), &address, address,
542 &commitSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE))
544 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize, address );
545 return FALSE;
548 /* Fill the sub-heap structure */
550 subheap = (SUBHEAP *)address;
551 subheap->heap = heap;
552 subheap->size = totalSize;
553 subheap->commitSize = commitSize;
554 subheap->magic = SUBHEAP_MAGIC;
556 if ( subheap != (SUBHEAP *)heap )
558 /* If this is a secondary subheap, insert it into list */
560 subheap->headerSize = ROUND_SIZE( sizeof(SUBHEAP) );
561 subheap->next = heap->subheap.next;
562 heap->subheap.next = subheap;
564 else
566 /* If this is a primary subheap, initialize main heap */
568 subheap->headerSize = ROUND_SIZE( sizeof(HEAP) );
569 subheap->next = NULL;
570 heap->next = NULL;
571 heap->flags = flags;
572 heap->magic = HEAP_MAGIC;
574 /* Build the free lists */
576 for (i = 0, pEntry = heap->freeList; i < HEAP_NB_FREE_LISTS; i++, pEntry++)
578 pEntry->size = HEAP_freeListSizes[i];
579 pEntry->arena.size = 0 | ARENA_FLAG_FREE;
580 pEntry->arena.next = i < HEAP_NB_FREE_LISTS-1 ?
581 &heap->freeList[i+1].arena : &heap->freeList[0].arena;
582 pEntry->arena.prev = i ? &heap->freeList[i-1].arena :
583 &heap->freeList[HEAP_NB_FREE_LISTS-1].arena;
584 pEntry->arena.magic = ARENA_FREE_MAGIC;
587 /* Initialize critical section */
589 RtlInitializeCriticalSection( &heap->critSection );
590 if (flags & HEAP_SHARED)
591 MakeCriticalSectionGlobal( &heap->critSection ); /* FIXME: dll separation */
594 /* Create the first free block */
596 HEAP_CreateFreeBlock( subheap, (LPBYTE)subheap + subheap->headerSize,
597 subheap->size - subheap->headerSize );
599 return TRUE;
602 /***********************************************************************
603 * HEAP_CreateSubHeap
605 * Create a sub-heap of the given size.
606 * If heap == NULL, creates a main heap.
608 static SUBHEAP *HEAP_CreateSubHeap( HEAP *heap, void *base, DWORD flags,
609 DWORD commitSize, DWORD totalSize )
611 LPVOID address = base;
613 /* round-up sizes on a 64K boundary */
614 totalSize = (totalSize + 0xffff) & 0xffff0000;
615 commitSize = (commitSize + 0xffff) & 0xffff0000;
616 if (!commitSize) commitSize = 0x10000;
617 if (totalSize < commitSize) totalSize = commitSize;
619 if (!address)
621 /* allocate the memory block */
622 if (NtAllocateVirtualMemory( GetCurrentProcess(), &address, NULL, &totalSize,
623 MEM_RESERVE, PAGE_EXECUTE_READWRITE ))
625 WARN("Could not allocate %08lx bytes\n", totalSize );
626 return NULL;
630 /* Initialize subheap */
632 if (!HEAP_InitSubHeap( heap ? heap : (HEAP *)address,
633 address, flags, commitSize, totalSize ))
635 ULONG size = 0;
636 if (!base) NtFreeVirtualMemory( GetCurrentProcess(), &address, &size, MEM_RELEASE );
637 return NULL;
640 return (SUBHEAP *)address;
644 /***********************************************************************
645 * HEAP_FindFreeBlock
647 * Find a free block at least as large as the requested size, and make sure
648 * the requested size is committed.
650 static ARENA_FREE *HEAP_FindFreeBlock( HEAP *heap, DWORD size,
651 SUBHEAP **ppSubHeap )
653 SUBHEAP *subheap;
654 ARENA_FREE *pArena;
655 FREE_LIST_ENTRY *pEntry = heap->freeList;
657 /* Find a suitable free list, and in it find a block large enough */
659 while (pEntry->size < size) pEntry++;
660 pArena = pEntry->arena.next;
661 while (pArena != &heap->freeList[0].arena)
663 DWORD arena_size = (pArena->size & ARENA_SIZE_MASK) +
664 sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
665 if (arena_size >= size)
667 subheap = HEAP_FindSubHeap( heap, pArena );
668 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
669 + size + HEAP_MIN_BLOCK_SIZE))
670 return NULL;
671 *ppSubHeap = subheap;
672 return pArena;
674 pArena = pArena->next;
677 /* If no block was found, attempt to grow the heap */
679 if (!(heap->flags & HEAP_GROWABLE))
681 WARN("Not enough space in heap %08lx for %08lx bytes\n",
682 (DWORD)heap, size );
683 return NULL;
685 /* make sure that we have a big enough size *committed* to fit another
686 * last free arena in !
687 * So just one heap struct, one first free arena which will eventually
688 * get inuse, and HEAP_MIN_BLOCK_SIZE for the second free arena that
689 * might get assigned all remaining free space in HEAP_ShrinkBlock() */
690 size += ROUND_SIZE(sizeof(SUBHEAP)) + sizeof(ARENA_INUSE) + HEAP_MIN_BLOCK_SIZE;
691 if (!(subheap = HEAP_CreateSubHeap( heap, NULL, heap->flags, size,
692 max( HEAP_DEF_SIZE, size ) )))
693 return NULL;
695 TRACE("created new sub-heap %08lx of %08lx bytes for heap %08lx\n",
696 (DWORD)subheap, size, (DWORD)heap );
698 *ppSubHeap = subheap;
699 return (ARENA_FREE *)(subheap + 1);
703 /***********************************************************************
704 * HEAP_IsValidArenaPtr
706 * Check that the pointer is inside the range possible for arenas.
708 static BOOL HEAP_IsValidArenaPtr( HEAP *heap, void *ptr )
710 int i;
711 SUBHEAP *subheap = HEAP_FindSubHeap( heap, ptr );
712 if (!subheap) return FALSE;
713 if ((char *)ptr >= (char *)subheap + subheap->headerSize) return TRUE;
714 if (subheap != &heap->subheap) return FALSE;
715 for (i = 0; i < HEAP_NB_FREE_LISTS; i++)
716 if (ptr == (void *)&heap->freeList[i].arena) return TRUE;
717 return FALSE;
721 /***********************************************************************
722 * HEAP_ValidateFreeArena
724 static BOOL HEAP_ValidateFreeArena( SUBHEAP *subheap, ARENA_FREE *pArena )
726 char *heapEnd = (char *)subheap + subheap->size;
728 /* Check for unaligned pointers */
729 if ( (long)pArena % ALIGNMENT != 0 )
731 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
732 (DWORD)subheap->heap, (DWORD)pArena );
733 return FALSE;
736 /* Check magic number */
737 if (pArena->magic != ARENA_FREE_MAGIC)
739 ERR("Heap %08lx: invalid free arena magic for %08lx\n",
740 (DWORD)subheap->heap, (DWORD)pArena );
741 return FALSE;
743 /* Check size flags */
744 if (!(pArena->size & ARENA_FLAG_FREE) ||
745 (pArena->size & ARENA_FLAG_PREV_FREE))
747 ERR("Heap %08lx: bad flags %lx for free arena %08lx\n",
748 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
750 /* Check arena size */
751 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
753 ERR("Heap %08lx: bad size %08lx for free arena %08lx\n",
754 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
755 return FALSE;
757 /* Check that next pointer is valid */
758 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->next ))
760 ERR("Heap %08lx: bad next ptr %08lx for arena %08lx\n",
761 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
762 return FALSE;
764 /* Check that next arena is free */
765 if (!(pArena->next->size & ARENA_FLAG_FREE) ||
766 (pArena->next->magic != ARENA_FREE_MAGIC))
768 ERR("Heap %08lx: next arena %08lx invalid for %08lx\n",
769 (DWORD)subheap->heap, (DWORD)pArena->next, (DWORD)pArena );
770 return FALSE;
772 /* Check that prev pointer is valid */
773 if (!HEAP_IsValidArenaPtr( subheap->heap, pArena->prev ))
775 ERR("Heap %08lx: bad prev ptr %08lx for arena %08lx\n",
776 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
777 return FALSE;
779 /* Check that prev arena is free */
780 if (!(pArena->prev->size & ARENA_FLAG_FREE) ||
781 (pArena->prev->magic != ARENA_FREE_MAGIC))
783 /* this often means that the prev arena got overwritten
784 * by a memory write before that prev arena */
785 ERR("Heap %08lx: prev arena %08lx invalid for %08lx\n",
786 (DWORD)subheap->heap, (DWORD)pArena->prev, (DWORD)pArena );
787 return FALSE;
789 /* Check that next block has PREV_FREE flag */
790 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd)
792 if (!(*(DWORD *)((char *)(pArena + 1) +
793 (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
795 ERR("Heap %08lx: free arena %08lx next block has no PREV_FREE flag\n",
796 (DWORD)subheap->heap, (DWORD)pArena );
797 return FALSE;
799 /* Check next block back pointer */
800 if (*((ARENA_FREE **)((char *)(pArena + 1) +
801 (pArena->size & ARENA_SIZE_MASK)) - 1) != pArena)
803 ERR("Heap %08lx: arena %08lx has wrong back ptr %08lx\n",
804 (DWORD)subheap->heap, (DWORD)pArena,
805 *((DWORD *)((char *)(pArena+1)+ (pArena->size & ARENA_SIZE_MASK)) - 1));
806 return FALSE;
809 return TRUE;
813 /***********************************************************************
814 * HEAP_ValidateInUseArena
816 static BOOL HEAP_ValidateInUseArena( SUBHEAP *subheap, ARENA_INUSE *pArena, BOOL quiet )
818 char *heapEnd = (char *)subheap + subheap->size;
820 /* Check for unaligned pointers */
821 if ( (long)pArena % ALIGNMENT != 0 )
823 if ( quiet == NOISY )
825 ERR( "Heap %08lx: unaligned arena pointer %08lx\n",
826 (DWORD)subheap->heap, (DWORD)pArena );
827 if ( TRACE_ON(heap) )
828 HEAP_Dump( subheap->heap );
830 else if ( WARN_ON(heap) )
832 WARN( "Heap %08lx: unaligned arena pointer %08lx\n",
833 (DWORD)subheap->heap, (DWORD)pArena );
834 if ( TRACE_ON(heap) )
835 HEAP_Dump( subheap->heap );
837 return FALSE;
840 /* Check magic number */
841 if (pArena->magic != ARENA_INUSE_MAGIC)
843 if (quiet == NOISY) {
844 ERR("Heap %08lx: invalid in-use arena magic for %08lx\n",
845 (DWORD)subheap->heap, (DWORD)pArena );
846 if (TRACE_ON(heap))
847 HEAP_Dump( subheap->heap );
848 } else if (WARN_ON(heap)) {
849 WARN("Heap %08lx: invalid in-use arena magic for %08lx\n",
850 (DWORD)subheap->heap, (DWORD)pArena );
851 if (TRACE_ON(heap))
852 HEAP_Dump( subheap->heap );
854 return FALSE;
856 /* Check size flags */
857 if (pArena->size & ARENA_FLAG_FREE)
859 ERR("Heap %08lx: bad flags %lx for in-use arena %08lx\n",
860 (DWORD)subheap->heap, pArena->size & ~ARENA_SIZE_MASK, (DWORD)pArena );
862 /* Check arena size */
863 if ((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) > heapEnd)
865 ERR("Heap %08lx: bad size %08lx for in-use arena %08lx\n",
866 (DWORD)subheap->heap, (DWORD)pArena->size & ARENA_SIZE_MASK, (DWORD)pArena );
867 return FALSE;
869 /* Check next arena PREV_FREE flag */
870 if (((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK) < heapEnd) &&
871 (*(DWORD *)((char *)(pArena + 1) + (pArena->size & ARENA_SIZE_MASK)) & ARENA_FLAG_PREV_FREE))
873 ERR("Heap %08lx: in-use arena %08lx next block has PREV_FREE flag\n",
874 (DWORD)subheap->heap, (DWORD)pArena );
875 return FALSE;
877 /* Check prev free arena */
878 if (pArena->size & ARENA_FLAG_PREV_FREE)
880 ARENA_FREE *pPrev = *((ARENA_FREE **)pArena - 1);
881 /* Check prev pointer */
882 if (!HEAP_IsValidArenaPtr( subheap->heap, pPrev ))
884 ERR("Heap %08lx: bad back ptr %08lx for arena %08lx\n",
885 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
886 return FALSE;
888 /* Check that prev arena is free */
889 if (!(pPrev->size & ARENA_FLAG_FREE) ||
890 (pPrev->magic != ARENA_FREE_MAGIC))
892 ERR("Heap %08lx: prev arena %08lx invalid for in-use %08lx\n",
893 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
894 return FALSE;
896 /* Check that prev arena is really the previous block */
897 if ((char *)(pPrev + 1) + (pPrev->size & ARENA_SIZE_MASK) != (char *)pArena)
899 ERR("Heap %08lx: prev arena %08lx is not prev for in-use %08lx\n",
900 (DWORD)subheap->heap, (DWORD)pPrev, (DWORD)pArena );
901 return FALSE;
904 return TRUE;
908 /***********************************************************************
909 * HEAP_IsRealArena [Internal]
910 * Validates a block is a valid arena.
912 * RETURNS
913 * TRUE: Success
914 * FALSE: Failure
916 static BOOL HEAP_IsRealArena( HEAP *heapPtr, /* [in] ptr to the heap */
917 DWORD flags, /* [in] Bit flags that control access during operation */
918 LPCVOID block, /* [in] Optional pointer to memory block to validate */
919 BOOL quiet ) /* [in] Flag - if true, HEAP_ValidateInUseArena
920 * does not complain */
922 SUBHEAP *subheap;
923 BOOL ret = TRUE;
925 if (!heapPtr || (heapPtr->magic != HEAP_MAGIC))
927 ERR("Invalid heap %p!\n", heapPtr );
928 return FALSE;
931 flags &= HEAP_NO_SERIALIZE;
932 flags |= heapPtr->flags;
933 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
934 if (!(flags & HEAP_NO_SERIALIZE))
935 RtlEnterCriticalSection( &heapPtr->critSection );
937 if (block)
939 /* Only check this single memory block */
941 if (!(subheap = HEAP_FindSubHeap( heapPtr, block )) ||
942 ((char *)block < (char *)subheap + subheap->headerSize
943 + sizeof(ARENA_INUSE)))
945 if (quiet == NOISY)
946 ERR("Heap %p: block %p is not inside heap\n", heapPtr, block );
947 else if (WARN_ON(heap))
948 WARN("Heap %p: block %p is not inside heap\n", heapPtr, block );
949 ret = FALSE;
950 } else
951 ret = HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)block - 1, quiet );
953 if (!(flags & HEAP_NO_SERIALIZE))
954 RtlLeaveCriticalSection( &heapPtr->critSection );
955 return ret;
958 subheap = &heapPtr->subheap;
959 while (subheap && ret)
961 char *ptr = (char *)subheap + subheap->headerSize;
962 while (ptr < (char *)subheap + subheap->size)
964 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
966 if (!HEAP_ValidateFreeArena( subheap, (ARENA_FREE *)ptr )) {
967 ret = FALSE;
968 break;
970 ptr += sizeof(ARENA_FREE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
972 else
974 if (!HEAP_ValidateInUseArena( subheap, (ARENA_INUSE *)ptr, NOISY )) {
975 ret = FALSE;
976 break;
978 ptr += sizeof(ARENA_INUSE) + (*(DWORD *)ptr & ARENA_SIZE_MASK);
981 subheap = subheap->next;
984 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
985 return ret;
989 /***********************************************************************
990 * RtlCreateHeap (NTDLL.@)
992 * Create a new Heap.
994 * PARAMS
995 * flags [I] HEAP_ flags from "winnt.h"
996 * addr [I] Desired base address
997 * totalSize [I] Total size of the heap, or 0 for a growable heap
998 * commitSize [I] Amount of heap space to commit
999 * unknown [I] Not yet understood
1000 * definition [I] Heap definition
1002 * RETURNS
1003 * Success: A HANDLE to the newly created heap.
1004 * Failure: a NULL HANDLE.
1006 HANDLE WINAPI RtlCreateHeap( ULONG flags, PVOID addr, ULONG totalSize, ULONG commitSize,
1007 PVOID unknown, PRTL_HEAP_DEFINITION definition )
1009 SUBHEAP *subheap;
1011 /* Allocate the heap block */
1013 if (!totalSize)
1015 totalSize = HEAP_DEF_SIZE;
1016 flags |= HEAP_GROWABLE;
1019 if (!(subheap = HEAP_CreateSubHeap( NULL, addr, flags, commitSize, totalSize ))) return 0;
1021 /* link it into the per-process heap list */
1022 if (processHeap)
1024 HEAP *heapPtr = subheap->heap;
1025 RtlLockHeap( processHeap );
1026 heapPtr->next = firstHeap;
1027 firstHeap = heapPtr;
1028 RtlUnlockHeap( processHeap );
1030 else /* assume the first heap we create is the process main heap */
1032 set_process_heap( (HANDLE)subheap->heap );
1034 return (HANDLE)subheap;
1038 /***********************************************************************
1039 * RtlDestroyHeap (NTDLL.@)
1041 * Destroy a Heap created with RtlCreateHeap().
1043 * PARAMS
1044 * heap [I] Heap to destroy.
1046 * RETURNS
1047 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1048 * Failure: The Heap handle, if heap is the process heap.
1050 HANDLE WINAPI RtlDestroyHeap( HANDLE heap )
1052 HEAP *heapPtr = HEAP_GetPtr( heap );
1053 SUBHEAP *subheap;
1055 TRACE("%p\n", heap );
1056 if (!heapPtr) return heap;
1058 if (heap == processHeap) return heap; /* cannot delete the main process heap */
1059 else /* remove it from the per-process list */
1061 HEAP **pptr;
1062 RtlLockHeap( processHeap );
1063 pptr = &firstHeap;
1064 while (*pptr && *pptr != heapPtr) pptr = &(*pptr)->next;
1065 if (*pptr) *pptr = (*pptr)->next;
1066 RtlUnlockHeap( processHeap );
1069 RtlDeleteCriticalSection( &heapPtr->critSection );
1070 subheap = &heapPtr->subheap;
1071 while (subheap)
1073 SUBHEAP *next = subheap->next;
1074 ULONG size = 0;
1075 void *addr = subheap;
1076 NtFreeVirtualMemory( GetCurrentProcess(), &addr, &size, MEM_RELEASE );
1077 subheap = next;
1079 return 0;
1083 /***********************************************************************
1084 * RtlAllocateHeap (NTDLL.@)
1086 * Allocate a memory block from a Heap.
1088 * PARAMS
1089 * heap [I] Heap to allocate block from
1090 * flags [I] HEAP_ flags from "winnt.h"
1091 * size [I] Size of the memory block to allocate
1093 * RETURNS
1094 * Success: A pointer to the newly allocated block
1095 * Failure: NULL.
1097 * NOTES
1098 * This call does not SetLastError().
1100 PVOID WINAPI RtlAllocateHeap( HANDLE heap, ULONG flags, ULONG size )
1102 ARENA_FREE *pArena;
1103 ARENA_INUSE *pInUse;
1104 SUBHEAP *subheap;
1105 HEAP *heapPtr = HEAP_GetPtr( heap );
1107 /* Validate the parameters */
1109 if (!heapPtr) return NULL;
1110 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1111 flags |= heapPtr->flags;
1112 size = ROUND_SIZE(size);
1113 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1115 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1116 /* Locate a suitable free block */
1118 if (!(pArena = HEAP_FindFreeBlock( heapPtr, size, &subheap )))
1120 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1121 heap, flags, size );
1122 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1123 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1124 return NULL;
1127 /* Remove the arena from the free list */
1129 pArena->next->prev = pArena->prev;
1130 pArena->prev->next = pArena->next;
1132 /* Build the in-use arena */
1134 pInUse = (ARENA_INUSE *)pArena;
1136 /* in-use arena is smaller than free arena,
1137 * so we have to add the difference to the size */
1138 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE) + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1139 pInUse->magic = ARENA_INUSE_MAGIC;
1141 /* Shrink the block */
1143 HEAP_ShrinkBlock( subheap, pInUse, size );
1145 if (flags & HEAP_ZERO_MEMORY)
1146 clear_block( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1147 else
1148 mark_block_uninitialized( pInUse + 1, pInUse->size & ARENA_SIZE_MASK );
1150 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1152 TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1153 heap, flags, size, (DWORD)(pInUse + 1) );
1154 return (LPVOID)(pInUse + 1);
1158 /***********************************************************************
1159 * RtlFreeHeap (NTDLL.@)
1161 * Free a memory block allocated with RtlAllocateHeap().
1163 * PARAMS
1164 * heap [I] Heap that block was allocated from
1165 * flags [I] HEAP_ flags from "winnt.h"
1166 * ptr [I] Block to free
1168 * RETURNS
1169 * Success: TRUE, if ptr is NULL or was freed successfully.
1170 * Failure: FALSE.
1172 BOOLEAN WINAPI RtlFreeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1174 ARENA_INUSE *pInUse;
1175 SUBHEAP *subheap;
1176 HEAP *heapPtr = HEAP_GetPtr( heap );
1178 /* Validate the parameters */
1180 if (!ptr) return TRUE; /* freeing a NULL ptr isn't an error in Win2k */
1181 if (!heapPtr)
1183 set_status( STATUS_INVALID_HANDLE );
1184 return FALSE;
1187 flags &= HEAP_NO_SERIALIZE;
1188 flags |= heapPtr->flags;
1189 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1190 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1192 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1193 set_status( STATUS_INVALID_PARAMETER );
1194 TRACE("(%p,%08lx,%08lx): returning FALSE\n",
1195 heap, flags, (DWORD)ptr );
1196 return FALSE;
1199 /* Turn the block into a free block */
1201 pInUse = (ARENA_INUSE *)ptr - 1;
1202 subheap = HEAP_FindSubHeap( heapPtr, pInUse );
1203 HEAP_MakeInUseBlockFree( subheap, pInUse );
1205 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1207 TRACE("(%p,%08lx,%08lx): returning TRUE\n",
1208 heap, flags, (DWORD)ptr );
1209 return TRUE;
1213 /***********************************************************************
1214 * RtlReAllocateHeap (NTDLL.@)
1216 * Change the size of a memory block allocated with RtlAllocateHeap().
1218 * PARAMS
1219 * heap [I] Heap that block was allocated from
1220 * flags [I] HEAP_ flags from "winnt.h"
1221 * ptr [I] Block to resize
1222 * size [I] Size of the memory block to allocate
1224 * RETURNS
1225 * Success: A pointer to the resized block (which may be different).
1226 * Failure: NULL.
1228 PVOID WINAPI RtlReAllocateHeap( HANDLE heap, ULONG flags, PVOID ptr, ULONG size )
1230 ARENA_INUSE *pArena;
1231 DWORD oldSize;
1232 HEAP *heapPtr;
1233 SUBHEAP *subheap;
1235 if (!ptr) return RtlAllocateHeap( heap, flags, size ); /* FIXME: correct? */
1236 if (!(heapPtr = HEAP_GetPtr( heap )))
1238 set_status( STATUS_INVALID_HANDLE );
1239 return FALSE;
1242 /* Validate the parameters */
1244 flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1245 HEAP_REALLOC_IN_PLACE_ONLY;
1246 flags |= heapPtr->flags;
1247 size = ROUND_SIZE(size);
1248 if (size < HEAP_MIN_BLOCK_SIZE) size = HEAP_MIN_BLOCK_SIZE;
1250 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1251 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1253 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1254 set_status( STATUS_INVALID_PARAMETER );
1255 TRACE("(%p,%08lx,%08lx,%08lx): returning NULL\n",
1256 heap, flags, (DWORD)ptr, size );
1257 return NULL;
1260 /* Check if we need to grow the block */
1262 pArena = (ARENA_INUSE *)ptr - 1;
1263 subheap = HEAP_FindSubHeap( heapPtr, pArena );
1264 oldSize = (pArena->size & ARENA_SIZE_MASK);
1265 if (size > oldSize)
1267 char *pNext = (char *)(pArena + 1) + oldSize;
1268 if ((pNext < (char *)subheap + subheap->size) &&
1269 (*(DWORD *)pNext & ARENA_FLAG_FREE) &&
1270 (oldSize + (*(DWORD *)pNext & ARENA_SIZE_MASK) + sizeof(ARENA_FREE) >= size))
1272 /* The next block is free and large enough */
1273 ARENA_FREE *pFree = (ARENA_FREE *)pNext;
1274 pFree->next->prev = pFree->prev;
1275 pFree->prev->next = pFree->next;
1276 pArena->size += (pFree->size & ARENA_SIZE_MASK) + sizeof(*pFree);
1277 if (!HEAP_Commit( subheap, (char *)pArena + sizeof(ARENA_INUSE)
1278 + size + HEAP_MIN_BLOCK_SIZE))
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;
1285 HEAP_ShrinkBlock( subheap, pArena, size );
1287 else /* Do it the hard way */
1289 ARENA_FREE *pNew;
1290 ARENA_INUSE *pInUse;
1291 SUBHEAP *newsubheap;
1293 if ((flags & HEAP_REALLOC_IN_PLACE_ONLY) ||
1294 !(pNew = HEAP_FindFreeBlock( heapPtr, size, &newsubheap )))
1296 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1297 if (flags & HEAP_GENERATE_EXCEPTIONS) RtlRaiseStatus( STATUS_NO_MEMORY );
1298 set_status( STATUS_NO_MEMORY );
1299 return NULL;
1302 /* Build the in-use arena */
1304 pNew->next->prev = pNew->prev;
1305 pNew->prev->next = pNew->next;
1306 pInUse = (ARENA_INUSE *)pNew;
1307 pInUse->size = (pInUse->size & ~ARENA_FLAG_FREE)
1308 + sizeof(ARENA_FREE) - sizeof(ARENA_INUSE);
1309 pInUse->magic = ARENA_INUSE_MAGIC;
1310 HEAP_ShrinkBlock( newsubheap, pInUse, size );
1311 mark_block_initialized( pInUse + 1, oldSize );
1312 memcpy( pInUse + 1, pArena + 1, oldSize );
1314 /* Free the previous block */
1316 HEAP_MakeInUseBlockFree( subheap, pArena );
1317 subheap = newsubheap;
1318 pArena = pInUse;
1321 else HEAP_ShrinkBlock( subheap, pArena, size ); /* Shrink the block */
1323 /* Clear the extra bytes if needed */
1325 if (size > oldSize)
1327 if (flags & HEAP_ZERO_MEMORY)
1328 clear_block( (char *)(pArena + 1) + oldSize,
1329 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1330 else
1331 mark_block_uninitialized( (char *)(pArena + 1) + oldSize,
1332 (pArena->size & ARENA_SIZE_MASK) - oldSize );
1335 /* Return the new arena */
1337 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1339 TRACE("(%p,%08lx,%08lx,%08lx): returning %08lx\n",
1340 heap, flags, (DWORD)ptr, size, (DWORD)(pArena + 1) );
1341 return (LPVOID)(pArena + 1);
1345 /***********************************************************************
1346 * RtlCompactHeap (NTDLL.@)
1348 * Compact the free space in a Heap.
1350 * PARAMS
1351 * heap [I] Heap that block was allocated from
1352 * flags [I] HEAP_ flags from "winnt.h"
1354 * RETURNS
1355 * The number of bytes compacted.
1357 * NOTES
1358 * This function is a harmless stub.
1360 ULONG WINAPI RtlCompactHeap( HANDLE heap, ULONG flags )
1362 FIXME( "stub\n" );
1363 return 0;
1367 /***********************************************************************
1368 * RtlLockHeap (NTDLL.@)
1370 * Lock a Heap.
1372 * PARAMS
1373 * heap [I] Heap to lock
1375 * RETURNS
1376 * Success: TRUE. The Heap is locked.
1377 * Failure: FALSE, if heap is invalid.
1379 BOOLEAN WINAPI RtlLockHeap( HANDLE heap )
1381 HEAP *heapPtr = HEAP_GetPtr( heap );
1382 if (!heapPtr) return FALSE;
1383 RtlEnterCriticalSection( &heapPtr->critSection );
1384 return TRUE;
1388 /***********************************************************************
1389 * RtlUnlockHeap (NTDLL.@)
1391 * Unlock a Heap.
1393 * PARAMS
1394 * heap [I] Heap to unlock
1396 * RETURNS
1397 * Success: TRUE. The Heap is unlocked.
1398 * Failure: FALSE, if heap is invalid.
1400 BOOLEAN WINAPI RtlUnlockHeap( HANDLE heap )
1402 HEAP *heapPtr = HEAP_GetPtr( heap );
1403 if (!heapPtr) return FALSE;
1404 RtlLeaveCriticalSection( &heapPtr->critSection );
1405 return TRUE;
1409 /***********************************************************************
1410 * RtlSizeHeap (NTDLL.@)
1412 * Get the actual size of a memory block allocated from a Heap.
1414 * PARAMS
1415 * heap [I] Heap that block was allocated from
1416 * flags [I] HEAP_ flags from "winnt.h"
1417 * ptr [I] Block to get the size of
1419 * RETURNS
1420 * Success: The size of the block.
1421 * Failure: -1, heap or ptr are invalid.
1423 * NOTES
1424 * The size may be bigger than what was passed to RtlAllocateHeap().
1426 ULONG WINAPI RtlSizeHeap( HANDLE heap, ULONG flags, PVOID ptr )
1428 DWORD ret;
1429 HEAP *heapPtr = HEAP_GetPtr( heap );
1431 if (!heapPtr)
1433 set_status( STATUS_INVALID_HANDLE );
1434 return (ULONG)-1;
1436 flags &= HEAP_NO_SERIALIZE;
1437 flags |= heapPtr->flags;
1438 if (!(flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1439 if (!HEAP_IsRealArena( heapPtr, HEAP_NO_SERIALIZE, ptr, QUIET ))
1441 set_status( STATUS_INVALID_PARAMETER );
1442 ret = (ULONG)-1;
1444 else
1446 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr - 1;
1447 ret = pArena->size & ARENA_SIZE_MASK;
1449 if (!(flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1451 TRACE("(%p,%08lx,%08lx): returning %08lx\n",
1452 heap, flags, (DWORD)ptr, ret );
1453 return ret;
1457 /***********************************************************************
1458 * RtlValidateHeap (NTDLL.@)
1460 * Determine if a block is a valid alloction from a heap.
1462 * PARAMS
1463 * heap [I] Heap that block was allocated from
1464 * flags [I] HEAP_ flags from "winnt.h"
1465 * ptr [I] Block to check
1467 * RETURNS
1468 * Success: TRUE. The block was allocated from heap.
1469 * Failure: FALSE, if heap is invalid or ptr was not allocated from it.
1471 BOOLEAN WINAPI RtlValidateHeap( HANDLE heap, ULONG flags, LPCVOID ptr )
1473 HEAP *heapPtr = HEAP_GetPtr( heap );
1474 if (!heapPtr) return FALSE;
1475 return HEAP_IsRealArena( heapPtr, flags, ptr, QUIET );
1479 /***********************************************************************
1480 * RtlWalkHeap (NTDLL.@)
1482 * FIXME
1483 * The PROCESS_HEAP_ENTRY flag values seem different between this
1484 * function and HeapWalk(). To be checked.
1486 NTSTATUS WINAPI RtlWalkHeap( HANDLE heap, PVOID entry_ptr )
1488 LPPROCESS_HEAP_ENTRY entry = entry_ptr; /* FIXME */
1489 HEAP *heapPtr = HEAP_GetPtr(heap);
1490 SUBHEAP *sub, *currentheap = NULL;
1491 NTSTATUS ret;
1492 char *ptr;
1493 int region_index = 0;
1495 FIXME( "not fully compatible\n" );
1497 if (!heapPtr || !entry) return STATUS_INVALID_PARAMETER;
1499 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlEnterCriticalSection( &heapPtr->critSection );
1501 /* set ptr to the next arena to be examined */
1503 if (!entry->lpData) /* first call (init) ? */
1505 TRACE("begin walking of heap %p.\n", heap);
1506 currentheap = &heapPtr->subheap;
1507 ptr = (char*)currentheap + currentheap->headerSize;
1509 else
1511 ptr = entry->lpData;
1512 sub = &heapPtr->subheap;
1513 while (sub)
1515 if (((char *)ptr >= (char *)sub) &&
1516 ((char *)ptr < (char *)sub + sub->size))
1518 currentheap = sub;
1519 break;
1521 sub = sub->next;
1522 region_index++;
1524 if (currentheap == NULL)
1526 ERR("no matching subheap found, shouldn't happen !\n");
1527 ret = STATUS_NO_MORE_ENTRIES;
1528 goto HW_end;
1531 ptr += entry->cbData; /* point to next arena */
1532 if (ptr > (char *)currentheap + currentheap->size - 1)
1533 { /* proceed with next subheap */
1534 if (!(currentheap = currentheap->next))
1535 { /* successfully finished */
1536 TRACE("end reached.\n");
1537 ret = STATUS_NO_MORE_ENTRIES;
1538 goto HW_end;
1540 ptr = (char*)currentheap + currentheap->headerSize;
1544 entry->wFlags = 0;
1545 if (*(DWORD *)ptr & ARENA_FLAG_FREE)
1547 ARENA_FREE *pArena = (ARENA_FREE *)ptr;
1549 /*TRACE("free, magic: %04x\n", pArena->magic);*/
1551 entry->lpData = pArena + 1;
1552 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1553 entry->cbOverhead = sizeof(ARENA_FREE);
1554 entry->wFlags = PROCESS_HEAP_UNCOMMITTED_RANGE;
1556 else
1558 ARENA_INUSE *pArena = (ARENA_INUSE *)ptr;
1560 /*TRACE("busy, magic: %04x\n", pArena->magic);*/
1562 entry->lpData = pArena + 1;
1563 entry->cbData = pArena->size & ARENA_SIZE_MASK;
1564 entry->cbOverhead = sizeof(ARENA_INUSE);
1565 entry->wFlags = PROCESS_HEAP_ENTRY_BUSY;
1566 /* FIXME: can't handle PROCESS_HEAP_ENTRY_MOVEABLE
1567 and PROCESS_HEAP_ENTRY_DDESHARE yet */
1570 entry->iRegionIndex = region_index;
1572 /* first element of heap ? */
1573 if (ptr == (char *)(currentheap + currentheap->headerSize))
1575 entry->wFlags |= PROCESS_HEAP_REGION;
1576 entry->u.Region.dwCommittedSize = currentheap->commitSize;
1577 entry->u.Region.dwUnCommittedSize =
1578 currentheap->size - currentheap->commitSize;
1579 entry->u.Region.lpFirstBlock = /* first valid block */
1580 currentheap + currentheap->headerSize;
1581 entry->u.Region.lpLastBlock = /* first invalid block */
1582 currentheap + currentheap->size;
1584 ret = STATUS_SUCCESS;
1586 HW_end:
1587 if (!(heapPtr->flags & HEAP_NO_SERIALIZE)) RtlLeaveCriticalSection( &heapPtr->critSection );
1588 return ret;
1592 /***********************************************************************
1593 * RtlGetProcessHeaps (NTDLL.@)
1595 * Get the Heaps belonging to the current process.
1597 * PARAMS
1598 * count [I] size of heaps
1599 * heaps [O] Destination array for heap HANDLE's
1601 * RETURNS
1602 * Success: The number of Heaps allocated by the process.
1603 * Failure: 0.
1605 ULONG WINAPI RtlGetProcessHeaps( ULONG count, HANDLE *heaps )
1607 DWORD total;
1608 HEAP *ptr;
1610 if (!processHeap) return 0; /* should never happen */
1611 total = 1; /* main heap */
1612 RtlLockHeap( processHeap );
1613 for (ptr = firstHeap; ptr; ptr = ptr->next) total++;
1614 if (total <= count)
1616 *heaps++ = (HANDLE)processHeap;
1617 for (ptr = firstHeap; ptr; ptr = ptr->next) *heaps++ = (HANDLE)ptr;
1619 RtlUnlockHeap( processHeap );
1620 return total;