1 /* COPYRIGHT: See COPYING in the top level directory
2 * PROJECT: ReactOS system libraries
3 * FILE: lib/rtl/image.c
4 * PURPOSE: Image handling functions
5 * PROGRAMMERS: Copyright 1996 Alexandre Julliard
6 * Copyright 1998 Ulrich Weigand
10 // Note: This is a slightly modified implementation of WINE's.
12 // WINE's implementation is a hack based on Windows 95's heap implementation,
13 // itself a hack of DOS memory management.It supports 3 out of the 18 possible
14 // NT Heap Flags, does not support custom allocation/deallocation routines,
15 // and is about 50-80x slower with fragmentation rates up to 500x higher when
16 // compared to NT's LFH. WINE is lucky because the advanced NT Heap features are
17 // used in kernel-mode usually, not in user-mode, and they are crossing their
18 // fingers for this being the same. Note that several high-end SQL/Database
19 // applications would significantly benefit from custom heap features provided
22 // ROS's changes include:
23 // - Using Zw instead of Nt calls, because this matters when in Kernel Mode
24 // - Not using per-process heap lists while in Kernel Mode
25 // - Using a macro to handle the Critical Section, because it's meaningless
27 // - Crappy support for a custom Commit routine.
28 // - Crappy support for User-defined flags and the User-defined value.
29 // - Ripping out all the code for shared heaps, because those don't exist on NT.
31 // Be aware of these changes when you try to sync something back.
34 /* INCLUDES *****************************************************************/
38 #undef LIST_FOR_EACH_SAFE
39 #include <wine/list.h>
47 #define DPRINTF DPRINT
49 /* FUNCTIONS *****************************************************************/
51 #define WARN_ON(x) (1)
54 #define TRACE_ON(x) (0)
56 #define TRACE_ON(x) (1)
59 /* Note: the heap data structures are based on what Pietrek describes in his
60 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
61 * the same, but could be easily adapted if it turns out some programs
65 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
66 * that there is no unaligned accesses to structure fields.
69 typedef struct tagARENA_INUSE
71 DWORD size
; /* Block size; must be the first field */
72 DWORD magic
: 24; /* Magic number */
73 DWORD unused_bytes
: 8; /* Number of bytes in the block not used by user data (max value is HEAP_MIN_DATA_SIZE+HEAP_MIN_SHRINK_SIZE) */
76 typedef struct tagARENA_FREE
78 DWORD size
; /* Block size; must be the first field */
79 DWORD magic
; /* Magic number */
80 struct list entry
; /* Entry in free list */
83 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
84 #define ARENA_FLAG_PREV_FREE 0x00000002
85 #define ARENA_SIZE_MASK (~3)
86 #define ARENA_INUSE_MAGIC 0x455355 /* Value for arena 'magic' field */
87 #define ARENA_FREE_MAGIC 0x45455246 /* Value for arena 'magic' field */
89 #define ARENA_INUSE_FILLER 0x55
90 #define ARENA_FREE_FILLER 0xaa
92 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
93 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
95 #define QUIET 1 /* Suppress messages */
96 #define NOISY 0 /* Report all errors */
98 /* minimum data size (without arenas) of an allocated block */
99 #define HEAP_MIN_DATA_SIZE 16
100 /* minimum size that must remain to shrink an allocated block */
101 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
103 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
105 /* Max size of the blocks on the free lists */
106 static const DWORD HEAP_freeListSizes
[HEAP_NB_FREE_LISTS
] =
108 0x20, 0x80, 0x200, ~0UL
118 typedef struct tagSUBHEAP
120 DWORD size
; /* Size of the whole sub-heap */
121 DWORD commitSize
; /* Committed size of the sub-heap */
122 DWORD headerSize
; /* Size of the heap header */
123 struct tagSUBHEAP
*next
; /* Next sub-heap */
124 struct tagHEAP
*heap
; /* Main heap structure */
125 DWORD magic
; /* Magic number */
130 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
132 typedef struct tagHEAP
134 SUBHEAP subheap
; /* First sub-heap */
135 struct list entry
; /* Entry in process heap list */
136 RTL_CRITICAL_SECTION critSection
; /* Critical section for serialization */
137 FREE_LIST_ENTRY freeList
[HEAP_NB_FREE_LISTS
]; /* Free lists */
138 DWORD flags
; /* Heap flags */
139 DWORD magic
; /* Magic number */
140 PRTL_HEAP_COMMIT_ROUTINE commitRoutine
;
143 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
145 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
146 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
148 static HEAP
*processHeap
; /* main process heap */
150 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, DWORD flags
, LPCVOID block
, BOOL quiet
);
152 /* mark a block of memory as free for debugging purposes */
153 static __inline
void mark_block_free( void *ptr
, SIZE_T size
)
155 if (TRACE_ON(heap
)) memset( ptr
, ARENA_FREE_FILLER
, size
);
156 #ifdef VALGRIND_MAKE_NOACCESS
157 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr
, size
));
161 /* mark a block of memory as initialized for debugging purposes */
162 static __inline
void mark_block_initialized( void *ptr
, SIZE_T size
)
164 #ifdef VALGRIND_MAKE_READABLE
165 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr
, size
));
169 /* mark a block of memory as uninitialized for debugging purposes */
170 static __inline
void mark_block_uninitialized( void *ptr
, SIZE_T size
)
172 #ifdef VALGRIND_MAKE_WRITABLE
173 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr
, size
));
177 memset( ptr
, ARENA_INUSE_FILLER
, size
);
178 #ifdef VALGRIND_MAKE_WRITABLE
179 /* make it uninitialized to valgrind again */
180 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr
, size
));
185 /* clear contents of a block of memory */
186 static __inline
void clear_block( void *ptr
, SIZE_T size
)
188 mark_block_initialized( ptr
, size
);
189 memset( ptr
, 0, size
);
192 /* locate a free list entry of the appropriate size */
193 /* size is the size of the whole block including the arena header */
194 static __inline
unsigned int get_freelist_index( SIZE_T size
)
198 size
-= sizeof(ARENA_FREE
);
199 for (i
= 0; i
< HEAP_NB_FREE_LISTS
- 1; i
++) if (size
<= HEAP_freeListSizes
[i
]) break;
203 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug
=
205 0, 0, NULL
, /* will be set later */
206 { &process_heap_critsect_debug
.ProcessLocksList
, &process_heap_critsect_debug
.ProcessLocksList
},
210 /***********************************************************************
213 static void HEAP_Dump( HEAP
*heap
)
219 DPRINTF( "Heap: %p\n", heap
);
220 DPRINTF( "Next: %p Sub-heaps: %p",
221 LIST_ENTRY( heap
->entry
.next
, HEAP
, entry
), &heap
->subheap
);
222 subheap
= &heap
->subheap
;
223 while (subheap
->next
)
225 DPRINTF( " -> %p", subheap
->next
);
226 subheap
= subheap
->next
;
229 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
230 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
231 DPRINTF( "%p free %08lx prev=%p next=%p\n",
232 &heap
->freeList
[i
].arena
, HEAP_freeListSizes
[i
],
233 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.prev
, ARENA_FREE
, entry
),
234 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.next
, ARENA_FREE
, entry
));
236 subheap
= &heap
->subheap
;
239 SIZE_T freeSize
= 0, usedSize
= 0, arenaSize
= subheap
->headerSize
;
240 DPRINTF( "\n\nSub-heap %p: size=%08lx committed=%08lx\n",
241 subheap
, subheap
->size
, subheap
->commitSize
);
243 DPRINTF( "\n Block Stat Size Id\n" );
244 ptr
= (char*)subheap
+ subheap
->headerSize
;
245 while (ptr
< (char *)subheap
+ subheap
->size
)
247 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
249 ARENA_FREE
*pArena
= (ARENA_FREE
*)ptr
;
250 DPRINTF( "%p free %08lx prev=%p next=%p\n",
251 pArena
, pArena
->size
& ARENA_SIZE_MASK
,
252 LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
),
253 LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
) );
254 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
255 arenaSize
+= sizeof(ARENA_FREE
);
256 freeSize
+= pArena
->size
& ARENA_SIZE_MASK
;
258 else if (*(DWORD
*)ptr
& ARENA_FLAG_PREV_FREE
)
260 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
261 DPRINTF( "%p Used %08lx back=%p\n",
262 pArena
, pArena
->size
& ARENA_SIZE_MASK
, *((ARENA_FREE
**)pArena
- 1) );
263 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
264 arenaSize
+= sizeof(ARENA_INUSE
);
265 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
269 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
270 DPRINTF( "%p used %08lx\n", pArena
, pArena
->size
& ARENA_SIZE_MASK
);
271 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
272 arenaSize
+= sizeof(ARENA_INUSE
);
273 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
276 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
277 subheap
->size
, subheap
->commitSize
, freeSize
, usedSize
,
278 arenaSize
, (arenaSize
* 100) / subheap
->size
);
279 subheap
= subheap
->next
;
284 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry
)
287 TRACE( "Dumping entry %p\n", entry
);
288 TRACE( "lpData\t\t: %p\n", entry
->lpData
);
289 TRACE( "cbData\t\t: %08lx\n", entry
->cbData
);
290 TRACE( "cbOverhead\t: %08x\n", entry
->cbOverhead
);
291 TRACE( "iRegionIndex\t: %08x\n", entry
->iRegionIndex
);
292 TRACE( "WFlags\t\t: ");
293 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
294 TRACE( "PROCESS_HEAP_REGION ");
295 if (entry
->wFlags
& PROCESS_HEAP_UNCOMMITTED_RANGE
)
296 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
297 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
298 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
299 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
)
300 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
301 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_DDESHARE
)
302 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
303 rem_flags
= entry
->wFlags
&
304 ~(PROCESS_HEAP_REGION
| PROCESS_HEAP_UNCOMMITTED_RANGE
|
305 PROCESS_HEAP_ENTRY_BUSY
| PROCESS_HEAP_ENTRY_MOVEABLE
|
306 PROCESS_HEAP_ENTRY_DDESHARE
);
308 TRACE( "Unknown %08x", rem_flags
);
310 if ((entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
311 && (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
))
314 TRACE( "BLOCK->hMem\t\t:%p\n", entry
->Block
.hMem
);
316 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
318 TRACE( "Region.dwCommittedSize\t:%08lx\n",entry
->Region
.dwCommittedSize
);
319 TRACE( "Region.dwUnCommittedSize\t:%08lx\n",entry
->Region
.dwUnCommittedSize
);
320 TRACE( "Region.lpFirstBlock\t:%p\n",entry
->Region
.lpFirstBlock
);
321 TRACE( "Region.lpLastBlock\t:%p\n",entry
->Region
.lpLastBlock
);
326 /***********************************************************************
329 * Pointer to the heap
332 static HEAP
*HEAP_GetPtr(
333 HANDLE heap
/* [in] Handle to the heap */
335 HEAP
*heapPtr
= (HEAP
*)heap
;
336 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
339 ERR("Invalid heap %p, magic:%.4s!\n", heap
, &heapPtr
->magic
);
341 ERR("Invalid heap %p!\n", heap
);
342 //KeDumpStackFrames(NULL);
345 if (TRACE_ON(heap
) && !HEAP_IsRealArena( heapPtr
, 0, NULL
, NOISY
))
347 HEAP_Dump( heapPtr
);
355 /***********************************************************************
356 * HEAP_InsertFreeBlock
358 * Insert a free block into the free list.
360 static __inline
void HEAP_InsertFreeBlock( HEAP
*heap
, ARENA_FREE
*pArena
, BOOL last
)
362 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( pArena
->size
+ sizeof(*pArena
) );
365 /* insert at end of free list, i.e. before the next free list entry */
367 if (pEntry
== &heap
->freeList
[HEAP_NB_FREE_LISTS
]) pEntry
= heap
->freeList
;
368 list_add_before( &pEntry
->arena
.entry
, &pArena
->entry
);
372 /* insert at head of free list */
373 list_add_after( &pEntry
->arena
.entry
, &pArena
->entry
);
375 pArena
->size
|= ARENA_FLAG_FREE
;
379 /***********************************************************************
381 * Find the sub-heap containing a given address.
387 static SUBHEAP
*HEAP_FindSubHeap(
388 const HEAP
*heap
, /* [in] Heap pointer */
389 LPCVOID ptr
/* [in] Address */
391 const SUBHEAP
*sub
= &heap
->subheap
;
394 if (((const char *)ptr
>= (const char *)sub
) &&
395 ((const char *)ptr
< (const char *)sub
+ sub
->size
)) return (SUBHEAP
*)sub
;
401 /***********************************************************************
404 * Make sure the heap storage is committed for a given size in the specified arena.
406 static __inline BOOL
HEAP_Commit( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T data_size
)
409 void *ptr
= (char *)(pArena
+ 1) + data_size
+ sizeof(ARENA_FREE
);
410 SIZE_T size
= (char *)ptr
- (char *)subheap
;
411 size
= (size
+ COMMIT_MASK
) & ~COMMIT_MASK
;
412 if (size
> subheap
->size
) size
= subheap
->size
;
413 if (size
<= subheap
->commitSize
) return TRUE
;
414 size
-= subheap
->commitSize
;
415 ptr
= (char *)subheap
+ subheap
->commitSize
;
416 if (subheap
->heap
->commitRoutine
!= NULL
)
418 Status
= subheap
->heap
->commitRoutine(subheap
->heap
, &ptr
, &size
);
422 Status
= ZwAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0,
423 &size
, MEM_COMMIT
, PAGE_READWRITE
);
425 if (!NT_SUCCESS(Status
))
427 WARN("Could not commit %08lx bytes at %p for heap %p\n",
428 size
, ptr
, subheap
->heap
);
431 subheap
->commitSize
+= size
;
436 /***********************************************************************
439 * If possible, decommit the heap storage from (including) 'ptr'.
441 static inline BOOL
HEAP_Decommit( SUBHEAP
*subheap
, void *ptr
)
444 SIZE_T decommit_size
;
445 SIZE_T size
= (char *)ptr
- (char *)subheap
;
447 /* round to next block and add one full block */
448 size
= ((size
+ COMMIT_MASK
) & ~COMMIT_MASK
) + COMMIT_MASK
+ 1;
449 if (size
>= subheap
->commitSize
) return TRUE
;
450 decommit_size
= subheap
->commitSize
- size
;
451 addr
= (char *)subheap
+ size
;
453 if (ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &decommit_size
, MEM_DECOMMIT
))
455 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
456 decommit_size
, (char *)subheap
+ size
, subheap
->heap
);
459 subheap
->commitSize
-= decommit_size
;
464 /***********************************************************************
465 * HEAP_CreateFreeBlock
467 * Create a free block at a specified address. 'size' is the size of the
468 * whole block, including the new arena.
470 static void HEAP_CreateFreeBlock( SUBHEAP
*subheap
, void *ptr
, SIZE_T size
)
476 /* Create a free arena */
477 mark_block_uninitialized( ptr
, sizeof( ARENA_FREE
) );
478 pFree
= (ARENA_FREE
*)ptr
;
479 pFree
->magic
= ARENA_FREE_MAGIC
;
481 /* If debugging, erase the freed block content */
483 pEnd
= (char *)ptr
+ size
;
484 if (pEnd
> (char *)subheap
+ subheap
->commitSize
) pEnd
= (char *)subheap
+ subheap
->commitSize
;
485 if (pEnd
> (char *)(pFree
+ 1)) mark_block_free( pFree
+ 1, pEnd
- (char *)(pFree
+ 1) );
487 /* Check if next block is free also */
489 if (((char *)ptr
+ size
< (char *)subheap
+ subheap
->size
) &&
490 (*(DWORD
*)((char *)ptr
+ size
) & ARENA_FLAG_FREE
))
492 /* Remove the next arena from the free list */
493 ARENA_FREE
*pNext
= (ARENA_FREE
*)((char *)ptr
+ size
);
494 list_remove( &pNext
->entry
);
495 size
+= (pNext
->size
& ARENA_SIZE_MASK
) + sizeof(*pNext
);
496 mark_block_free( pNext
, sizeof(ARENA_FREE
) );
499 /* Set the next block PREV_FREE flag and pointer */
501 last
= ((char *)ptr
+ size
>= (char *)subheap
+ subheap
->size
);
504 DWORD
*pNext
= (DWORD
*)((char *)ptr
+ size
);
505 *pNext
|= ARENA_FLAG_PREV_FREE
;
506 mark_block_initialized( pNext
- 1, sizeof( ARENA_FREE
* ) );
507 *((ARENA_FREE
**)pNext
- 1) = pFree
;
510 /* Last, insert the new block into the free list */
512 pFree
->size
= size
- sizeof(*pFree
);
513 HEAP_InsertFreeBlock( subheap
->heap
, pFree
, last
);
517 /***********************************************************************
518 * HEAP_MakeInUseBlockFree
520 * Turn an in-use block into a free block. Can also decommit the end of
521 * the heap, and possibly even free the sub-heap altogether.
523 static void HEAP_MakeInUseBlockFree( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
)
526 SIZE_T size
= (pArena
->size
& ARENA_SIZE_MASK
) + sizeof(*pArena
);
528 /* Check if we can merge with previous block */
530 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
532 pFree
= *((ARENA_FREE
**)pArena
- 1);
533 size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
534 /* Remove it from the free list */
535 list_remove( &pFree
->entry
);
537 else pFree
= (ARENA_FREE
*)pArena
;
539 /* Create a free block */
541 HEAP_CreateFreeBlock( subheap
, pFree
, size
);
542 size
= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
543 if ((char *)pFree
+ size
< (char *)subheap
+ subheap
->size
)
544 return; /* Not the last block, so nothing more to do */
546 /* Free the whole sub-heap if it's empty and not the original one */
548 if (((char *)pFree
== (char *)subheap
+ subheap
->headerSize
) &&
549 (subheap
!= &subheap
->heap
->subheap
))
552 SUBHEAP
*pPrev
= &subheap
->heap
->subheap
;
553 /* Remove the free block from the list */
554 list_remove( &pFree
->entry
);
555 /* Remove the subheap from the list */
556 while (pPrev
&& (pPrev
->next
!= subheap
)) pPrev
= pPrev
->next
;
557 if (pPrev
) pPrev
->next
= subheap
->next
;
558 /* Free the memory */
560 ZwFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap
, &size
, MEM_RELEASE
);
564 /* Decommit the end of the heap */
567 /***********************************************************************
570 * Shrink an in-use block.
572 static void HEAP_ShrinkBlock(SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T size
)
574 if ((pArena
->size
& ARENA_SIZE_MASK
) >= size
+ HEAP_MIN_SHRINK_SIZE
)
576 HEAP_CreateFreeBlock( subheap
, (char *)(pArena
+ 1) + size
,
577 (pArena
->size
& ARENA_SIZE_MASK
) - size
);
578 /* assign size plus previous arena flags */
579 pArena
->size
= size
| (pArena
->size
& ~ARENA_SIZE_MASK
);
583 /* Turn off PREV_FREE flag in next block */
584 char *pNext
= (char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
);
585 if (pNext
< (char *)subheap
+ subheap
->size
)
586 *(DWORD
*)pNext
&= ~ARENA_FLAG_PREV_FREE
;
590 /***********************************************************************
593 static BOOL
HEAP_InitSubHeap( HEAP
*heap
, LPVOID address
, DWORD flags
,
594 SIZE_T commitSize
, SIZE_T totalSize
,
595 PRTL_HEAP_PARAMETERS Parameters
)
598 FREE_LIST_ENTRY
*pEntry
;
602 if (!address
&& ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0,
603 &commitSize
, MEM_COMMIT
, PAGE_READWRITE
))
605 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize
, address
);
609 /* Fill the sub-heap structure */
611 subheap
= (SUBHEAP
*)address
;
612 subheap
->heap
= heap
;
613 subheap
->size
= totalSize
;
614 subheap
->commitSize
= commitSize
;
615 subheap
->magic
= SUBHEAP_MAGIC
;
617 if ( subheap
!= (SUBHEAP
*)heap
)
619 /* If this is a secondary subheap, insert it into list */
621 subheap
->headerSize
= ROUND_SIZE( sizeof(SUBHEAP
) );
622 subheap
->next
= heap
->subheap
.next
;
623 heap
->subheap
.next
= subheap
;
627 /* If this is a primary subheap, initialize main heap */
629 subheap
->headerSize
= ROUND_SIZE( sizeof(HEAP
) );
630 subheap
->next
= NULL
;
632 heap
->magic
= HEAP_MAGIC
;
634 heap
->commitRoutine
= Parameters
->CommitRoutine
;
636 heap
->commitRoutine
= NULL
;
638 /* Build the free lists */
640 list_init( &heap
->freeList
[0].arena
.entry
);
641 for (i
= 0, pEntry
= heap
->freeList
; i
< HEAP_NB_FREE_LISTS
; i
++, pEntry
++)
643 pEntry
->arena
.size
= 0 | ARENA_FLAG_FREE
;
644 pEntry
->arena
.magic
= ARENA_FREE_MAGIC
;
645 if (i
) list_add_after( &pEntry
[-1].arena
.entry
, &pEntry
->arena
.entry
);
648 /* Initialize critical section */
650 if (RtlpGetMode() == UserMode
)
652 if (!processHeap
) /* do it by hand to avoid memory allocations */
654 heap
->critSection
.DebugInfo
= &process_heap_critsect_debug
;
655 heap
->critSection
.LockCount
= -1;
656 heap
->critSection
.RecursionCount
= 0;
657 heap
->critSection
.OwningThread
= 0;
658 heap
->critSection
.LockSemaphore
= 0;
659 heap
->critSection
.SpinCount
= 0;
660 process_heap_critsect_debug
.CriticalSection
= &heap
->critSection
;
662 else RtlInitializeHeapLock( &heap
->critSection
);
667 if (heap
->commitRoutine
)
669 if (subheap
!= (SUBHEAP
*)heap
)
671 Status
= heap
->commitRoutine(heap
, &address
, &commitSize
);
675 /* the caller is responsible for committing the first page! */
676 Status
= STATUS_SUCCESS
;
681 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
686 PAGE_EXECUTE_READWRITE
);
688 if (!NT_SUCCESS(Status
))
690 DPRINT("Could not commit %08lx bytes for sub-heap %p\n",
691 commitSize
, address
);
695 /* Create the first free block */
697 HEAP_CreateFreeBlock( subheap
, (LPBYTE
)subheap
+ subheap
->headerSize
,
698 subheap
->size
- subheap
->headerSize
);
703 /***********************************************************************
706 * Create a sub-heap of the given size.
707 * If heap == NULL, creates a main heap.
709 static SUBHEAP
*HEAP_CreateSubHeap( HEAP
*heap
, void *base
, DWORD flags
,
710 SIZE_T commitSize
, SIZE_T totalSize
,
711 IN PRTL_HEAP_PARAMETERS Parameters
)
713 LPVOID address
= base
;
715 /* round-up sizes on a 64K boundary */
716 totalSize
= (totalSize
+ 0xffff) & 0xffff0000;
717 commitSize
= (commitSize
+ 0xffff) & 0xffff0000;
718 if (!commitSize
) commitSize
= 0x10000;
719 if (totalSize
< commitSize
) totalSize
= commitSize
;
723 /* allocate the memory block */
724 if (ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0, &totalSize
,
725 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
))
727 WARN("Could not allocate %08lx bytes\n", totalSize
);
732 /* Initialize subheap */
734 if (!HEAP_InitSubHeap( heap
? heap
: (HEAP
*)address
,
735 address
, flags
, commitSize
, totalSize
, Parameters
))
738 if (!base
) ZwFreeVirtualMemory( NtCurrentProcess(), &address
, &size
, MEM_RELEASE
);
742 return (SUBHEAP
*)address
;
746 /***********************************************************************
749 * Find a free block at least as large as the requested size, and make sure
750 * the requested size is committed.
752 static ARENA_FREE
*HEAP_FindFreeBlock( HEAP
*heap
, SIZE_T size
,
753 SUBHEAP
**ppSubHeap
)
757 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( size
+ sizeof(ARENA_INUSE
) );
759 /* Find a suitable free list, and in it find a block large enough */
761 ptr
= &pEntry
->arena
.entry
;
762 while ((ptr
= list_next( &heap
->freeList
[0].arena
.entry
, ptr
)))
764 ARENA_FREE
*pArena
= LIST_ENTRY( ptr
, ARENA_FREE
, entry
);
765 SIZE_T arena_size
= (pArena
->size
& ARENA_SIZE_MASK
) +
766 sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
767 if (arena_size
>= size
)
769 subheap
= HEAP_FindSubHeap( heap
, pArena
);
770 if (!HEAP_Commit( subheap
, (ARENA_INUSE
*)pArena
, size
)) return NULL
;
771 *ppSubHeap
= subheap
;
776 /* If no block was found, attempt to grow the heap */
778 if (!(heap
->flags
& HEAP_GROWABLE
))
780 ERR("Not enough space in heap %p for %08lx bytes\n", heap
, size
);
783 /* make sure that we have a big enough size *committed* to fit another
784 * last free arena in !
785 * So just one heap struct, one first free arena which will eventually
786 * get used, and a second free arena that might get assigned all remaining
787 * free space in HEAP_ShrinkBlock() */
788 size
+= ROUND_SIZE(sizeof(SUBHEAP
)) + sizeof(ARENA_INUSE
) + sizeof(ARENA_FREE
);
789 if (!(subheap
= HEAP_CreateSubHeap( heap
, NULL
, heap
->flags
, size
,
790 max( HEAP_DEF_SIZE
, size
), NULL
)))
793 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
794 subheap
, size
, heap
);
796 *ppSubHeap
= subheap
;
797 return (ARENA_FREE
*)(subheap
+ 1);
800 /***********************************************************************
801 * HEAP_IsValidArenaPtr
803 * Check that the pointer is inside the range possible for arenas.
805 static BOOL
HEAP_IsValidArenaPtr( const HEAP
*heap
, const void *ptr
)
808 const SUBHEAP
*subheap
= HEAP_FindSubHeap( heap
, ptr
);
809 if (!subheap
) return FALSE
;
810 if ((const char *)ptr
>= (const char *)subheap
+ subheap
->headerSize
) return TRUE
;
811 if (subheap
!= &heap
->subheap
) return FALSE
;
812 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
813 if (ptr
== (const void *)&heap
->freeList
[i
].arena
) return TRUE
;
818 /***********************************************************************
819 * HEAP_ValidateFreeArena
821 static BOOL
HEAP_ValidateFreeArena( SUBHEAP
*subheap
, ARENA_FREE
*pArena
)
823 ARENA_FREE
*prev
, *next
;
824 char *heapEnd
= (char *)subheap
+ subheap
->size
;
826 /* Check for unaligned pointers */
827 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= 0 )
829 ERR("Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
833 /* Check magic number */
834 if (pArena
->magic
!= ARENA_FREE_MAGIC
)
836 ERR("Heap %p: invalid free arena magic for %p\n", subheap
->heap
, pArena
);
839 /* Check size flags */
840 if (!(pArena
->size
& ARENA_FLAG_FREE
) ||
841 (pArena
->size
& ARENA_FLAG_PREV_FREE
))
843 ERR("Heap %p: bad flags %08lx for free arena %p\n",
844 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
847 /* Check arena size */
848 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
850 ERR("Heap %p: bad size %08lx for free arena %p\n",
851 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
854 /* Check that next pointer is valid */
855 next
= LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
);
856 if (!HEAP_IsValidArenaPtr( subheap
->heap
, next
))
858 ERR("Heap %p: bad next ptr %p for arena %p\n",
859 subheap
->heap
, next
, pArena
);
862 /* Check that next arena is free */
863 if (!(next
->size
& ARENA_FLAG_FREE
) || (next
->magic
!= ARENA_FREE_MAGIC
))
865 ERR("Heap %p: next arena %p invalid for %p\n",
866 subheap
->heap
, next
, pArena
);
869 /* Check that prev pointer is valid */
870 prev
= LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
);
871 if (!HEAP_IsValidArenaPtr( subheap
->heap
, prev
))
873 ERR("Heap %p: bad prev ptr %p for arena %p\n",
874 subheap
->heap
, prev
, pArena
);
877 /* Check that prev arena is free */
878 if (!(prev
->size
& ARENA_FLAG_FREE
) || (prev
->magic
!= ARENA_FREE_MAGIC
))
880 /* this often means that the prev arena got overwritten
881 * by a memory write before that prev arena */
882 ERR("Heap %p: prev arena %p invalid for %p\n",
883 subheap
->heap
, prev
, pArena
);
886 /* Check that next block has PREV_FREE flag */
887 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
)
889 if (!(*(DWORD
*)((char *)(pArena
+ 1) +
890 (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
892 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
893 subheap
->heap
, pArena
);
896 /* Check next block back pointer */
897 if (*((ARENA_FREE
**)((char *)(pArena
+ 1) +
898 (pArena
->size
& ARENA_SIZE_MASK
)) - 1) != pArena
)
900 ERR("Heap %p: arena %p has wrong back ptr %p\n",
901 subheap
->heap
, pArena
,
902 *((ARENA_FREE
**)((char *)(pArena
+1) + (pArena
->size
& ARENA_SIZE_MASK
)) - 1));
909 /***********************************************************************
910 * HEAP_ValidateInUseArena
912 static BOOL
HEAP_ValidateInUseArena( const SUBHEAP
*subheap
, const ARENA_INUSE
*pArena
, BOOL quiet
)
914 const char *heapEnd
= (const char *)subheap
+ subheap
->size
;
916 /* Check for unaligned pointers */
917 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= 0 )
919 if ( quiet
== NOISY
)
921 ERR( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
922 if ( TRACE_ON(heap
) )
923 HEAP_Dump( subheap
->heap
);
925 else if ( WARN_ON(heap
) )
927 WARN( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
928 if ( TRACE_ON(heap
) )
929 HEAP_Dump( subheap
->heap
);
934 /* Check magic number */
935 if (pArena
->magic
!= ARENA_INUSE_MAGIC
)
937 if (quiet
== NOISY
) {
938 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
940 HEAP_Dump( subheap
->heap
);
941 } else if (WARN_ON(heap
)) {
942 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
944 HEAP_Dump( subheap
->heap
);
948 /* Check size flags */
949 if (pArena
->size
& ARENA_FLAG_FREE
)
951 ERR("Heap %p: bad flags %08lx for in-use arena %p\n",
952 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
955 /* Check arena size */
956 if ((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
958 ERR("Heap %p: bad size %08lx for in-use arena %p\n",
959 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
962 /* Check next arena PREV_FREE flag */
963 if (((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
) &&
964 (*(const DWORD
*)((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
966 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
967 subheap
->heap
, pArena
);
970 /* Check prev free arena */
971 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
973 const ARENA_FREE
*pPrev
= *((const ARENA_FREE
* const*)pArena
- 1);
974 /* Check prev pointer */
975 if (!HEAP_IsValidArenaPtr( subheap
->heap
, pPrev
))
977 ERR("Heap %p: bad back ptr %p for arena %p\n",
978 subheap
->heap
, pPrev
, pArena
);
981 /* Check that prev arena is free */
982 if (!(pPrev
->size
& ARENA_FLAG_FREE
) ||
983 (pPrev
->magic
!= ARENA_FREE_MAGIC
))
985 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
986 subheap
->heap
, pPrev
, pArena
);
989 /* Check that prev arena is really the previous block */
990 if ((const char *)(pPrev
+ 1) + (pPrev
->size
& ARENA_SIZE_MASK
) != (const char *)pArena
)
992 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
993 subheap
->heap
, pPrev
, pArena
);
1000 /***********************************************************************
1001 * HEAP_IsRealArena [Internal]
1002 * Validates a block is a valid arena.
1008 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, /* [in] ptr to the heap */
1009 DWORD flags
, /* [in] Bit flags that control access during operation */
1010 LPCVOID block
, /* [in] Optional pointer to memory block to validate */
1011 BOOL quiet
) /* [in] Flag - if true, HEAP_ValidateInUseArena
1012 * does not complain */
1017 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
1019 ERR("Invalid heap %p!\n", heapPtr
);
1023 flags
&= HEAP_NO_SERIALIZE
;
1024 flags
|= heapPtr
->flags
;
1025 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1026 if (!(flags
& HEAP_NO_SERIALIZE
))
1027 RtlEnterHeapLock( &heapPtr
->critSection
);
1031 /* Only check this single memory block */
1033 if (!(subheap
= HEAP_FindSubHeap( heapPtr
, block
)) ||
1034 ((const char *)block
< (char *)subheap
+ subheap
->headerSize
1035 + sizeof(ARENA_INUSE
)))
1038 ERR("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1039 else if (WARN_ON(heap
))
1040 WARN("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1043 ret
= HEAP_ValidateInUseArena( subheap
, (const ARENA_INUSE
*)block
- 1, quiet
);
1045 if (!(flags
& HEAP_NO_SERIALIZE
))
1046 RtlLeaveHeapLock( &heapPtr
->critSection
);
1050 subheap
= &heapPtr
->subheap
;
1051 while (subheap
&& ret
)
1053 char *ptr
= (char *)subheap
+ subheap
->headerSize
;
1054 while (ptr
< (char *)subheap
+ subheap
->size
)
1056 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
1058 if (!HEAP_ValidateFreeArena( subheap
, (ARENA_FREE
*)ptr
)) {
1062 ptr
+= sizeof(ARENA_FREE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1066 if (!HEAP_ValidateInUseArena( subheap
, (ARENA_INUSE
*)ptr
, NOISY
)) {
1070 ptr
+= sizeof(ARENA_INUSE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1073 subheap
= subheap
->next
;
1076 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1081 /***********************************************************************
1082 * HeapCreate (KERNEL32.336)
1084 * Handle of heap: Success
1090 RtlCreateHeap(ULONG flags
,
1095 PRTL_HEAP_PARAMETERS Parameters
)
1099 /* Allocate the heap block */
1103 totalSize
= HEAP_DEF_SIZE
;
1104 flags
|= HEAP_GROWABLE
;
1106 if (!(subheap
= HEAP_CreateSubHeap( NULL
, addr
, flags
, commitSize
, totalSize
, Parameters
))) return 0;
1108 if (RtlpGetMode() == UserMode
)
1110 /* link it into the per-process heap list */
1113 HEAP
*heapPtr
= subheap
->heap
;
1114 RtlEnterHeapLock( &processHeap
->critSection
);
1115 list_add_head( &processHeap
->entry
, &heapPtr
->entry
);
1116 RtlLeaveHeapLock( &processHeap
->critSection
);
1120 processHeap
= subheap
->heap
; /* assume the first heap we create is the process main heap */
1121 list_init( &processHeap
->entry
);
1125 return (HANDLE
)subheap
;
1128 /***********************************************************************
1129 * HeapDestroy (KERNEL32.337)
1137 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1138 * Failure: The Heap handle, if heap is the process heap.
1141 RtlDestroyHeap(HANDLE heap
) /* [in] Handle of heap */
1143 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1146 DPRINT("%p\n", heap
);
1150 if (RtlpGetMode() == UserMode
)
1152 if (heap
== NtCurrentPeb()->ProcessHeap
)
1153 return heap
; /* cannot delete the main process heap */
1155 /* remove it from the per-process list */
1156 RtlEnterHeapLock( &processHeap
->critSection
);
1157 list_remove( &heapPtr
->entry
);
1158 RtlLeaveHeapLock( &processHeap
->critSection
);
1161 RtlDeleteHeapLock( &heapPtr
->critSection
);
1162 subheap
= &heapPtr
->subheap
;
1165 SUBHEAP
*next
= subheap
->next
;
1167 void *addr
= subheap
;
1168 ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &size
, MEM_RELEASE
);
1171 return (HANDLE
)NULL
;
1175 /***********************************************************************
1176 * HeapAlloc (KERNEL32.334)
1178 * Pointer to allocated memory block
1180 * 0x7d030f60--invalid flags in RtlHeapAllocate
1184 RtlAllocateHeap(HANDLE heap
, /* [in] Handle of private heap block */
1185 ULONG flags
, /* [in] Heap allocation control flags */
1186 ULONG size
) /* [in] Number of bytes to allocate */
1189 ARENA_INUSE
*pInUse
;
1191 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1192 SIZE_T rounded_size
;
1194 /* Validate the parameters */
1198 if (flags
& HEAP_GENERATE_EXCEPTIONS
)
1199 RtlRaiseStatus( STATUS_NO_MEMORY
);
1202 //flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1203 flags
|= heapPtr
->flags
;
1204 rounded_size
= ROUND_SIZE(size
);
1205 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1207 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1208 /* Locate a suitable free block */
1210 /* Locate a suitable free block */
1212 if (!(pArena
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &subheap
)))
1214 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1215 heap
, flags
, size
);
1216 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1217 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1221 /* Remove the arena from the free list */
1223 list_remove( &pArena
->entry
);
1225 /* Build the in-use arena */
1227 pInUse
= (ARENA_INUSE
*)pArena
;
1229 /* in-use arena is smaller than free arena,
1230 * so we have to add the difference to the size */
1231 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
) + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1232 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1234 /* Save user flags */
1235 subheap
->UserFlags
= flags
& HEAP_SETTABLE_USER_FLAGS
;
1237 /* Shrink the block */
1239 HEAP_ShrinkBlock( subheap
, pInUse
, rounded_size
);
1240 pInUse
->unused_bytes
= (pInUse
->size
& ARENA_SIZE_MASK
) - size
;
1242 if (flags
& HEAP_ZERO_MEMORY
)
1243 clear_block( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1245 mark_block_uninitialized( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1247 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1249 TRACE("(%p,%08lx,%08lx): returning %p\n", heap
, flags
, size
, pInUse
+ 1 );
1250 return (LPVOID
)(pInUse
+ 1);
1254 /***********************************************************************
1255 * HeapFree (KERNEL32.338)
1262 BOOLEAN NTAPI
RtlFreeHeap(
1263 HANDLE heap
, /* [in] Handle of heap */
1264 ULONG flags
, /* [in] Heap freeing flags */
1265 PVOID ptr
/* [in] Address of memory to free */
1268 ARENA_INUSE
*pInUse
;
1272 /* Validate the parameters */
1274 if (!ptr
) return TRUE
; /* freeing a NULL ptr isn't an error in Win2k */
1276 heapPtr
= HEAP_GetPtr( heap
);
1279 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1283 flags
&= HEAP_NO_SERIALIZE
;
1284 flags
|= heapPtr
->flags
;
1285 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1286 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1288 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1289 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1290 TRACE("(%p,%08lx,%p): returning FALSE\n", heap
, flags
, ptr
);
1294 /* Turn the block into a free block */
1296 pInUse
= (ARENA_INUSE
*)ptr
- 1;
1297 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1298 HEAP_MakeInUseBlockFree( subheap
, pInUse
);
1300 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1302 TRACE("(%p,%08lx,%p): returning TRUE\n", heap
, flags
, ptr
);
1307 /***********************************************************************
1310 * Heap [in] Handle of heap block
1311 * Flags [in] Heap reallocation flags
1312 * Ptr, [in] Address of memory to reallocate
1313 * Size [in] Number of bytes to reallocate
1316 * Pointer to reallocated memory block
1318 * 0x7d030f60--invalid flags in RtlHeapAllocate
1321 PVOID NTAPI
RtlReAllocateHeap(
1328 ARENA_INUSE
*pArena
;
1331 SIZE_T oldSize
, rounded_size
;
1333 if (!ptr
) return NULL
;
1334 if (!(heapPtr
= HEAP_GetPtr( heap
)))
1336 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1340 /* Validate the parameters */
1342 //Flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1343 // HEAP_REALLOC_IN_PLACE_ONLY;
1344 flags
|= heapPtr
->flags
;
1345 rounded_size
= ROUND_SIZE(size
);
1346 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1348 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1349 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1351 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1352 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1353 TRACE("(%p,%08lx,%p,%08lx): returning NULL\n", heap
, flags
, ptr
, size
);
1357 pArena
= (ARENA_INUSE
*)ptr
- 1;
1358 subheap
= HEAP_FindSubHeap( heapPtr
, pArena
);
1359 oldSize
= (pArena
->size
& ARENA_SIZE_MASK
);
1360 if (rounded_size
> oldSize
)
1362 char *pNext
= (char *)(pArena
+ 1) + oldSize
;
1363 if ((pNext
< (char *)subheap
+ subheap
->size
) &&
1364 (*(DWORD
*)pNext
& ARENA_FLAG_FREE
) &&
1365 (oldSize
+ (*(DWORD
*)pNext
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
) >= rounded_size
))
1367 /* The next block is free and large enough */
1368 ARENA_FREE
*pFree
= (ARENA_FREE
*)pNext
;
1369 list_remove( &pFree
->entry
);
1370 pArena
->size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(*pFree
);
1371 if (!HEAP_Commit( subheap
, pArena
, rounded_size
))
1373 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1374 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1375 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1378 HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
);
1380 else /* Do it the hard way */
1383 ARENA_INUSE
*pInUse
;
1384 SUBHEAP
*newsubheap
;
1386 if ((flags
& HEAP_REALLOC_IN_PLACE_ONLY
) ||
1387 !(pNew
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &newsubheap
)))
1389 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1390 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1391 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1395 /* Build the in-use arena */
1397 list_remove( &pNew
->entry
);
1398 pInUse
= (ARENA_INUSE
*)pNew
;
1399 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
)
1400 + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1401 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1402 HEAP_ShrinkBlock( newsubheap
, pInUse
, rounded_size
);
1403 mark_block_initialized( pInUse
+ 1, oldSize
);
1404 memcpy( pInUse
+ 1, pArena
+ 1, oldSize
);
1406 /* Free the previous block */
1408 HEAP_MakeInUseBlockFree( subheap
, pArena
);
1409 subheap
= newsubheap
;
1413 else HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
); /* Shrink the block */
1415 pArena
->unused_bytes
= (pArena
->size
& ARENA_SIZE_MASK
) - size
;
1417 /* Clear the extra bytes if needed */
1419 if (rounded_size
> oldSize
)
1421 if (flags
& HEAP_ZERO_MEMORY
)
1422 clear_block( (char *)(pArena
+ 1) + oldSize
,
1423 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1425 mark_block_uninitialized( (char *)(pArena
+ 1) + oldSize
,
1426 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1429 /* Return the new arena */
1431 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1433 TRACE("(%p,%08lx,%p,%08lx): returning %p\n", heap
, flags
, ptr
, size
, pArena
+ 1 );
1434 return (LPVOID
)(pArena
+ 1);
1438 /***********************************************************************
1444 RtlCompactHeap(HANDLE Heap
,
1452 /***********************************************************************
1454 * Attempts to acquire the critical section object for a specified heap.
1457 * Heap [in] Handle of heap to lock for exclusive access
1466 RtlLockHeap(IN HANDLE Heap
)
1468 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1471 RtlEnterHeapLock( &heapPtr
->critSection
);
1476 /***********************************************************************
1478 * Releases ownership of the critical section object.
1481 * Heap [in] Handle to the heap to unlock
1490 RtlUnlockHeap(HANDLE Heap
)
1492 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1495 RtlLeaveHeapLock( &heapPtr
->critSection
);
1500 /***********************************************************************
1503 * Heap [in] Handle of heap
1504 * Flags [in] Heap size control flags
1505 * Ptr [in] Address of memory to return size for
1508 * Size in bytes of allocated memory
1509 * 0xffffffff: Failure
1521 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1525 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1528 flags
&= HEAP_NO_SERIALIZE
;
1529 flags
|= heapPtr
->flags
;
1530 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1531 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1533 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1538 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
- 1;
1539 ret
= (pArena
->size
& ARENA_SIZE_MASK
) - pArena
->unused_bytes
;
1541 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1543 TRACE("(%p,%08lx,%p): returning %08lx\n", heap
, flags
, ptr
, ret
);
1548 /***********************************************************************
1550 * Validates a specified heap.
1553 * Heap [in] Handle to the heap
1554 * Flags [in] Bit flags that control access during operation
1555 * Block [in] Optional pointer to memory block to validate
1566 BOOLEAN NTAPI
RtlValidateHeap(
1572 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1575 return HEAP_IsRealArena( heapPtr
, Flags
, Block
, QUIET
);
1579 RtlInitializeHeapManager(VOID
)
1583 Peb
= NtCurrentPeb();
1585 Peb
->NumberOfHeaps
= 0;
1586 Peb
->MaximumNumberOfHeaps
= -1; /* no limit */
1587 Peb
->ProcessHeaps
= NULL
;
1589 //RtlInitializeHeapLock(&RtlpProcessHeapsListLock);
1597 RtlEnumProcessHeaps(PHEAP_ENUMERATION_ROUTINE HeapEnumerationRoutine
,
1600 NTSTATUS Status
= STATUS_SUCCESS
;
1602 struct list
*ptr
=NULL
;
1603 RtlEnterHeapLock(&processHeap
->critSection
);
1604 Status
=HeapEnumerationRoutine(processHeap
,lParam
);
1606 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1608 if (!NT_SUCCESS(Status
)) break;
1609 Status
= HeapEnumerationRoutine(ptr
,lParam
);
1612 RtlLeaveHeapLock(&processHeap
->critSection
);
1622 RtlGetProcessHeaps(ULONG count
,
1625 ULONG total
= 1; /* main heap */
1628 RtlEnterHeapLock( &processHeap
->critSection
);
1629 LIST_FOR_EACH( ptr
, &processHeap
->entry
) total
++;
1630 //if (total <= count)
1632 *(heaps
++) = processHeap
;
1634 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1636 if (i
>= count
) break;
1638 *(heaps
++) = LIST_ENTRY( ptr
, HEAP
, entry
);
1641 RtlLeaveHeapLock( &processHeap
->critSection
);
1650 RtlValidateProcessHeaps(VOID
)
1652 BOOLEAN Result
= TRUE
;
1655 RtlEnterHeapLock( &processHeap
->critSection
);
1657 for (pptr
= (HEAP
**)&NtCurrentPeb()->ProcessHeaps
; *pptr
; pptr
++)
1659 if (!RtlValidateHeap(*pptr
, 0, NULL
))
1666 RtlLeaveHeapLock( &processHeap
->critSection
);
1676 IN PVOID HeapHandle
,
1689 RtlSetUserValueHeap(IN PVOID HeapHandle
,
1691 IN PVOID BaseAddress
,
1694 HEAP
*heapPtr
= HEAP_GetPtr(HeapHandle
);
1695 ARENA_INUSE
*pInUse
;
1698 /* Get the subheap */
1699 pInUse
= (ARENA_INUSE
*)BaseAddress
- 1;
1700 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1703 subheap
->UserValue
= UserValue
;
1712 RtlGetUserInfoHeap(IN PVOID HeapHandle
,
1714 IN PVOID BaseAddress
,
1715 OUT PVOID
*UserValue
,
1716 OUT PULONG UserFlags
)
1718 HEAP
*heapPtr
= HEAP_GetPtr(HeapHandle
);
1719 ARENA_INUSE
*pInUse
;
1722 /* Get the subheap */
1723 pInUse
= (ARENA_INUSE
*)BaseAddress
- 1;
1724 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1727 DPRINT1("V/F: %lx %p\n", subheap
->UserValue
, subheap
->UserFlags
);
1728 if (UserValue
) *UserValue
= subheap
->UserValue
;
1729 if (UserFlags
) *UserFlags
= subheap
->UserFlags
;
1738 RtlUsageHeap(IN HANDLE Heap
,
1740 OUT PRTL_HEAP_USAGE Usage
)
1744 return STATUS_NOT_IMPLEMENTED
;
1749 RtlQueryTagHeap(IN PVOID HeapHandle
,
1752 IN BOOLEAN ResetCounters
,
1753 OUT PRTL_HEAP_TAG_INFO HeapTagInfo
)
1762 RtlExtendHeap(IN HANDLE Heap
,
1774 RtlCreateTagHeap(IN HANDLE HeapHandle
,
1777 IN PWSTR TagSubName
)