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 SIZE_T size
; /* Block size; must be the first field */
72 SIZE_T magic
: 23; /* Magic number */
73 SIZE_T has_user_data
: 1; /* There is user data associated with this block */
74 SIZE_T 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) */
77 typedef struct tagARENA_FREE
79 SIZE_T size
; /* Block size; must be the first field */
80 SIZE_T magic
; /* Magic number */
81 struct list entry
; /* Entry in free list */
84 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
85 #define ARENA_FLAG_PREV_FREE 0x00000002
86 #define ARENA_INUSE_MAGIC 0x455355 /* Value for arena 'magic' field */
87 #define ARENA_FREE_MAGIC 0x45455246 /* Value for arena 'magic' field */
90 #define ARENA_SIZE_MASK (~3L)
92 #define ARENA_SIZE_MASK (~7L)
95 #define ARENA_INUSE_FILLER 0x55
96 #define ARENA_FREE_FILLER 0xaa
99 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
104 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
106 #define QUIET 1 /* Suppress messages */
107 #define NOISY 0 /* Report all errors */
109 /* minimum data size (without arenas) of an allocated block */
110 #define HEAP_MIN_DATA_SIZE 16
111 /* minimum size that must remain to shrink an allocated block */
112 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
114 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
116 /* Max size of the blocks on the free lists */
117 static const DWORD HEAP_freeListSizes
[HEAP_NB_FREE_LISTS
] =
119 0x20, 0x80, 0x200, ~0UL
129 typedef struct tagSUBHEAP
131 SIZE_T size
; /* Size of the whole sub-heap */
132 SIZE_T commitSize
; /* Committed size of the sub-heap */
133 SIZE_T headerSize
; /* Size of the heap header */
134 struct tagSUBHEAP
*next
; /* Next sub-heap */
135 struct tagHEAP
*heap
; /* Main heap structure */
136 SIZE_T magic
; /* Magic number */
139 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
141 typedef struct tagHEAP_USER_DATA
143 LIST_ENTRY ListEntry
;
147 } HEAP_USER_DATA
, *PHEAP_USER_DATA
;
149 typedef struct tagHEAP
151 SUBHEAP subheap
; /* First sub-heap */
152 struct list entry
; /* Entry in process heap list */
153 RTL_CRITICAL_SECTION critSection
; /* Critical section for serialization */
154 FREE_LIST_ENTRY freeList
[HEAP_NB_FREE_LISTS
]; /* Free lists */
155 DWORD flags
; /* Heap flags */
156 DWORD magic
; /* Magic number */
157 PRTL_HEAP_COMMIT_ROUTINE commitRoutine
;
158 LIST_ENTRY UserDataHead
;
161 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
163 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
164 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
166 static HEAP
*processHeap
; /* main process heap */
168 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, DWORD flags
, LPCVOID block
, BOOL quiet
);
170 /* mark a block of memory as free for debugging purposes */
171 static __inline
void mark_block_free( void *ptr
, SIZE_T size
)
173 if (TRACE_ON(heap
)) memset( ptr
, ARENA_FREE_FILLER
, size
);
174 #ifdef VALGRIND_MAKE_NOACCESS
175 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr
, size
));
179 /* mark a block of memory as initialized for debugging purposes */
180 static __inline
void mark_block_initialized( void *ptr
, SIZE_T size
)
182 #ifdef VALGRIND_MAKE_READABLE
183 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr
, size
));
187 /* mark a block of memory as uninitialized for debugging purposes */
188 static __inline
void mark_block_uninitialized( void *ptr
, SIZE_T size
)
190 #ifdef VALGRIND_MAKE_WRITABLE
191 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr
, size
));
195 memset( ptr
, ARENA_INUSE_FILLER
, size
);
196 #ifdef VALGRIND_MAKE_WRITABLE
197 /* make it uninitialized to valgrind again */
198 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr
, size
));
203 /* clear contents of a block of memory */
204 static __inline
void clear_block( void *ptr
, SIZE_T size
)
206 mark_block_initialized( ptr
, size
);
207 memset( ptr
, 0, size
);
210 /* locate a free list entry of the appropriate size */
211 /* size is the size of the whole block including the arena header */
212 static __inline
unsigned int get_freelist_index( SIZE_T size
)
216 size
-= sizeof(ARENA_FREE
);
217 for (i
= 0; i
< HEAP_NB_FREE_LISTS
- 1; i
++) if (size
<= HEAP_freeListSizes
[i
]) break;
221 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug
=
223 0, 0, NULL
, /* will be set later */
224 { &process_heap_critsect_debug
.ProcessLocksList
, &process_heap_critsect_debug
.ProcessLocksList
},
228 /***********************************************************************
231 static void HEAP_Dump( HEAP
*heap
)
237 DPRINTF( "Heap: %p\n", heap
);
238 DPRINTF( "Next: %p Sub-heaps: %p",
239 LIST_ENTRY( heap
->entry
.next
, HEAP
, entry
), &heap
->subheap
);
240 subheap
= &heap
->subheap
;
241 while (subheap
->next
)
243 DPRINTF( " -> %p", subheap
->next
);
244 subheap
= subheap
->next
;
247 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
248 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
249 DPRINTF( "%p free %08lx prev=%p next=%p\n",
250 &heap
->freeList
[i
].arena
, HEAP_freeListSizes
[i
],
251 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.prev
, ARENA_FREE
, entry
),
252 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.next
, ARENA_FREE
, entry
));
254 subheap
= &heap
->subheap
;
257 SIZE_T freeSize
= 0, usedSize
= 0, arenaSize
= subheap
->headerSize
;
258 DPRINTF( "\n\nSub-heap %p: size=%08lx committed=%08lx\n",
259 subheap
, subheap
->size
, subheap
->commitSize
);
261 DPRINTF( "\n Block Stat Size Id\n" );
262 ptr
= (char*)subheap
+ subheap
->headerSize
;
263 while (ptr
< (char *)subheap
+ subheap
->size
)
265 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
267 ARENA_FREE
*pArena
= (ARENA_FREE
*)ptr
;
268 DPRINTF( "%p free %08lx prev=%p next=%p\n",
269 pArena
, pArena
->size
& ARENA_SIZE_MASK
,
270 LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
),
271 LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
) );
272 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
273 arenaSize
+= sizeof(ARENA_FREE
);
274 freeSize
+= pArena
->size
& ARENA_SIZE_MASK
;
276 else if (*(DWORD
*)ptr
& ARENA_FLAG_PREV_FREE
)
278 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
279 DPRINTF( "%p Used %08lx back=%p\n",
280 pArena
, pArena
->size
& ARENA_SIZE_MASK
, *((ARENA_FREE
**)pArena
- 1) );
281 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
282 arenaSize
+= sizeof(ARENA_INUSE
);
283 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
287 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
288 DPRINTF( "%p used %08lx\n", pArena
, pArena
->size
& ARENA_SIZE_MASK
);
289 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
290 arenaSize
+= sizeof(ARENA_INUSE
);
291 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
294 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
295 subheap
->size
, subheap
->commitSize
, freeSize
, usedSize
,
296 arenaSize
, (arenaSize
* 100) / subheap
->size
);
297 subheap
= subheap
->next
;
302 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry
)
305 TRACE( "Dumping entry %p\n", entry
);
306 TRACE( "lpData\t\t: %p\n", entry
->lpData
);
307 TRACE( "cbData\t\t: %08lx\n", entry
->cbData
);
308 TRACE( "cbOverhead\t: %08x\n", entry
->cbOverhead
);
309 TRACE( "iRegionIndex\t: %08x\n", entry
->iRegionIndex
);
310 TRACE( "WFlags\t\t: ");
311 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
312 TRACE( "PROCESS_HEAP_REGION ");
313 if (entry
->wFlags
& PROCESS_HEAP_UNCOMMITTED_RANGE
)
314 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
315 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
316 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
317 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
)
318 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
319 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_DDESHARE
)
320 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
321 rem_flags
= entry
->wFlags
&
322 ~(PROCESS_HEAP_REGION
| PROCESS_HEAP_UNCOMMITTED_RANGE
|
323 PROCESS_HEAP_ENTRY_BUSY
| PROCESS_HEAP_ENTRY_MOVEABLE
|
324 PROCESS_HEAP_ENTRY_DDESHARE
);
326 TRACE( "Unknown %08x", rem_flags
);
328 if ((entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
329 && (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
))
332 TRACE( "BLOCK->hMem\t\t:%p\n", entry
->Block
.hMem
);
334 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
336 TRACE( "Region.dwCommittedSize\t:%08lx\n",entry
->Region
.dwCommittedSize
);
337 TRACE( "Region.dwUnCommittedSize\t:%08lx\n",entry
->Region
.dwUnCommittedSize
);
338 TRACE( "Region.lpFirstBlock\t:%p\n",entry
->Region
.lpFirstBlock
);
339 TRACE( "Region.lpLastBlock\t:%p\n",entry
->Region
.lpLastBlock
);
344 static PHEAP_USER_DATA
HEAP_GetUserData(HEAP
*heapPtr
, PVOID BaseAddress
)
346 PLIST_ENTRY CurrentEntry
;
347 PHEAP_USER_DATA udata
;
349 CurrentEntry
= heapPtr
->UserDataHead
.Flink
;
350 while (CurrentEntry
!= &heapPtr
->UserDataHead
)
352 udata
= CONTAINING_RECORD(CurrentEntry
, HEAP_USER_DATA
, ListEntry
);
353 if (udata
->BaseAddress
== BaseAddress
)
355 CurrentEntry
= CurrentEntry
->Flink
;
360 static PHEAP_USER_DATA
HEAP_AllocUserData(HEAP
*heapPtr
, PVOID BaseAddress
)
362 /* Allocate user data entry */
364 PHEAP_USER_DATA udata
= RtlAllocateHeap(heapPtr
, 0, sizeof(HEAP_USER_DATA
));
365 if (!udata
) return NULL
;
366 udata
->BaseAddress
= BaseAddress
;
367 InsertTailList(&heapPtr
->UserDataHead
, &udata
->ListEntry
);
368 pInUse
= (ARENA_INUSE
*)BaseAddress
- 1;
369 pInUse
->has_user_data
= 1;
373 /***********************************************************************
376 * Pointer to the heap
379 static HEAP
*HEAP_GetPtr(
380 HANDLE heap
/* [in] Handle to the heap */
382 HEAP
*heapPtr
= (HEAP
*)heap
;
383 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
386 ERR("Invalid heap %p, magic:%.4s!\n", heap
, &heapPtr
->magic
);
388 ERR("Invalid heap %p!\n", heap
);
389 //KeDumpStackFrames(NULL);
392 if (TRACE_ON(heap
) && !HEAP_IsRealArena( heapPtr
, 0, NULL
, NOISY
))
394 HEAP_Dump( heapPtr
);
402 /***********************************************************************
403 * HEAP_InsertFreeBlock
405 * Insert a free block into the free list.
407 static __inline
void HEAP_InsertFreeBlock( HEAP
*heap
, ARENA_FREE
*pArena
, BOOL last
)
409 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( pArena
->size
+ sizeof(*pArena
) );
412 /* insert at end of free list, i.e. before the next free list entry */
414 if (pEntry
== &heap
->freeList
[HEAP_NB_FREE_LISTS
]) pEntry
= heap
->freeList
;
415 list_add_before( &pEntry
->arena
.entry
, &pArena
->entry
);
419 /* insert at head of free list */
420 list_add_after( &pEntry
->arena
.entry
, &pArena
->entry
);
422 pArena
->size
|= ARENA_FLAG_FREE
;
426 /***********************************************************************
428 * Find the sub-heap containing a given address.
434 static SUBHEAP
*HEAP_FindSubHeap(
435 const HEAP
*heap
, /* [in] Heap pointer */
436 LPCVOID ptr
/* [in] Address */
438 const SUBHEAP
*sub
= &heap
->subheap
;
441 if (((const char *)ptr
>= (const char *)sub
) &&
442 ((const char *)ptr
< (const char *)sub
+ sub
->size
)) return (SUBHEAP
*)sub
;
448 /***********************************************************************
451 * Make sure the heap storage is committed for a given size in the specified arena.
453 static __inline BOOL
HEAP_Commit( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T data_size
)
456 void *ptr
= (char *)(pArena
+ 1) + data_size
+ sizeof(ARENA_FREE
);
457 SIZE_T size
= (char *)ptr
- (char *)subheap
;
458 size
= (size
+ COMMIT_MASK
) & ~COMMIT_MASK
;
459 if (size
> subheap
->size
) size
= subheap
->size
;
460 if (size
<= subheap
->commitSize
) return TRUE
;
461 size
-= subheap
->commitSize
;
462 ptr
= (char *)subheap
+ subheap
->commitSize
;
463 if (subheap
->heap
->commitRoutine
!= NULL
)
465 Status
= subheap
->heap
->commitRoutine(subheap
->heap
, &ptr
, &size
);
469 Status
= ZwAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0,
470 &size
, MEM_COMMIT
, PAGE_READWRITE
);
472 if (!NT_SUCCESS(Status
))
474 WARN("Could not commit %08lx bytes at %p for heap %p\n",
475 size
, ptr
, subheap
->heap
);
478 subheap
->commitSize
+= size
;
483 /***********************************************************************
486 * If possible, decommit the heap storage from (including) 'ptr'.
488 static inline BOOL
HEAP_Decommit( SUBHEAP
*subheap
, void *ptr
)
491 SIZE_T decommit_size
;
492 SIZE_T size
= (char *)ptr
- (char *)subheap
;
494 /* round to next block and add one full block */
495 size
= ((size
+ COMMIT_MASK
) & ~COMMIT_MASK
) + COMMIT_MASK
+ 1;
496 if (size
>= subheap
->commitSize
) return TRUE
;
497 decommit_size
= subheap
->commitSize
- size
;
498 addr
= (char *)subheap
+ size
;
500 if (ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &decommit_size
, MEM_DECOMMIT
))
502 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
503 decommit_size
, (char *)subheap
+ size
, subheap
->heap
);
506 subheap
->commitSize
-= decommit_size
;
511 /***********************************************************************
512 * HEAP_CreateFreeBlock
514 * Create a free block at a specified address. 'size' is the size of the
515 * whole block, including the new arena.
517 static void HEAP_CreateFreeBlock( SUBHEAP
*subheap
, void *ptr
, SIZE_T size
)
523 /* Create a free arena */
524 mark_block_uninitialized( ptr
, sizeof( ARENA_FREE
) );
525 pFree
= (ARENA_FREE
*)ptr
;
526 pFree
->magic
= ARENA_FREE_MAGIC
;
528 /* If debugging, erase the freed block content */
530 pEnd
= (char *)ptr
+ size
;
531 if (pEnd
> (char *)subheap
+ subheap
->commitSize
) pEnd
= (char *)subheap
+ subheap
->commitSize
;
532 if (pEnd
> (char *)(pFree
+ 1)) mark_block_free( pFree
+ 1, pEnd
- (char *)(pFree
+ 1) );
534 /* Check if next block is free also */
536 if (((char *)ptr
+ size
< (char *)subheap
+ subheap
->size
) &&
537 (*(DWORD
*)((char *)ptr
+ size
) & ARENA_FLAG_FREE
))
539 /* Remove the next arena from the free list */
540 ARENA_FREE
*pNext
= (ARENA_FREE
*)((char *)ptr
+ size
);
541 list_remove( &pNext
->entry
);
542 size
+= (pNext
->size
& ARENA_SIZE_MASK
) + sizeof(*pNext
);
543 mark_block_free( pNext
, sizeof(ARENA_FREE
) );
546 /* Set the next block PREV_FREE flag and pointer */
548 last
= ((char *)ptr
+ size
>= (char *)subheap
+ subheap
->size
);
551 DWORD
*pNext
= (DWORD
*)((char *)ptr
+ size
);
552 *pNext
|= ARENA_FLAG_PREV_FREE
;
553 mark_block_initialized( pNext
- 1, sizeof( ARENA_FREE
* ) );
554 *((ARENA_FREE
**)pNext
- 1) = pFree
;
557 /* Last, insert the new block into the free list */
559 pFree
->size
= size
- sizeof(*pFree
);
560 HEAP_InsertFreeBlock( subheap
->heap
, pFree
, last
);
564 /***********************************************************************
565 * HEAP_MakeInUseBlockFree
567 * Turn an in-use block into a free block. Can also decommit the end of
568 * the heap, and possibly even free the sub-heap altogether.
570 static void HEAP_MakeInUseBlockFree( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
)
573 SIZE_T size
= (pArena
->size
& ARENA_SIZE_MASK
) + sizeof(*pArena
);
574 PHEAP_USER_DATA udata
;
576 /* Find and free user data */
577 if (pArena
->has_user_data
)
579 udata
= HEAP_GetUserData(subheap
->heap
, pArena
+ 1);
582 RemoveEntryList(&udata
->ListEntry
);
583 RtlFreeHeap(subheap
->heap
, 0, udata
);
587 /* Check if we can merge with previous block */
589 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
591 pFree
= *((ARENA_FREE
**)pArena
- 1);
592 size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
593 /* Remove it from the free list */
594 list_remove( &pFree
->entry
);
596 else pFree
= (ARENA_FREE
*)pArena
;
598 /* Create a free block */
600 HEAP_CreateFreeBlock( subheap
, pFree
, size
);
601 size
= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
602 if ((char *)pFree
+ size
< (char *)subheap
+ subheap
->size
)
603 return; /* Not the last block, so nothing more to do */
605 /* Free the whole sub-heap if it's empty and not the original one */
607 if (((char *)pFree
== (char *)subheap
+ subheap
->headerSize
) &&
608 (subheap
!= &subheap
->heap
->subheap
))
611 SUBHEAP
*pPrev
= &subheap
->heap
->subheap
;
612 /* Remove the free block from the list */
613 list_remove( &pFree
->entry
);
614 /* Remove the subheap from the list */
615 while (pPrev
&& (pPrev
->next
!= subheap
)) pPrev
= pPrev
->next
;
616 if (pPrev
) pPrev
->next
= subheap
->next
;
617 /* Free the memory */
619 ZwFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap
, &size
, MEM_RELEASE
);
623 /* Decommit the end of the heap */
626 /***********************************************************************
629 * Shrink an in-use block.
631 static void HEAP_ShrinkBlock(SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T size
)
633 if ((pArena
->size
& ARENA_SIZE_MASK
) >= size
+ HEAP_MIN_SHRINK_SIZE
)
635 HEAP_CreateFreeBlock( subheap
, (char *)(pArena
+ 1) + size
,
636 (pArena
->size
& ARENA_SIZE_MASK
) - size
);
637 /* assign size plus previous arena flags */
638 pArena
->size
= size
| (pArena
->size
& ~ARENA_SIZE_MASK
);
642 /* Turn off PREV_FREE flag in next block */
643 char *pNext
= (char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
);
644 if (pNext
< (char *)subheap
+ subheap
->size
)
645 *(DWORD
*)pNext
&= ~ARENA_FLAG_PREV_FREE
;
649 /***********************************************************************
652 static BOOL
HEAP_InitSubHeap( HEAP
*heap
, LPVOID address
, DWORD flags
,
653 SIZE_T commitSize
, SIZE_T totalSize
,
654 PRTL_HEAP_PARAMETERS Parameters
)
657 FREE_LIST_ENTRY
*pEntry
;
661 if (!address
&& ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0,
662 &commitSize
, MEM_COMMIT
, PAGE_READWRITE
))
664 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize
, address
);
668 /* Fill the sub-heap structure */
670 subheap
= (SUBHEAP
*)address
;
671 subheap
->heap
= heap
;
672 subheap
->size
= totalSize
;
673 subheap
->commitSize
= commitSize
;
674 subheap
->magic
= SUBHEAP_MAGIC
;
676 if ( subheap
!= (SUBHEAP
*)heap
)
678 /* If this is a secondary subheap, insert it into list */
680 subheap
->headerSize
= ROUND_SIZE( sizeof(SUBHEAP
) );
681 subheap
->next
= heap
->subheap
.next
;
682 heap
->subheap
.next
= subheap
;
686 /* If this is a primary subheap, initialize main heap */
688 subheap
->headerSize
= ROUND_SIZE( sizeof(HEAP
) );
689 subheap
->next
= NULL
;
691 heap
->magic
= HEAP_MAGIC
;
693 heap
->commitRoutine
= Parameters
->CommitRoutine
;
695 heap
->commitRoutine
= NULL
;
696 InitializeListHead(&heap
->UserDataHead
);
698 /* Build the free lists */
700 list_init( &heap
->freeList
[0].arena
.entry
);
701 for (i
= 0, pEntry
= heap
->freeList
; i
< HEAP_NB_FREE_LISTS
; i
++, pEntry
++)
703 pEntry
->arena
.size
= 0 | ARENA_FLAG_FREE
;
704 pEntry
->arena
.magic
= ARENA_FREE_MAGIC
;
705 if (i
) list_add_after( &pEntry
[-1].arena
.entry
, &pEntry
->arena
.entry
);
708 /* Initialize critical section */
710 if (RtlpGetMode() == UserMode
)
712 if (!processHeap
) /* do it by hand to avoid memory allocations */
714 heap
->critSection
.DebugInfo
= &process_heap_critsect_debug
;
715 heap
->critSection
.LockCount
= -1;
716 heap
->critSection
.RecursionCount
= 0;
717 heap
->critSection
.OwningThread
= 0;
718 heap
->critSection
.LockSemaphore
= 0;
719 heap
->critSection
.SpinCount
= 0;
720 process_heap_critsect_debug
.CriticalSection
= &heap
->critSection
;
722 else RtlInitializeHeapLock( &heap
->critSection
);
727 if (heap
->commitRoutine
)
729 if (subheap
!= (SUBHEAP
*)heap
)
731 Status
= heap
->commitRoutine(heap
, &address
, &commitSize
);
735 /* the caller is responsible for committing the first page! */
736 Status
= STATUS_SUCCESS
;
741 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
746 PAGE_EXECUTE_READWRITE
);
748 if (!NT_SUCCESS(Status
))
750 DPRINT("Could not commit %08lx bytes for sub-heap %p\n",
751 commitSize
, address
);
755 /* Create the first free block */
757 HEAP_CreateFreeBlock( subheap
, (LPBYTE
)subheap
+ subheap
->headerSize
,
758 subheap
->size
- subheap
->headerSize
);
763 /***********************************************************************
766 * Create a sub-heap of the given size.
767 * If heap == NULL, creates a main heap.
769 static SUBHEAP
*HEAP_CreateSubHeap( HEAP
*heap
, void *base
, DWORD flags
,
770 SIZE_T commitSize
, SIZE_T totalSize
,
771 IN PRTL_HEAP_PARAMETERS Parameters
)
773 LPVOID address
= base
;
775 /* round-up sizes on a 64K boundary */
776 totalSize
= (totalSize
+ 0xffff) & 0xffff0000;
777 commitSize
= (commitSize
+ 0xffff) & 0xffff0000;
778 if (!commitSize
) commitSize
= 0x10000;
779 if (totalSize
< commitSize
) totalSize
= commitSize
;
783 /* allocate the memory block */
784 if (ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0, &totalSize
,
785 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
))
787 WARN("Could not allocate %08lx bytes\n", totalSize
);
792 /* Initialize subheap */
794 if (!HEAP_InitSubHeap( heap
? heap
: (HEAP
*)address
,
795 address
, flags
, commitSize
, totalSize
, Parameters
))
798 if (!base
) ZwFreeVirtualMemory( NtCurrentProcess(), &address
, &size
, MEM_RELEASE
);
802 return (SUBHEAP
*)address
;
806 /***********************************************************************
809 * Find a free block at least as large as the requested size, and make sure
810 * the requested size is committed.
812 static ARENA_FREE
*HEAP_FindFreeBlock( HEAP
*heap
, SIZE_T size
,
813 SUBHEAP
**ppSubHeap
)
817 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( size
+ sizeof(ARENA_INUSE
) );
819 /* Find a suitable free list, and in it find a block large enough */
821 ptr
= &pEntry
->arena
.entry
;
822 while ((ptr
= list_next( &heap
->freeList
[0].arena
.entry
, ptr
)))
824 ARENA_FREE
*pArena
= LIST_ENTRY( ptr
, ARENA_FREE
, entry
);
825 SIZE_T arena_size
= (pArena
->size
& ARENA_SIZE_MASK
) +
826 sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
827 if (arena_size
>= size
)
829 subheap
= HEAP_FindSubHeap( heap
, pArena
);
830 if (!HEAP_Commit( subheap
, (ARENA_INUSE
*)pArena
, size
)) return NULL
;
831 *ppSubHeap
= subheap
;
836 /* If no block was found, attempt to grow the heap */
838 if (!(heap
->flags
& HEAP_GROWABLE
))
840 ERR("Not enough space in heap %p for %08lx bytes\n", heap
, size
);
843 /* make sure that we have a big enough size *committed* to fit another
844 * last free arena in !
845 * So just one heap struct, one first free arena which will eventually
846 * get used, and a second free arena that might get assigned all remaining
847 * free space in HEAP_ShrinkBlock() */
848 size
+= ROUND_SIZE(sizeof(SUBHEAP
)) + sizeof(ARENA_INUSE
) + sizeof(ARENA_FREE
);
849 if (!(subheap
= HEAP_CreateSubHeap( heap
, NULL
, heap
->flags
, size
,
850 max( HEAP_DEF_SIZE
, size
), NULL
)))
853 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
854 subheap
, size
, heap
);
856 *ppSubHeap
= subheap
;
857 return (ARENA_FREE
*)(subheap
+ 1);
860 /***********************************************************************
861 * HEAP_IsValidArenaPtr
863 * Check that the pointer is inside the range possible for arenas.
865 static BOOL
HEAP_IsValidArenaPtr( const HEAP
*heap
, const void *ptr
)
868 const SUBHEAP
*subheap
= HEAP_FindSubHeap( heap
, ptr
);
869 if (!subheap
) return FALSE
;
870 if ((const char *)ptr
>= (const char *)subheap
+ subheap
->headerSize
) return TRUE
;
871 if (subheap
!= &heap
->subheap
) return FALSE
;
872 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
873 if (ptr
== (const void *)&heap
->freeList
[i
].arena
) return TRUE
;
878 /***********************************************************************
879 * HEAP_ValidateFreeArena
881 static BOOL
HEAP_ValidateFreeArena( SUBHEAP
*subheap
, ARENA_FREE
*pArena
)
883 ARENA_FREE
*prev
, *next
;
884 char *heapEnd
= (char *)subheap
+ subheap
->size
;
886 /* Check for unaligned pointers */
887 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= 0 )
889 ERR("Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
893 /* Check magic number */
894 if (pArena
->magic
!= ARENA_FREE_MAGIC
)
896 ERR("Heap %p: invalid free arena magic for %p\n", subheap
->heap
, pArena
);
899 /* Check size flags */
900 if (!(pArena
->size
& ARENA_FLAG_FREE
) ||
901 (pArena
->size
& ARENA_FLAG_PREV_FREE
))
903 ERR("Heap %p: bad flags %08lx for free arena %p\n",
904 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
907 /* Check arena size */
908 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
910 ERR("Heap %p: bad size %08lx for free arena %p\n",
911 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
914 /* Check that next pointer is valid */
915 next
= LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
);
916 if (!HEAP_IsValidArenaPtr( subheap
->heap
, next
))
918 ERR("Heap %p: bad next ptr %p for arena %p\n",
919 subheap
->heap
, next
, pArena
);
922 /* Check that next arena is free */
923 if (!(next
->size
& ARENA_FLAG_FREE
) || (next
->magic
!= ARENA_FREE_MAGIC
))
925 ERR("Heap %p: next arena %p invalid for %p\n",
926 subheap
->heap
, next
, pArena
);
929 /* Check that prev pointer is valid */
930 prev
= LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
);
931 if (!HEAP_IsValidArenaPtr( subheap
->heap
, prev
))
933 ERR("Heap %p: bad prev ptr %p for arena %p\n",
934 subheap
->heap
, prev
, pArena
);
937 /* Check that prev arena is free */
938 if (!(prev
->size
& ARENA_FLAG_FREE
) || (prev
->magic
!= ARENA_FREE_MAGIC
))
940 /* this often means that the prev arena got overwritten
941 * by a memory write before that prev arena */
942 ERR("Heap %p: prev arena %p invalid for %p\n",
943 subheap
->heap
, prev
, pArena
);
946 /* Check that next block has PREV_FREE flag */
947 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
)
949 if (!(*(DWORD
*)((char *)(pArena
+ 1) +
950 (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
952 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
953 subheap
->heap
, pArena
);
956 /* Check next block back pointer */
957 if (*((ARENA_FREE
**)((char *)(pArena
+ 1) +
958 (pArena
->size
& ARENA_SIZE_MASK
)) - 1) != pArena
)
960 ERR("Heap %p: arena %p has wrong back ptr %p\n",
961 subheap
->heap
, pArena
,
962 *((ARENA_FREE
**)((char *)(pArena
+1) + (pArena
->size
& ARENA_SIZE_MASK
)) - 1));
969 /***********************************************************************
970 * HEAP_ValidateInUseArena
972 static BOOL
HEAP_ValidateInUseArena( const SUBHEAP
*subheap
, const ARENA_INUSE
*pArena
, BOOL quiet
)
974 const char *heapEnd
= (const char *)subheap
+ subheap
->size
;
976 /* Check for unaligned pointers */
977 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= 0 )
979 if ( quiet
== NOISY
)
981 ERR( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
982 if ( TRACE_ON(heap
) )
983 HEAP_Dump( subheap
->heap
);
985 else if ( WARN_ON(heap
) )
987 WARN( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
988 if ( TRACE_ON(heap
) )
989 HEAP_Dump( subheap
->heap
);
994 /* Check magic number */
995 if (pArena
->magic
!= ARENA_INUSE_MAGIC
)
997 if (quiet
== NOISY
) {
998 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
1000 HEAP_Dump( subheap
->heap
);
1001 } else if (WARN_ON(heap
)) {
1002 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
1004 HEAP_Dump( subheap
->heap
);
1008 /* Check size flags */
1009 if (pArena
->size
& ARENA_FLAG_FREE
)
1011 ERR("Heap %p: bad flags %08lx for in-use arena %p\n",
1012 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
1015 /* Check arena size */
1016 if ((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
1018 ERR("Heap %p: bad size %08lx for in-use arena %p\n",
1019 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
1022 /* Check next arena PREV_FREE flag */
1023 if (((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
) &&
1024 (*(const DWORD
*)((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
1026 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
1027 subheap
->heap
, pArena
);
1030 /* Check prev free arena */
1031 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
1033 const ARENA_FREE
*pPrev
= *((const ARENA_FREE
* const*)pArena
- 1);
1034 /* Check prev pointer */
1035 if (!HEAP_IsValidArenaPtr( subheap
->heap
, pPrev
))
1037 ERR("Heap %p: bad back ptr %p for arena %p\n",
1038 subheap
->heap
, pPrev
, pArena
);
1041 /* Check that prev arena is free */
1042 if (!(pPrev
->size
& ARENA_FLAG_FREE
) ||
1043 (pPrev
->magic
!= ARENA_FREE_MAGIC
))
1045 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1046 subheap
->heap
, pPrev
, pArena
);
1049 /* Check that prev arena is really the previous block */
1050 if ((const char *)(pPrev
+ 1) + (pPrev
->size
& ARENA_SIZE_MASK
) != (const char *)pArena
)
1052 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1053 subheap
->heap
, pPrev
, pArena
);
1060 /***********************************************************************
1061 * HEAP_IsRealArena [Internal]
1062 * Validates a block is a valid arena.
1068 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, /* [in] ptr to the heap */
1069 DWORD flags
, /* [in] Bit flags that control access during operation */
1070 LPCVOID block
, /* [in] Optional pointer to memory block to validate */
1071 BOOL quiet
) /* [in] Flag - if true, HEAP_ValidateInUseArena
1072 * does not complain */
1077 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
1079 ERR("Invalid heap %p!\n", heapPtr
);
1083 flags
&= HEAP_NO_SERIALIZE
;
1084 flags
|= heapPtr
->flags
;
1085 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1086 if (!(flags
& HEAP_NO_SERIALIZE
))
1087 RtlEnterHeapLock( &heapPtr
->critSection
);
1091 /* Only check this single memory block */
1093 if (!(subheap
= HEAP_FindSubHeap( heapPtr
, block
)) ||
1094 ((const char *)block
< (char *)subheap
+ subheap
->headerSize
1095 + sizeof(ARENA_INUSE
)))
1098 ERR("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1099 else if (WARN_ON(heap
))
1100 WARN("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1103 ret
= HEAP_ValidateInUseArena( subheap
, (const ARENA_INUSE
*)block
- 1, quiet
);
1105 if (!(flags
& HEAP_NO_SERIALIZE
))
1106 RtlLeaveHeapLock( &heapPtr
->critSection
);
1110 subheap
= &heapPtr
->subheap
;
1111 while (subheap
&& ret
)
1113 char *ptr
= (char *)subheap
+ subheap
->headerSize
;
1114 while (ptr
< (char *)subheap
+ subheap
->size
)
1116 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
1118 if (!HEAP_ValidateFreeArena( subheap
, (ARENA_FREE
*)ptr
)) {
1122 ptr
+= sizeof(ARENA_FREE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1126 if (!HEAP_ValidateInUseArena( subheap
, (ARENA_INUSE
*)ptr
, NOISY
)) {
1130 ptr
+= sizeof(ARENA_INUSE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1133 subheap
= subheap
->next
;
1136 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1141 /***********************************************************************
1142 * HeapCreate (KERNEL32.336)
1144 * Handle of heap: Success
1150 RtlCreateHeap(ULONG flags
,
1155 PRTL_HEAP_PARAMETERS Parameters
)
1159 /* Allocate the heap block */
1163 totalSize
= HEAP_DEF_SIZE
;
1164 flags
|= HEAP_GROWABLE
;
1166 if (!(subheap
= HEAP_CreateSubHeap( NULL
, addr
, flags
, commitSize
, totalSize
, Parameters
))) return 0;
1168 if (RtlpGetMode() == UserMode
)
1170 /* link it into the per-process heap list */
1173 HEAP
*heapPtr
= subheap
->heap
;
1174 RtlEnterHeapLock( &processHeap
->critSection
);
1175 list_add_head( &processHeap
->entry
, &heapPtr
->entry
);
1176 RtlLeaveHeapLock( &processHeap
->critSection
);
1180 processHeap
= subheap
->heap
; /* assume the first heap we create is the process main heap */
1181 list_init( &processHeap
->entry
);
1185 return (HANDLE
)subheap
;
1188 /***********************************************************************
1189 * HeapDestroy (KERNEL32.337)
1197 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1198 * Failure: The Heap handle, if heap is the process heap.
1201 RtlDestroyHeap(HANDLE heap
) /* [in] Handle of heap */
1203 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1206 DPRINT("%p\n", heap
);
1210 if (RtlpGetMode() == UserMode
)
1212 if (heap
== NtCurrentPeb()->ProcessHeap
)
1213 return heap
; /* cannot delete the main process heap */
1215 /* remove it from the per-process list */
1216 RtlEnterHeapLock( &processHeap
->critSection
);
1217 list_remove( &heapPtr
->entry
);
1218 RtlLeaveHeapLock( &processHeap
->critSection
);
1221 RtlDeleteHeapLock( &heapPtr
->critSection
);
1222 subheap
= &heapPtr
->subheap
;
1225 SUBHEAP
*next
= subheap
->next
;
1227 void *addr
= subheap
;
1228 ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &size
, MEM_RELEASE
);
1231 return (HANDLE
)NULL
;
1235 /***********************************************************************
1236 * HeapAlloc (KERNEL32.334)
1238 * Pointer to allocated memory block
1240 * 0x7d030f60--invalid flags in RtlHeapAllocate
1244 RtlAllocateHeap(HANDLE heap
, /* [in] Handle of private heap block */
1245 ULONG flags
, /* [in] Heap allocation control flags */
1246 ULONG size
) /* [in] Number of bytes to allocate */
1249 ARENA_INUSE
*pInUse
;
1251 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1252 SIZE_T rounded_size
;
1254 /* Validate the parameters */
1258 if (flags
& HEAP_GENERATE_EXCEPTIONS
)
1259 RtlRaiseStatus( STATUS_NO_MEMORY
);
1262 //flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1263 flags
|= heapPtr
->flags
;
1264 rounded_size
= ROUND_SIZE(size
);
1265 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1267 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1268 /* Locate a suitable free block */
1270 /* Locate a suitable free block */
1272 if (!(pArena
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &subheap
)))
1274 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1275 heap
, flags
, size
);
1276 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1277 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1281 /* Remove the arena from the free list */
1283 list_remove( &pArena
->entry
);
1285 /* Build the in-use arena */
1287 pInUse
= (ARENA_INUSE
*)pArena
;
1289 /* in-use arena is smaller than free arena,
1290 * so we have to add the difference to the size */
1291 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
) + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1292 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1293 pInUse
->has_user_data
= 0;
1295 /* Shrink the block */
1297 HEAP_ShrinkBlock( subheap
, pInUse
, rounded_size
);
1298 pInUse
->unused_bytes
= (pInUse
->size
& ARENA_SIZE_MASK
) - size
;
1300 if (flags
& HEAP_ZERO_MEMORY
)
1301 clear_block( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1303 mark_block_uninitialized( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1305 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1307 TRACE("(%p,%08lx,%08lx): returning %p\n", heap
, flags
, size
, pInUse
+ 1 );
1308 return (LPVOID
)(pInUse
+ 1);
1312 /***********************************************************************
1313 * HeapFree (KERNEL32.338)
1320 BOOLEAN NTAPI
RtlFreeHeap(
1321 HANDLE heap
, /* [in] Handle of heap */
1322 ULONG flags
, /* [in] Heap freeing flags */
1323 PVOID ptr
/* [in] Address of memory to free */
1326 ARENA_INUSE
*pInUse
;
1330 /* Validate the parameters */
1332 if (!ptr
) return TRUE
; /* freeing a NULL ptr isn't an error in Win2k */
1334 heapPtr
= HEAP_GetPtr( heap
);
1337 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1341 flags
&= HEAP_NO_SERIALIZE
;
1342 flags
|= heapPtr
->flags
;
1343 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1344 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1346 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1347 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1348 TRACE("(%p,%08lx,%p): returning FALSE\n", heap
, flags
, ptr
);
1352 /* Turn the block into a free block */
1354 pInUse
= (ARENA_INUSE
*)ptr
- 1;
1355 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1356 HEAP_MakeInUseBlockFree( subheap
, pInUse
);
1358 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1360 TRACE("(%p,%08lx,%p): returning TRUE\n", heap
, flags
, ptr
);
1365 /***********************************************************************
1368 * Heap [in] Handle of heap block
1369 * Flags [in] Heap reallocation flags
1370 * Ptr, [in] Address of memory to reallocate
1371 * Size [in] Number of bytes to reallocate
1374 * Pointer to reallocated memory block
1376 * 0x7d030f60--invalid flags in RtlHeapAllocate
1379 PVOID NTAPI
RtlReAllocateHeap(
1386 ARENA_INUSE
*pArena
;
1389 SIZE_T oldSize
, rounded_size
;
1391 if (!ptr
) return NULL
;
1392 if (!(heapPtr
= HEAP_GetPtr( heap
)))
1394 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1398 /* Validate the parameters */
1400 //Flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1401 // HEAP_REALLOC_IN_PLACE_ONLY;
1402 flags
|= heapPtr
->flags
;
1403 rounded_size
= ROUND_SIZE(size
);
1404 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1406 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1407 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1409 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1410 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1411 TRACE("(%p,%08lx,%p,%08lx): returning NULL\n", heap
, flags
, ptr
, size
);
1415 pArena
= (ARENA_INUSE
*)ptr
- 1;
1416 subheap
= HEAP_FindSubHeap( heapPtr
, pArena
);
1417 oldSize
= (pArena
->size
& ARENA_SIZE_MASK
);
1418 if (rounded_size
> oldSize
)
1420 char *pNext
= (char *)(pArena
+ 1) + oldSize
;
1421 if ((pNext
< (char *)subheap
+ subheap
->size
) &&
1422 (*(DWORD
*)pNext
& ARENA_FLAG_FREE
) &&
1423 (oldSize
+ (*(DWORD
*)pNext
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
) >= rounded_size
))
1425 /* The next block is free and large enough */
1426 ARENA_FREE
*pFree
= (ARENA_FREE
*)pNext
;
1427 list_remove( &pFree
->entry
);
1428 pArena
->size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(*pFree
);
1429 if (!HEAP_Commit( subheap
, pArena
, rounded_size
))
1431 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1432 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1433 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1436 HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
);
1438 else /* Do it the hard way */
1441 ARENA_INUSE
*pInUse
;
1442 SUBHEAP
*newsubheap
;
1444 if ((flags
& HEAP_REALLOC_IN_PLACE_ONLY
) ||
1445 !(pNew
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &newsubheap
)))
1447 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1448 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1449 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1453 /* Build the in-use arena */
1455 list_remove( &pNew
->entry
);
1456 pInUse
= (ARENA_INUSE
*)pNew
;
1457 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
)
1458 + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1459 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1460 HEAP_ShrinkBlock( newsubheap
, pInUse
, rounded_size
);
1461 mark_block_initialized( pInUse
+ 1, oldSize
);
1462 memcpy( pInUse
+ 1, pArena
+ 1, oldSize
);
1464 /* Free the previous block */
1466 HEAP_MakeInUseBlockFree( subheap
, pArena
);
1467 subheap
= newsubheap
;
1471 else HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
); /* Shrink the block */
1473 pArena
->unused_bytes
= (pArena
->size
& ARENA_SIZE_MASK
) - size
;
1475 /* Clear the extra bytes if needed */
1477 if (rounded_size
> oldSize
)
1479 if (flags
& HEAP_ZERO_MEMORY
)
1480 clear_block( (char *)(pArena
+ 1) + oldSize
,
1481 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1483 mark_block_uninitialized( (char *)(pArena
+ 1) + oldSize
,
1484 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1487 /* Return the new arena */
1489 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1491 TRACE("(%p,%08lx,%p,%08lx): returning %p\n", heap
, flags
, ptr
, size
, pArena
+ 1 );
1492 return (LPVOID
)(pArena
+ 1);
1496 /***********************************************************************
1502 RtlCompactHeap(HANDLE Heap
,
1510 /***********************************************************************
1512 * Attempts to acquire the critical section object for a specified heap.
1515 * Heap [in] Handle of heap to lock for exclusive access
1524 RtlLockHeap(IN HANDLE Heap
)
1526 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1529 RtlEnterHeapLock( &heapPtr
->critSection
);
1534 /***********************************************************************
1536 * Releases ownership of the critical section object.
1539 * Heap [in] Handle to the heap to unlock
1548 RtlUnlockHeap(HANDLE Heap
)
1550 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1553 RtlLeaveHeapLock( &heapPtr
->critSection
);
1558 /***********************************************************************
1561 * Heap [in] Handle of heap
1562 * Flags [in] Heap size control flags
1563 * Ptr [in] Address of memory to return size for
1566 * Size in bytes of allocated memory
1567 * 0xffffffff: Failure
1579 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1583 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1586 flags
&= HEAP_NO_SERIALIZE
;
1587 flags
|= heapPtr
->flags
;
1588 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1589 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1591 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1596 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
- 1;
1597 ret
= (pArena
->size
& ARENA_SIZE_MASK
) - pArena
->unused_bytes
;
1599 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1601 TRACE("(%p,%08lx,%p): returning %08lx\n", heap
, flags
, ptr
, ret
);
1606 /***********************************************************************
1608 * Validates a specified heap.
1611 * Heap [in] Handle to the heap
1612 * Flags [in] Bit flags that control access during operation
1613 * Block [in] Optional pointer to memory block to validate
1624 BOOLEAN NTAPI
RtlValidateHeap(
1630 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1633 return HEAP_IsRealArena( heapPtr
, Flags
, Block
, QUIET
);
1637 RtlInitializeHeapManager(VOID
)
1641 Peb
= NtCurrentPeb();
1643 Peb
->NumberOfHeaps
= 0;
1644 Peb
->MaximumNumberOfHeaps
= -1; /* no limit */
1645 Peb
->ProcessHeaps
= NULL
;
1647 //RtlInitializeHeapLock(&RtlpProcessHeapsListLock);
1655 RtlEnumProcessHeaps(PHEAP_ENUMERATION_ROUTINE HeapEnumerationRoutine
,
1658 NTSTATUS Status
= STATUS_SUCCESS
;
1660 struct list
*ptr
=NULL
;
1661 RtlEnterHeapLock(&processHeap
->critSection
);
1662 Status
=HeapEnumerationRoutine(processHeap
,lParam
);
1664 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1666 if (!NT_SUCCESS(Status
)) break;
1667 Status
= HeapEnumerationRoutine(ptr
,lParam
);
1670 RtlLeaveHeapLock(&processHeap
->critSection
);
1680 RtlGetProcessHeaps(ULONG count
,
1683 ULONG total
= 1; /* main heap */
1686 RtlEnterHeapLock( &processHeap
->critSection
);
1687 LIST_FOR_EACH( ptr
, &processHeap
->entry
) total
++;
1688 //if (total <= count)
1690 *(heaps
++) = processHeap
;
1692 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1694 if (i
>= count
) break;
1696 *(heaps
++) = LIST_ENTRY( ptr
, HEAP
, entry
);
1699 RtlLeaveHeapLock( &processHeap
->critSection
);
1708 RtlValidateProcessHeaps(VOID
)
1710 BOOLEAN Result
= TRUE
;
1713 RtlEnterHeapLock( &processHeap
->critSection
);
1715 for (pptr
= (HEAP
**)&NtCurrentPeb()->ProcessHeaps
; *pptr
; pptr
++)
1717 if (!RtlValidateHeap(*pptr
, 0, NULL
))
1724 RtlLeaveHeapLock( &processHeap
->critSection
);
1734 IN PVOID HeapHandle
,
1747 RtlSetUserValueHeap(IN PVOID HeapHandle
,
1749 IN PVOID BaseAddress
,
1753 PHEAP_USER_DATA udata
;
1755 heapPtr
= HEAP_GetPtr(HeapHandle
);
1758 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1761 udata
= HEAP_GetUserData(heapPtr
, BaseAddress
);
1764 udata
= HEAP_AllocUserData(heapPtr
, BaseAddress
);
1765 if (!udata
) return FALSE
;
1767 udata
->UserValue
= UserValue
;
1776 RtlSetUserFlagsHeap(IN PVOID HeapHandle
,
1778 IN PVOID BaseAddress
,
1782 PHEAP_USER_DATA udata
;
1784 heapPtr
= HEAP_GetPtr(HeapHandle
);
1787 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1790 udata
= HEAP_GetUserData(heapPtr
, BaseAddress
);
1793 udata
= HEAP_AllocUserData(heapPtr
, BaseAddress
);
1794 if (!udata
) return FALSE
;
1796 udata
->UserFlags
= UserFlags
& HEAP_SETTABLE_USER_FLAGS
;
1805 RtlGetUserInfoHeap(IN PVOID HeapHandle
,
1807 IN PVOID BaseAddress
,
1808 OUT PVOID
*UserValue
,
1809 OUT PULONG UserFlags
)
1812 PHEAP_USER_DATA udata
;
1814 heapPtr
= HEAP_GetPtr(HeapHandle
);
1817 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1820 udata
= HEAP_GetUserData(heapPtr
, BaseAddress
);
1823 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1826 if (UserValue
) *UserValue
= udata
->UserValue
;
1827 if (UserFlags
) *UserFlags
= udata
->UserFlags
;
1836 RtlUsageHeap(IN HANDLE Heap
,
1838 OUT PRTL_HEAP_USAGE Usage
)
1842 return STATUS_NOT_IMPLEMENTED
;
1847 RtlQueryTagHeap(IN PVOID HeapHandle
,
1850 IN BOOLEAN ResetCounters
,
1851 OUT PRTL_HEAP_TAG_INFO HeapTagInfo
)
1860 RtlExtendHeap(IN HANDLE Heap
,
1872 RtlCreateTagHeap(IN HANDLE HeapHandle
,
1875 IN PWSTR TagSubName
)
1884 RtlWalkHeap(IN HANDLE HeapHandle
,
1888 return STATUS_NOT_IMPLEMENTED
;
1893 RtlProtectHeap(IN PVOID HeapHandle
,
1894 IN BOOLEAN ReadOnly
)
1902 RtlSetHeapInformation(IN HANDLE HeapHandle OPTIONAL
,
1903 IN HEAP_INFORMATION_CLASS HeapInformationClass
,
1904 IN PVOID HeapInformation
,
1905 IN SIZE_T HeapInformationLength
)
1913 RtlQueryHeapInformation(HANDLE HeapHandle
,
1914 HEAP_INFORMATION_CLASS HeapInformationClass
,
1915 PVOID HeapInformation OPTIONAL
,
1916 SIZE_T HeapInformationLength OPTIONAL
,
1917 PSIZE_T ReturnLength OPTIONAL
)
1925 RtlMultipleAllocateHeap(IN PVOID HeapHandle
,
1937 RtlMultipleFreeHeap(IN PVOID HeapHandle
,