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 DWORD magic
: 23; /* Magic number */
73 DWORD has_user_data
: 1; /* There is user data associated with this block */
74 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) */
77 typedef struct tagARENA_FREE
79 SIZE_T size
; /* Block size; must be the first field */
80 DWORD 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
98 /* everything is aligned on 8 byte boundaries (16 for Win64)*/
99 #define ALIGNMENT (2*sizeof(void*))
100 #define ARENA_OFFSET (ALIGNMENT - sizeof(ARENA_INUSE))
102 #define ROUND_SIZE(size) ((((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1)) + ARENA_OFFSET)
105 #define QUIET 1 /* Suppress messages */
106 #define NOISY 0 /* Report all errors */
108 /* minimum data size (without arenas) of an allocated block */
109 #define HEAP_MIN_DATA_SIZE ROUND_SIZE(2 * sizeof(struct list))
110 /* minimum size that must remain to shrink an allocated block */
111 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
113 #define HEAP_NB_FREE_LISTS 5 /* Number of free lists */
115 /* Max size of the blocks on the free lists */
116 static const DWORD HEAP_freeListSizes
[HEAP_NB_FREE_LISTS
] =
118 0x10, 0x20, 0x80, 0x200, MAXULONG
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 DWORD headerSize
; /* Size of the heap header */
134 struct tagSUBHEAP
*next
; /* Next sub-heap */
135 struct tagHEAP
*heap
; /* Main heap structure */
136 DWORD 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 DECLSPEC_ALIGN(8) 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 /* get the memory protection type to use for a given heap */
222 static inline ULONG
get_protection_type( DWORD flags
)
224 return (flags
& HEAP_CREATE_ENABLE_EXECUTE
) ? PAGE_EXECUTE_READWRITE
: PAGE_READWRITE
;
227 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug
=
229 0, 0, NULL
, /* will be set later */
230 { &process_heap_critsect_debug
.ProcessLocksList
, &process_heap_critsect_debug
.ProcessLocksList
},
234 /***********************************************************************
237 static void HEAP_Dump( HEAP
*heap
)
243 DPRINTF( "Heap: %p\n", heap
);
244 DPRINTF( "Next: %p Sub-heaps: %p",
245 LIST_ENTRY( heap
->entry
.next
, HEAP
, entry
), &heap
->subheap
);
246 subheap
= &heap
->subheap
;
247 while (subheap
->next
)
249 DPRINTF( " -> %p", subheap
->next
);
250 subheap
= subheap
->next
;
253 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
254 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
255 DPRINTF( "%p free %08lx prev=%p next=%p\n",
256 &heap
->freeList
[i
].arena
, HEAP_freeListSizes
[i
],
257 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.prev
, ARENA_FREE
, entry
),
258 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.next
, ARENA_FREE
, entry
));
260 subheap
= &heap
->subheap
;
263 SIZE_T freeSize
= 0, usedSize
= 0, arenaSize
= subheap
->headerSize
;
264 DPRINTF( "\n\nSub-heap %p: size=%08lx committed=%08lx\n",
265 subheap
, subheap
->size
, subheap
->commitSize
);
267 DPRINTF( "\n Block Stat Size Id\n" );
268 ptr
= (char*)subheap
+ subheap
->headerSize
;
269 while (ptr
< (char *)subheap
+ subheap
->size
)
271 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
273 ARENA_FREE
*pArena
= (ARENA_FREE
*)ptr
;
274 DPRINTF( "%p free %08lx prev=%p next=%p\n",
275 pArena
, pArena
->size
& ARENA_SIZE_MASK
,
276 LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
),
277 LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
) );
278 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
279 arenaSize
+= sizeof(ARENA_FREE
);
280 freeSize
+= pArena
->size
& ARENA_SIZE_MASK
;
282 else if (*(DWORD
*)ptr
& ARENA_FLAG_PREV_FREE
)
284 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
285 DPRINTF( "%p Used %08lx back=%p\n",
286 pArena
, pArena
->size
& ARENA_SIZE_MASK
, *((ARENA_FREE
**)pArena
- 1) );
287 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
288 arenaSize
+= sizeof(ARENA_INUSE
);
289 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
293 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
294 DPRINTF( "%p used %08lx\n", pArena
, pArena
->size
& ARENA_SIZE_MASK
);
295 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
296 arenaSize
+= sizeof(ARENA_INUSE
);
297 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
300 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
301 subheap
->size
, subheap
->commitSize
, freeSize
, usedSize
,
302 arenaSize
, (arenaSize
* 100) / subheap
->size
);
303 subheap
= subheap
->next
;
308 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry
)
311 TRACE( "Dumping entry %p\n", entry
);
312 TRACE( "lpData\t\t: %p\n", entry
->lpData
);
313 TRACE( "cbData\t\t: %08lx\n", entry
->cbData
);
314 TRACE( "cbOverhead\t: %08x\n", entry
->cbOverhead
);
315 TRACE( "iRegionIndex\t: %08x\n", entry
->iRegionIndex
);
316 TRACE( "WFlags\t\t: ");
317 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
318 TRACE( "PROCESS_HEAP_REGION ");
319 if (entry
->wFlags
& PROCESS_HEAP_UNCOMMITTED_RANGE
)
320 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
321 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
322 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
323 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
)
324 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
325 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_DDESHARE
)
326 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
327 rem_flags
= entry
->wFlags
&
328 ~(PROCESS_HEAP_REGION
| PROCESS_HEAP_UNCOMMITTED_RANGE
|
329 PROCESS_HEAP_ENTRY_BUSY
| PROCESS_HEAP_ENTRY_MOVEABLE
|
330 PROCESS_HEAP_ENTRY_DDESHARE
);
332 TRACE( "Unknown %08x", rem_flags
);
334 if ((entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
335 && (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
))
338 TRACE( "BLOCK->hMem\t\t:%p\n", entry
->Block
.hMem
);
340 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
342 TRACE( "Region.dwCommittedSize\t:%08lx\n",entry
->Region
.dwCommittedSize
);
343 TRACE( "Region.dwUnCommittedSize\t:%08lx\n",entry
->Region
.dwUnCommittedSize
);
344 TRACE( "Region.lpFirstBlock\t:%p\n",entry
->Region
.lpFirstBlock
);
345 TRACE( "Region.lpLastBlock\t:%p\n",entry
->Region
.lpLastBlock
);
350 static PHEAP_USER_DATA
HEAP_GetUserData(HEAP
*heapPtr
, PVOID BaseAddress
)
352 PLIST_ENTRY CurrentEntry
;
353 PHEAP_USER_DATA udata
;
355 CurrentEntry
= heapPtr
->UserDataHead
.Flink
;
356 while (CurrentEntry
!= &heapPtr
->UserDataHead
)
358 udata
= CONTAINING_RECORD(CurrentEntry
, HEAP_USER_DATA
, ListEntry
);
359 if (udata
->BaseAddress
== BaseAddress
)
361 CurrentEntry
= CurrentEntry
->Flink
;
366 static PHEAP_USER_DATA
HEAP_AllocUserData(HEAP
*heapPtr
, PVOID BaseAddress
)
368 /* Allocate user data entry */
370 PHEAP_USER_DATA udata
= RtlAllocateHeap(heapPtr
, 0, sizeof(HEAP_USER_DATA
));
371 if (!udata
) return NULL
;
372 udata
->BaseAddress
= BaseAddress
;
373 InsertTailList(&heapPtr
->UserDataHead
, &udata
->ListEntry
);
374 pInUse
= (ARENA_INUSE
*)BaseAddress
- 1;
375 pInUse
->has_user_data
= 1;
379 /***********************************************************************
382 * Pointer to the heap
385 static HEAP
*HEAP_GetPtr(
386 HANDLE heap
/* [in] Handle to the heap */
388 HEAP
*heapPtr
= (HEAP
*)heap
;
389 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
392 ERR("Invalid heap %p, magic:%.4s!\n", heap
, &heapPtr
->magic
);
394 ERR("Invalid heap %p!\n", heap
);
395 //KeDumpStackFrames(NULL);
398 if (TRACE_ON(heap
) && !HEAP_IsRealArena( heapPtr
, 0, NULL
, NOISY
))
400 HEAP_Dump( heapPtr
);
408 /***********************************************************************
409 * HEAP_InsertFreeBlock
411 * Insert a free block into the free list.
413 static __inline
void HEAP_InsertFreeBlock( HEAP
*heap
, ARENA_FREE
*pArena
, BOOL last
)
415 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( pArena
->size
+ sizeof(*pArena
) );
418 /* insert at end of free list, i.e. before the next free list entry */
420 if (pEntry
== &heap
->freeList
[HEAP_NB_FREE_LISTS
]) pEntry
= heap
->freeList
;
421 list_add_before( &pEntry
->arena
.entry
, &pArena
->entry
);
425 /* insert at head of free list */
426 list_add_after( &pEntry
->arena
.entry
, &pArena
->entry
);
428 pArena
->size
|= ARENA_FLAG_FREE
;
432 /***********************************************************************
434 * Find the sub-heap containing a given address.
440 static SUBHEAP
*HEAP_FindSubHeap(
441 const HEAP
*heap
, /* [in] Heap pointer */
442 LPCVOID ptr
/* [in] Address */
444 const SUBHEAP
*sub
= &heap
->subheap
;
447 if (((const char *)ptr
>= (const char *)sub
) &&
448 ((const char *)ptr
< (const char *)sub
+ sub
->size
)) return (SUBHEAP
*)sub
;
454 /***********************************************************************
457 * Make sure the heap storage is committed for a given size in the specified arena.
459 static __inline BOOL
HEAP_Commit( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T data_size
)
462 void *ptr
= (char *)(pArena
+ 1) + data_size
+ sizeof(ARENA_FREE
);
463 SIZE_T size
= (char *)ptr
- (char *)subheap
;
464 size
= (size
+ COMMIT_MASK
) & ~COMMIT_MASK
;
465 if (size
> subheap
->size
) size
= subheap
->size
;
466 if (size
<= subheap
->commitSize
) return TRUE
;
467 size
-= subheap
->commitSize
;
468 ptr
= (char *)subheap
+ subheap
->commitSize
;
469 if (subheap
->heap
->commitRoutine
!= NULL
)
471 Status
= subheap
->heap
->commitRoutine(subheap
->heap
, &ptr
, &size
);
475 Status
= ZwAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0,
476 &size
, MEM_COMMIT
, get_protection_type(subheap
->heap
->flags
) );
478 if (!NT_SUCCESS(Status
))
480 WARN("Could not commit %08lx bytes at %p for heap %p\n",
481 size
, ptr
, subheap
->heap
);
484 subheap
->commitSize
+= size
;
489 /***********************************************************************
492 * If possible, decommit the heap storage from (including) 'ptr'.
494 static inline BOOL
HEAP_Decommit( SUBHEAP
*subheap
, void *ptr
)
497 SIZE_T decommit_size
;
498 SIZE_T size
= (char *)ptr
- (char *)subheap
;
500 /* round to next block and add one full block */
501 size
= ((size
+ COMMIT_MASK
) & ~COMMIT_MASK
) + COMMIT_MASK
+ 1;
502 if (size
>= subheap
->commitSize
) return TRUE
;
503 decommit_size
= subheap
->commitSize
- size
;
504 addr
= (char *)subheap
+ size
;
506 if (ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &decommit_size
, MEM_DECOMMIT
))
508 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
509 decommit_size
, (char *)subheap
+ size
, subheap
->heap
);
512 subheap
->commitSize
-= decommit_size
;
517 /***********************************************************************
518 * HEAP_CreateFreeBlock
520 * Create a free block at a specified address. 'size' is the size of the
521 * whole block, including the new arena.
523 static void HEAP_CreateFreeBlock( SUBHEAP
*subheap
, void *ptr
, SIZE_T size
)
529 /* Create a free arena */
530 mark_block_uninitialized( ptr
, sizeof( ARENA_FREE
) );
531 pFree
= (ARENA_FREE
*)ptr
;
532 pFree
->magic
= ARENA_FREE_MAGIC
;
534 /* If debugging, erase the freed block content */
536 pEnd
= (char *)ptr
+ size
;
537 if (pEnd
> (char *)subheap
+ subheap
->commitSize
) pEnd
= (char *)subheap
+ subheap
->commitSize
;
538 if (pEnd
> (char *)(pFree
+ 1)) mark_block_free( pFree
+ 1, pEnd
- (char *)(pFree
+ 1) );
540 /* Check if next block is free also */
542 if (((char *)ptr
+ size
< (char *)subheap
+ subheap
->size
) &&
543 (*(DWORD
*)((char *)ptr
+ size
) & ARENA_FLAG_FREE
))
545 /* Remove the next arena from the free list */
546 ARENA_FREE
*pNext
= (ARENA_FREE
*)((char *)ptr
+ size
);
547 list_remove( &pNext
->entry
);
548 size
+= (pNext
->size
& ARENA_SIZE_MASK
) + sizeof(*pNext
);
549 mark_block_free( pNext
, sizeof(ARENA_FREE
) );
552 /* Set the next block PREV_FREE flag and pointer */
554 last
= ((char *)ptr
+ size
>= (char *)subheap
+ subheap
->size
);
557 DWORD
*pNext
= (DWORD
*)((char *)ptr
+ size
);
558 *pNext
|= ARENA_FLAG_PREV_FREE
;
559 mark_block_initialized( pNext
- 1, sizeof( ARENA_FREE
* ) );
560 *((ARENA_FREE
**)pNext
- 1) = pFree
;
563 /* Last, insert the new block into the free list */
565 pFree
->size
= size
- sizeof(*pFree
);
566 HEAP_InsertFreeBlock( subheap
->heap
, pFree
, last
);
570 /***********************************************************************
571 * HEAP_MakeInUseBlockFree
573 * Turn an in-use block into a free block. Can also decommit the end of
574 * the heap, and possibly even free the sub-heap altogether.
576 static void HEAP_MakeInUseBlockFree( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
)
579 SIZE_T size
= (pArena
->size
& ARENA_SIZE_MASK
) + sizeof(*pArena
);
580 PHEAP_USER_DATA udata
;
582 /* Find and free user data */
583 if (pArena
->has_user_data
)
585 udata
= HEAP_GetUserData(subheap
->heap
, pArena
+ 1);
588 RemoveEntryList(&udata
->ListEntry
);
589 RtlFreeHeap(subheap
->heap
, 0, udata
);
593 /* Check if we can merge with previous block */
595 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
597 pFree
= *((ARENA_FREE
**)pArena
- 1);
598 size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
599 /* Remove it from the free list */
600 list_remove( &pFree
->entry
);
602 else pFree
= (ARENA_FREE
*)pArena
;
604 /* Create a free block */
606 HEAP_CreateFreeBlock( subheap
, pFree
, size
);
607 size
= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
608 if ((char *)pFree
+ size
< (char *)subheap
+ subheap
->size
)
609 return; /* Not the last block, so nothing more to do */
611 /* Free the whole sub-heap if it's empty and not the original one */
613 if (((char *)pFree
== (char *)subheap
+ subheap
->headerSize
) &&
614 (subheap
!= &subheap
->heap
->subheap
))
617 SUBHEAP
*pPrev
= &subheap
->heap
->subheap
;
618 /* Remove the free block from the list */
619 list_remove( &pFree
->entry
);
620 /* Remove the subheap from the list */
621 while (pPrev
&& (pPrev
->next
!= subheap
)) pPrev
= pPrev
->next
;
622 if (pPrev
) pPrev
->next
= subheap
->next
;
623 /* Free the memory */
625 ZwFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap
, &size
, MEM_RELEASE
);
629 /* Decommit the end of the heap */
632 /***********************************************************************
635 * Shrink an in-use block.
637 static void HEAP_ShrinkBlock(SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T size
)
639 if ((pArena
->size
& ARENA_SIZE_MASK
) >= size
+ HEAP_MIN_SHRINK_SIZE
)
641 HEAP_CreateFreeBlock( subheap
, (char *)(pArena
+ 1) + size
,
642 (pArena
->size
& ARENA_SIZE_MASK
) - size
);
643 /* assign size plus previous arena flags */
644 pArena
->size
= size
| (pArena
->size
& ~ARENA_SIZE_MASK
);
648 /* Turn off PREV_FREE flag in next block */
649 char *pNext
= (char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
);
650 if (pNext
< (char *)subheap
+ subheap
->size
)
651 *(DWORD
*)pNext
&= ~ARENA_FLAG_PREV_FREE
;
655 /***********************************************************************
658 static BOOL
HEAP_InitSubHeap( HEAP
*heap
, LPVOID address
, DWORD flags
,
659 SIZE_T commitSize
, SIZE_T totalSize
,
660 PRTL_HEAP_PARAMETERS Parameters
)
663 FREE_LIST_ENTRY
*pEntry
;
667 if (!address
&& ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0,
668 &commitSize
, MEM_COMMIT
, get_protection_type(flags
) ))
670 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize
, address
);
674 /* Fill the sub-heap structure */
676 subheap
= (SUBHEAP
*)address
;
677 subheap
->heap
= heap
;
678 subheap
->size
= totalSize
;
679 subheap
->commitSize
= commitSize
;
680 subheap
->magic
= SUBHEAP_MAGIC
;
682 if ( subheap
!= (SUBHEAP
*)heap
)
684 /* If this is a secondary subheap, insert it into list */
686 subheap
->headerSize
= ROUND_SIZE( sizeof(SUBHEAP
) );
687 subheap
->next
= heap
->subheap
.next
;
688 heap
->subheap
.next
= subheap
;
692 /* If this is a primary subheap, initialize main heap */
694 subheap
->headerSize
= ROUND_SIZE( sizeof(HEAP
) );
695 subheap
->next
= NULL
;
697 heap
->magic
= HEAP_MAGIC
;
699 heap
->commitRoutine
= Parameters
->CommitRoutine
;
701 heap
->commitRoutine
= NULL
;
702 InitializeListHead(&heap
->UserDataHead
);
704 /* Build the free lists */
706 list_init( &heap
->freeList
[0].arena
.entry
);
707 for (i
= 0, pEntry
= heap
->freeList
; i
< HEAP_NB_FREE_LISTS
; i
++, pEntry
++)
709 pEntry
->arena
.size
= 0 | ARENA_FLAG_FREE
;
710 pEntry
->arena
.magic
= ARENA_FREE_MAGIC
;
711 if (i
) list_add_after( &pEntry
[-1].arena
.entry
, &pEntry
->arena
.entry
);
714 /* Initialize critical section */
716 if (RtlpGetMode() == UserMode
)
718 if (!processHeap
) /* do it by hand to avoid memory allocations */
720 heap
->critSection
.DebugInfo
= &process_heap_critsect_debug
;
721 heap
->critSection
.LockCount
= -1;
722 heap
->critSection
.RecursionCount
= 0;
723 heap
->critSection
.OwningThread
= 0;
724 heap
->critSection
.LockSemaphore
= 0;
725 heap
->critSection
.SpinCount
= 0;
726 process_heap_critsect_debug
.CriticalSection
= &heap
->critSection
;
728 else RtlInitializeHeapLock( &heap
->critSection
);
733 if (heap
->commitRoutine
)
735 if (subheap
!= (SUBHEAP
*)heap
)
737 Status
= heap
->commitRoutine(heap
, &address
, &commitSize
);
741 /* the caller is responsible for committing the first page! */
742 Status
= STATUS_SUCCESS
;
747 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
752 get_protection_type(flags
));
754 if (!NT_SUCCESS(Status
))
756 DPRINT("Could not commit %08lx bytes for sub-heap %p\n",
757 commitSize
, address
);
761 /* Create the first free block */
763 HEAP_CreateFreeBlock( subheap
, (LPBYTE
)subheap
+ subheap
->headerSize
,
764 subheap
->size
- subheap
->headerSize
);
769 /***********************************************************************
772 * Create a sub-heap of the given size.
773 * If heap == NULL, creates a main heap.
775 static SUBHEAP
*HEAP_CreateSubHeap( HEAP
*heap
, void *base
, DWORD flags
,
776 SIZE_T commitSize
, SIZE_T totalSize
,
777 IN PRTL_HEAP_PARAMETERS Parameters
)
779 LPVOID address
= base
;
781 /* round-up sizes on a 64K boundary */
782 totalSize
= (totalSize
+ 0xffff) & 0xffff0000;
783 commitSize
= (commitSize
+ 0xffff) & 0xffff0000;
784 if (!commitSize
) commitSize
= 0x10000;
785 totalSize
= min( totalSize
, 0xffff0000 ); /* don't allow a heap larger than 4Gb */
786 if (totalSize
< commitSize
) totalSize
= commitSize
;
790 /* allocate the memory block */
791 if (ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0, &totalSize
,
792 MEM_RESERVE
| MEM_COMMIT
, get_protection_type(flags
) ))
794 WARN("Could not allocate %08lx bytes\n", totalSize
);
799 /* Initialize subheap */
801 if (!HEAP_InitSubHeap( heap
? heap
: (HEAP
*)address
,
802 address
, flags
, commitSize
, totalSize
, Parameters
))
805 if (!base
) ZwFreeVirtualMemory( NtCurrentProcess(), &address
, &size
, MEM_RELEASE
);
809 return (SUBHEAP
*)address
;
813 /***********************************************************************
816 * Find a free block at least as large as the requested size, and make sure
817 * the requested size is committed.
819 static ARENA_FREE
*HEAP_FindFreeBlock( HEAP
*heap
, SIZE_T size
,
820 SUBHEAP
**ppSubHeap
)
825 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( size
+ sizeof(ARENA_INUSE
) );
827 /* Find a suitable free list, and in it find a block large enough */
829 ptr
= &pEntry
->arena
.entry
;
830 while ((ptr
= list_next( &heap
->freeList
[0].arena
.entry
, ptr
)))
832 ARENA_FREE
*pArena
= LIST_ENTRY( ptr
, ARENA_FREE
, entry
);
833 SIZE_T arena_size
= (pArena
->size
& ARENA_SIZE_MASK
) +
834 sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
835 if (arena_size
>= size
)
837 subheap
= HEAP_FindSubHeap( heap
, pArena
);
838 if (!HEAP_Commit( subheap
, (ARENA_INUSE
*)pArena
, size
)) return NULL
;
839 *ppSubHeap
= subheap
;
844 /* If no block was found, attempt to grow the heap */
846 if (!(heap
->flags
& HEAP_GROWABLE
))
848 ERR("Not enough space in heap %p for %08lx bytes\n", heap
, size
);
851 /* make sure that we have a big enough size *committed* to fit another
852 * last free arena in !
853 * So just one heap struct, one first free arena which will eventually
854 * get used, and a second free arena that might get assigned all remaining
855 * free space in HEAP_ShrinkBlock() */
856 total_size
= size
+ ROUND_SIZE(sizeof(SUBHEAP
)) + sizeof(ARENA_INUSE
) + sizeof(ARENA_FREE
);
857 if (total_size
< size
) return NULL
; /* overflow */
859 if (!(subheap
= HEAP_CreateSubHeap( heap
, NULL
, heap
->flags
, total_size
,
860 max( HEAP_DEF_SIZE
, total_size
), NULL
)))
863 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
864 subheap
, size
, heap
);
866 *ppSubHeap
= subheap
;
867 return (ARENA_FREE
*)(subheap
+ 1);
870 /***********************************************************************
871 * HEAP_IsValidArenaPtr
873 * Check that the pointer is inside the range possible for arenas.
875 static BOOL
HEAP_IsValidArenaPtr( const HEAP
*heap
, const void *ptr
)
878 const SUBHEAP
*subheap
= HEAP_FindSubHeap( heap
, ptr
);
879 if (!subheap
) return FALSE
;
880 if ((const char *)ptr
>= (const char *)subheap
+ subheap
->headerSize
) return TRUE
;
881 if (subheap
!= &heap
->subheap
) return FALSE
;
882 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
883 if (ptr
== (const void *)&heap
->freeList
[i
].arena
) return TRUE
;
888 /***********************************************************************
889 * HEAP_ValidateFreeArena
891 static BOOL
HEAP_ValidateFreeArena( SUBHEAP
*subheap
, ARENA_FREE
*pArena
)
893 ARENA_FREE
*prev
, *next
;
894 char *heapEnd
= (char *)subheap
+ subheap
->size
;
896 /* Check for unaligned pointers */
897 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= ARENA_OFFSET
)
899 ERR("Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
903 /* Check magic number */
904 if (pArena
->magic
!= ARENA_FREE_MAGIC
)
906 ERR("Heap %p: invalid free arena magic for %p\n", subheap
->heap
, pArena
);
909 /* Check size flags */
910 if (!(pArena
->size
& ARENA_FLAG_FREE
) ||
911 (pArena
->size
& ARENA_FLAG_PREV_FREE
))
913 ERR("Heap %p: bad flags %08lx for free arena %p\n",
914 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
917 /* Check arena size */
918 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
920 ERR("Heap %p: bad size %08lx for free arena %p\n",
921 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
924 /* Check that next pointer is valid */
925 next
= LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
);
926 if (!HEAP_IsValidArenaPtr( subheap
->heap
, next
))
928 ERR("Heap %p: bad next ptr %p for arena %p\n",
929 subheap
->heap
, next
, pArena
);
932 /* Check that next arena is free */
933 if (!(next
->size
& ARENA_FLAG_FREE
) || (next
->magic
!= ARENA_FREE_MAGIC
))
935 ERR("Heap %p: next arena %p invalid for %p\n",
936 subheap
->heap
, next
, pArena
);
939 /* Check that prev pointer is valid */
940 prev
= LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
);
941 if (!HEAP_IsValidArenaPtr( subheap
->heap
, prev
))
943 ERR("Heap %p: bad prev ptr %p for arena %p\n",
944 subheap
->heap
, prev
, pArena
);
947 /* Check that prev arena is free */
948 if (!(prev
->size
& ARENA_FLAG_FREE
) || (prev
->magic
!= ARENA_FREE_MAGIC
))
950 /* this often means that the prev arena got overwritten
951 * by a memory write before that prev arena */
952 ERR("Heap %p: prev arena %p invalid for %p\n",
953 subheap
->heap
, prev
, pArena
);
956 /* Check that next block has PREV_FREE flag */
957 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
)
959 if (!(*(DWORD
*)((char *)(pArena
+ 1) +
960 (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
962 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
963 subheap
->heap
, pArena
);
966 /* Check next block back pointer */
967 if (*((ARENA_FREE
**)((char *)(pArena
+ 1) +
968 (pArena
->size
& ARENA_SIZE_MASK
)) - 1) != pArena
)
970 ERR("Heap %p: arena %p has wrong back ptr %p\n",
971 subheap
->heap
, pArena
,
972 *((ARENA_FREE
**)((char *)(pArena
+1) + (pArena
->size
& ARENA_SIZE_MASK
)) - 1));
979 /***********************************************************************
980 * HEAP_ValidateInUseArena
982 static BOOL
HEAP_ValidateInUseArena( const SUBHEAP
*subheap
, const ARENA_INUSE
*pArena
, BOOL quiet
)
984 const char *heapEnd
= (const char *)subheap
+ subheap
->size
;
986 /* Check for unaligned pointers */
987 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= ARENA_OFFSET
)
989 if ( quiet
== NOISY
)
991 ERR( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
992 if ( TRACE_ON(heap
) )
993 HEAP_Dump( subheap
->heap
);
995 else if ( WARN_ON(heap
) )
997 WARN( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
998 if ( TRACE_ON(heap
) )
999 HEAP_Dump( subheap
->heap
);
1004 /* Check magic number */
1005 if (pArena
->magic
!= ARENA_INUSE_MAGIC
)
1007 if (quiet
== NOISY
) {
1008 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
1010 HEAP_Dump( subheap
->heap
);
1011 } else if (WARN_ON(heap
)) {
1012 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
1014 HEAP_Dump( subheap
->heap
);
1018 /* Check size flags */
1019 if (pArena
->size
& ARENA_FLAG_FREE
)
1021 ERR("Heap %p: bad flags %08lx for in-use arena %p\n",
1022 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
1025 /* Check arena size */
1026 if ((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
1028 ERR("Heap %p: bad size %08lx for in-use arena %p\n",
1029 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
1032 /* Check next arena PREV_FREE flag */
1033 if (((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
) &&
1034 (*(const DWORD
*)((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
1036 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
1037 subheap
->heap
, pArena
);
1040 /* Check prev free arena */
1041 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
1043 const ARENA_FREE
*pPrev
= *((const ARENA_FREE
* const*)pArena
- 1);
1044 /* Check prev pointer */
1045 if (!HEAP_IsValidArenaPtr( subheap
->heap
, pPrev
))
1047 ERR("Heap %p: bad back ptr %p for arena %p\n",
1048 subheap
->heap
, pPrev
, pArena
);
1051 /* Check that prev arena is free */
1052 if (!(pPrev
->size
& ARENA_FLAG_FREE
) ||
1053 (pPrev
->magic
!= ARENA_FREE_MAGIC
))
1055 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1056 subheap
->heap
, pPrev
, pArena
);
1059 /* Check that prev arena is really the previous block */
1060 if ((const char *)(pPrev
+ 1) + (pPrev
->size
& ARENA_SIZE_MASK
) != (const char *)pArena
)
1062 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1063 subheap
->heap
, pPrev
, pArena
);
1070 /***********************************************************************
1071 * HEAP_IsRealArena [Internal]
1072 * Validates a block is a valid arena.
1078 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, /* [in] ptr to the heap */
1079 DWORD flags
, /* [in] Bit flags that control access during operation */
1080 LPCVOID block
, /* [in] Optional pointer to memory block to validate */
1081 BOOL quiet
) /* [in] Flag - if true, HEAP_ValidateInUseArena
1082 * does not complain */
1087 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
1089 ERR("Invalid heap %p!\n", heapPtr
);
1093 flags
&= HEAP_NO_SERIALIZE
;
1094 flags
|= heapPtr
->flags
;
1095 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1096 if (!(flags
& HEAP_NO_SERIALIZE
))
1097 RtlEnterHeapLock( &heapPtr
->critSection
);
1101 /* Only check this single memory block */
1103 if (!(subheap
= HEAP_FindSubHeap( heapPtr
, block
)) ||
1104 ((const char *)block
< (char *)subheap
+ subheap
->headerSize
1105 + sizeof(ARENA_INUSE
)))
1108 ERR("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1109 else if (WARN_ON(heap
))
1110 WARN("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1113 ret
= HEAP_ValidateInUseArena( subheap
, (const ARENA_INUSE
*)block
- 1, quiet
);
1115 if (!(flags
& HEAP_NO_SERIALIZE
))
1116 RtlLeaveHeapLock( &heapPtr
->critSection
);
1120 subheap
= &heapPtr
->subheap
;
1121 while (subheap
&& ret
)
1123 char *ptr
= (char *)subheap
+ subheap
->headerSize
;
1124 while (ptr
< (char *)subheap
+ subheap
->size
)
1126 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
1128 if (!HEAP_ValidateFreeArena( subheap
, (ARENA_FREE
*)ptr
)) {
1132 ptr
+= sizeof(ARENA_FREE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1136 if (!HEAP_ValidateInUseArena( subheap
, (ARENA_INUSE
*)ptr
, NOISY
)) {
1140 ptr
+= sizeof(ARENA_INUSE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1143 subheap
= subheap
->next
;
1146 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1151 /***********************************************************************
1152 * HeapCreate (KERNEL32.336)
1154 * Handle of heap: Success
1160 RtlCreateHeap(ULONG flags
,
1165 PRTL_HEAP_PARAMETERS Parameters
)
1169 /* Allocate the heap block */
1173 totalSize
= HEAP_DEF_SIZE
;
1174 flags
|= HEAP_GROWABLE
;
1176 if (!(subheap
= HEAP_CreateSubHeap( NULL
, addr
, flags
, commitSize
, totalSize
, Parameters
))) return 0;
1178 if (RtlpGetMode() == UserMode
)
1180 /* link it into the per-process heap list */
1183 HEAP
*heapPtr
= subheap
->heap
;
1184 RtlEnterHeapLock( &processHeap
->critSection
);
1185 list_add_head( &processHeap
->entry
, &heapPtr
->entry
);
1186 RtlLeaveHeapLock( &processHeap
->critSection
);
1190 processHeap
= subheap
->heap
; /* assume the first heap we create is the process main heap */
1191 list_init( &processHeap
->entry
);
1192 assert( (ULONG_PTR
)processHeap
->freeList
% ALIGNMENT
== ARENA_OFFSET
);
1196 return (HANDLE
)subheap
;
1199 /***********************************************************************
1200 * HeapDestroy (KERNEL32.337)
1208 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1209 * Failure: The Heap handle, if heap is the process heap.
1212 RtlDestroyHeap(HANDLE heap
) /* [in] Handle of heap */
1214 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1217 DPRINT("%p\n", heap
);
1221 if (RtlpGetMode() == UserMode
)
1223 if (heap
== NtCurrentPeb()->ProcessHeap
)
1224 return heap
; /* cannot delete the main process heap */
1226 /* remove it from the per-process list */
1227 RtlEnterHeapLock( &processHeap
->critSection
);
1228 list_remove( &heapPtr
->entry
);
1229 RtlLeaveHeapLock( &processHeap
->critSection
);
1232 RtlDeleteHeapLock( &heapPtr
->critSection
);
1233 subheap
= &heapPtr
->subheap
;
1236 SUBHEAP
*next
= subheap
->next
;
1238 void *addr
= subheap
;
1239 ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &size
, MEM_RELEASE
);
1242 return (HANDLE
)NULL
;
1246 /***********************************************************************
1247 * HeapAlloc (KERNEL32.334)
1249 * Pointer to allocated memory block
1251 * 0x7d030f60--invalid flags in RtlHeapAllocate
1255 RtlAllocateHeap(HANDLE heap
, /* [in] Handle of private heap block */
1256 ULONG flags
, /* [in] Heap allocation control flags */
1257 SIZE_T size
) /* [in] Number of bytes to allocate */
1260 ARENA_INUSE
*pInUse
;
1262 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1263 SIZE_T rounded_size
;
1265 /* Validate the parameters */
1269 if (flags
& HEAP_GENERATE_EXCEPTIONS
)
1270 RtlRaiseStatus( STATUS_NO_MEMORY
);
1273 //flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1274 flags
|= heapPtr
->flags
;
1275 rounded_size
= ROUND_SIZE(size
);
1276 if (rounded_size
< size
) /* overflow */
1278 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1282 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1284 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1285 /* Locate a suitable free block */
1286 if (!(pArena
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &subheap
)))
1288 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1289 heap
, flags
, size
);
1290 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1291 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1295 /* Remove the arena from the free list */
1297 list_remove( &pArena
->entry
);
1299 /* Build the in-use arena */
1301 pInUse
= (ARENA_INUSE
*)pArena
;
1303 /* in-use arena is smaller than free arena,
1304 * so we have to add the difference to the size */
1305 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
) + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1306 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1307 pInUse
->has_user_data
= 0;
1309 /* Shrink the block */
1311 HEAP_ShrinkBlock( subheap
, pInUse
, rounded_size
);
1312 pInUse
->unused_bytes
= (pInUse
->size
& ARENA_SIZE_MASK
) - size
;
1314 if (flags
& HEAP_ZERO_MEMORY
)
1316 clear_block( pInUse
+ 1, size
);
1317 mark_block_uninitialized( (char *)(pInUse
+ 1) + size
, pInUse
->unused_bytes
);
1320 mark_block_uninitialized( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1322 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1324 TRACE("(%p,%08lx,%08lx): returning %p\n", heap
, flags
, size
, pInUse
+ 1 );
1325 return (LPVOID
)(pInUse
+ 1);
1329 /***********************************************************************
1330 * HeapFree (KERNEL32.338)
1337 BOOLEAN NTAPI
RtlFreeHeap(
1338 HANDLE heap
, /* [in] Handle of heap */
1339 ULONG flags
, /* [in] Heap freeing flags */
1340 PVOID ptr
/* [in] Address of memory to free */
1343 ARENA_INUSE
*pInUse
;
1347 /* Validate the parameters */
1349 if (!ptr
) return TRUE
; /* freeing a NULL ptr isn't an error in Win2k */
1351 heapPtr
= HEAP_GetPtr( heap
);
1354 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1358 flags
&= HEAP_NO_SERIALIZE
;
1359 flags
|= heapPtr
->flags
;
1360 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1361 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1363 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1364 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1365 TRACE("(%p,%08lx,%p): returning FALSE\n", heap
, flags
, ptr
);
1369 /* Some sanity checks */
1370 pInUse
= (ARENA_INUSE
*)ptr
- 1;
1371 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1372 if ((char *)pInUse
< (char *)subheap
+ subheap
->headerSize
) goto error
;
1373 if (!HEAP_ValidateInUseArena( subheap
, pInUse
, QUIET
)) goto error
;
1375 /* Turn the block into a free block */
1377 HEAP_MakeInUseBlockFree( subheap
, pInUse
);
1379 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1381 TRACE("(%p,%08lx,%p): returning TRUE\n", heap
, flags
, ptr
);
1385 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1386 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1387 TRACE("(%p,%08x,%p): returning FALSE\n", heap
, flags
, ptr
);
1392 /***********************************************************************
1395 * Heap [in] Handle of heap block
1396 * Flags [in] Heap reallocation flags
1397 * Ptr, [in] Address of memory to reallocate
1398 * Size [in] Number of bytes to reallocate
1401 * Pointer to reallocated memory block
1403 * 0x7d030f60--invalid flags in RtlHeapAllocate
1406 PVOID NTAPI
RtlReAllocateHeap(
1413 ARENA_INUSE
*pArena
;
1416 SIZE_T oldBlockSize
, oldActualSize
, rounded_size
;
1418 if (!ptr
) return NULL
;
1419 if (!(heapPtr
= HEAP_GetPtr( heap
)))
1421 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1425 /* Validate the parameters */
1427 //Flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1428 // HEAP_REALLOC_IN_PLACE_ONLY;
1429 flags
|= heapPtr
->flags
;
1430 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1432 rounded_size
= ROUND_SIZE(size
);
1433 if (rounded_size
< size
) goto oom
; /* overflow */
1434 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1436 pArena
= (ARENA_INUSE
*)ptr
- 1;
1437 if(!(subheap
= HEAP_FindSubHeap( heapPtr
, pArena
))) goto done
;
1438 if ((char *)pArena
< (char *)subheap
+ subheap
->headerSize
) goto error
;
1439 if (!HEAP_ValidateInUseArena( subheap
, pArena
, QUIET
)) goto error
;
1441 oldBlockSize
= (pArena
->size
& ARENA_SIZE_MASK
);
1442 oldActualSize
= (pArena
->size
& ARENA_SIZE_MASK
) - pArena
->unused_bytes
;
1444 if (rounded_size
> oldBlockSize
)
1446 char *pNext
= (char *)(pArena
+ 1) + oldBlockSize
;
1447 if ((pNext
< (char *)subheap
+ subheap
->size
) &&
1448 (*(DWORD
*)pNext
& ARENA_FLAG_FREE
) &&
1449 (oldBlockSize
+ (*(DWORD
*)pNext
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
) >= rounded_size
))
1451 ARENA_FREE
*pFree
= (ARENA_FREE
*)pNext
;
1452 list_remove( &pFree
->entry
);
1453 pArena
->size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(*pFree
);
1455 if (!HEAP_Commit( subheap
, pArena
, rounded_size
)) goto oom
;
1457 HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
);
1458 mark_block_initialized( pArena
+ 1, oldActualSize
);
1460 else /* Do it the hard way */
1463 ARENA_INUSE
*pInUse
;
1464 SUBHEAP
*newsubheap
;
1465 if ((flags
& HEAP_REALLOC_IN_PLACE_ONLY
) ||
1466 !(pNew
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &newsubheap
)))
1469 /* Build the in-use arena */
1471 list_remove( &pNew
->entry
);
1472 pInUse
= (ARENA_INUSE
*)pNew
;
1473 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
)
1474 + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1475 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1476 HEAP_ShrinkBlock( newsubheap
, pInUse
, rounded_size
);
1478 mark_block_initialized( pInUse
+ 1, oldActualSize
);
1479 memcpy( pInUse
+ 1, pArena
+ 1, oldActualSize
);
1481 /* Free the previous block */
1483 HEAP_MakeInUseBlockFree( subheap
, pArena
);
1484 subheap
= newsubheap
;
1490 HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
); /* Shrink the block */
1491 mark_block_initialized( pArena
+ 1, size
);
1494 pArena
->unused_bytes
= (pArena
->size
& ARENA_SIZE_MASK
) - size
;
1496 /* Clear the extra bytes if needed */
1498 if (size
> oldActualSize
)
1500 if (flags
& HEAP_ZERO_MEMORY
)
1502 clear_block( (char *)(pArena
+ 1) + oldActualSize
, size
- oldActualSize
);
1503 mark_block_uninitialized( (char *)(pArena
+ 1) + size
,
1504 (pArena
->size
& ARENA_SIZE_MASK
) - oldActualSize
);
1507 mark_block_uninitialized( (char *)(pArena
+ 1) + oldActualSize
,
1508 (pArena
->size
& ARENA_SIZE_MASK
) - oldActualSize
);
1511 /* Return the new arena */
1513 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1514 TRACE("(%p,%08lx,%p,%08lx): returning %p\n", heap
, flags
, ptr
, size
, pArena
+ 1 );
1515 return (LPVOID
)(pArena
+ 1);
1518 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1519 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1520 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1521 TRACE("(%p,%08x,%p,%08lx): returning oom\n", heap
, flags
, ptr
, size
);
1525 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1526 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1527 TRACE("(%p,%08x,%p,%08lx): returning error\n", heap
, flags
, ptr
, size
);
1532 /***********************************************************************
1538 RtlCompactHeap(HANDLE Heap
,
1546 /***********************************************************************
1548 * Attempts to acquire the critical section object for a specified heap.
1551 * Heap [in] Handle of heap to lock for exclusive access
1560 RtlLockHeap(IN HANDLE Heap
)
1562 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1565 RtlEnterHeapLock( &heapPtr
->critSection
);
1570 /***********************************************************************
1572 * Releases ownership of the critical section object.
1575 * Heap [in] Handle to the heap to unlock
1584 RtlUnlockHeap(HANDLE Heap
)
1586 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1589 RtlLeaveHeapLock( &heapPtr
->critSection
);
1594 /***********************************************************************
1597 * Heap [in] Handle of heap
1598 * Flags [in] Heap size control flags
1599 * Ptr [in] Address of memory to return size for
1602 * Size in bytes of allocated memory
1603 * 0xffffffff: Failure
1615 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1619 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1622 flags
&= HEAP_NO_SERIALIZE
;
1623 flags
|= heapPtr
->flags
;
1624 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1625 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1627 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1632 const ARENA_INUSE
*pArena
= (const ARENA_INUSE
*)ptr
- 1;
1633 ret
= (pArena
->size
& ARENA_SIZE_MASK
) - pArena
->unused_bytes
;
1635 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1637 TRACE("(%p,%08lx,%p): returning %08lx\n", heap
, flags
, ptr
, ret
);
1642 /***********************************************************************
1644 * Validates a specified heap.
1647 * Heap [in] Handle to the heap
1648 * Flags [in] Bit flags that control access during operation
1649 * Block [in] Optional pointer to memory block to validate
1660 BOOLEAN NTAPI
RtlValidateHeap(
1666 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1669 return HEAP_IsRealArena( heapPtr
, Flags
, Block
, QUIET
);
1673 RtlInitializeHeapManager(VOID
)
1677 Peb
= NtCurrentPeb();
1679 Peb
->NumberOfHeaps
= 0;
1680 Peb
->MaximumNumberOfHeaps
= -1; /* no limit */
1681 Peb
->ProcessHeaps
= NULL
;
1683 //RtlInitializeHeapLock(&RtlpProcessHeapsListLock);
1691 RtlEnumProcessHeaps(PHEAP_ENUMERATION_ROUTINE HeapEnumerationRoutine
,
1694 NTSTATUS Status
= STATUS_SUCCESS
;
1696 struct list
*ptr
=NULL
;
1697 RtlEnterHeapLock(&processHeap
->critSection
);
1698 Status
=HeapEnumerationRoutine(processHeap
,lParam
);
1700 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1702 if (!NT_SUCCESS(Status
)) break;
1703 Status
= HeapEnumerationRoutine(ptr
,lParam
);
1706 RtlLeaveHeapLock(&processHeap
->critSection
);
1716 RtlGetProcessHeaps(ULONG count
,
1719 ULONG total
= 1; /* main heap */
1722 RtlEnterHeapLock( &processHeap
->critSection
);
1723 LIST_FOR_EACH( ptr
, &processHeap
->entry
) total
++;
1724 //if (total <= count)
1726 *(heaps
++) = processHeap
;
1728 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1730 if (i
>= count
) break;
1732 *(heaps
++) = LIST_ENTRY( ptr
, HEAP
, entry
);
1735 RtlLeaveHeapLock( &processHeap
->critSection
);
1744 RtlValidateProcessHeaps(VOID
)
1746 BOOLEAN Result
= TRUE
;
1749 RtlEnterHeapLock( &processHeap
->critSection
);
1751 for (pptr
= (HEAP
**)&NtCurrentPeb()->ProcessHeaps
; *pptr
; pptr
++)
1753 if (!RtlValidateHeap(*pptr
, 0, NULL
))
1760 RtlLeaveHeapLock( &processHeap
->critSection
);
1770 IN PVOID HeapHandle
,
1783 RtlSetUserValueHeap(IN PVOID HeapHandle
,
1785 IN PVOID BaseAddress
,
1789 PHEAP_USER_DATA udata
;
1791 heapPtr
= HEAP_GetPtr(HeapHandle
);
1794 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1797 udata
= HEAP_GetUserData(heapPtr
, BaseAddress
);
1800 udata
= HEAP_AllocUserData(heapPtr
, BaseAddress
);
1801 if (!udata
) return FALSE
;
1803 udata
->UserValue
= UserValue
;
1812 RtlSetUserFlagsHeap(IN PVOID HeapHandle
,
1814 IN PVOID BaseAddress
,
1818 PHEAP_USER_DATA udata
;
1820 heapPtr
= HEAP_GetPtr(HeapHandle
);
1823 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1826 udata
= HEAP_GetUserData(heapPtr
, BaseAddress
);
1829 udata
= HEAP_AllocUserData(heapPtr
, BaseAddress
);
1830 if (!udata
) return FALSE
;
1832 udata
->UserFlags
= UserFlags
& HEAP_SETTABLE_USER_FLAGS
;
1841 RtlGetUserInfoHeap(IN PVOID HeapHandle
,
1843 IN PVOID BaseAddress
,
1844 OUT PVOID
*UserValue
,
1845 OUT PULONG UserFlags
)
1848 PHEAP_USER_DATA udata
;
1850 heapPtr
= HEAP_GetPtr(HeapHandle
);
1853 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1856 udata
= HEAP_GetUserData(heapPtr
, BaseAddress
);
1859 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1862 if (UserValue
) *UserValue
= udata
->UserValue
;
1863 if (UserFlags
) *UserFlags
= udata
->UserFlags
;
1872 RtlUsageHeap(IN HANDLE Heap
,
1874 OUT PRTL_HEAP_USAGE Usage
)
1878 return STATUS_NOT_IMPLEMENTED
;
1883 RtlQueryTagHeap(IN PVOID HeapHandle
,
1886 IN BOOLEAN ResetCounters
,
1887 OUT PRTL_HEAP_TAG_INFO HeapTagInfo
)
1896 RtlExtendHeap(IN HANDLE Heap
,
1908 RtlCreateTagHeap(IN HANDLE HeapHandle
,
1911 IN PWSTR TagSubName
)
1920 RtlWalkHeap(IN HANDLE HeapHandle
,
1924 return STATUS_NOT_IMPLEMENTED
;
1929 RtlProtectHeap(IN PVOID HeapHandle
,
1930 IN BOOLEAN ReadOnly
)
1938 RtlSetHeapInformation(IN HANDLE HeapHandle OPTIONAL
,
1939 IN HEAP_INFORMATION_CLASS HeapInformationClass
,
1940 IN PVOID HeapInformation
,
1941 IN SIZE_T HeapInformationLength
)
1949 RtlQueryHeapInformation(HANDLE HeapHandle
,
1950 HEAP_INFORMATION_CLASS HeapInformationClass
,
1951 PVOID HeapInformation OPTIONAL
,
1952 SIZE_T HeapInformationLength OPTIONAL
,
1953 PSIZE_T ReturnLength OPTIONAL
)
1957 heapPtr
= HEAP_GetPtr(HeapHandle
);
1960 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1966 switch (HeapInformationClass
)
1968 case HeapCompatibilityInformation
:
1969 if (ReturnLength
) *ReturnLength
= sizeof(ULONG
);
1971 if (HeapInformationLength
< sizeof(ULONG
))
1972 return STATUS_BUFFER_TOO_SMALL
;
1974 *(ULONG
*)HeapInformation
= 0; /* standard heap */
1975 return STATUS_SUCCESS
;
1977 return STATUS_INVALID_INFO_CLASS
;
1983 RtlMultipleAllocateHeap(IN PVOID HeapHandle
,
1995 RtlMultipleFreeHeap(IN PVOID HeapHandle
,