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_SIZE_MASK (~3)
87 #define ARENA_INUSE_MAGIC 0x455355 /* Value for arena 'magic' field */
88 #define ARENA_FREE_MAGIC 0x45455246 /* Value for arena 'magic' field */
90 #define ARENA_INUSE_FILLER 0x55
91 #define ARENA_FREE_FILLER 0xaa
93 /* everything is aligned on 8 byte boundaries (16 for Win64)*/
94 #define ALIGNMENT (2*sizeof(void*))
95 #define ARENA_OFFSET (ALIGNMENT - sizeof(ARENA_INUSE))
97 #define ROUND_SIZE(size) ((((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1)) + ARENA_OFFSET)
100 #define QUIET 1 /* Suppress messages */
101 #define NOISY 0 /* Report all errors */
103 /* minimum data size (without arenas) of an allocated block */
104 #define HEAP_MIN_DATA_SIZE ROUND_SIZE(2 * sizeof(struct list))
105 /* minimum size that must remain to shrink an allocated block */
106 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
108 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
110 /* Max size of the blocks on the free lists */
111 static const DWORD HEAP_freeListSizes
[HEAP_NB_FREE_LISTS
] =
113 0x20, 0x80, 0x200, ~0UL
124 typedef struct tagSUBHEAP
126 SIZE_T size
; /* Size of the whole sub-heap */
127 SIZE_T commitSize
; /* Committed size of the sub-heap */
128 DWORD headerSize
; /* Size of the heap header */
129 struct tagSUBHEAP
*next
; /* Next sub-heap */
130 struct tagHEAP
*heap
; /* Main heap structure */
131 DWORD magic
; /* Magic number */
134 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
136 typedef struct tagHEAP_USER_DATA
138 LIST_ENTRY ListEntry
;
142 } HEAP_USER_DATA
, *PHEAP_USER_DATA
;
144 typedef struct tagHEAP
146 SUBHEAP subheap
; /* First sub-heap */
147 struct list entry
; /* Entry in process heap list */
148 RTL_CRITICAL_SECTION critSection
; /* Critical section for serialization */
149 FREE_LIST_ENTRY freeList
[HEAP_NB_FREE_LISTS
]; /* Free lists */
150 DWORD flags
; /* Heap flags */
151 DWORD magic
; /* Magic number */
152 PRTL_HEAP_COMMIT_ROUTINE commitRoutine
;
153 LIST_ENTRY UserDataHead
;
156 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
158 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
159 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
161 static HEAP
*processHeap
; /* main process heap */
163 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, DWORD flags
, LPCVOID block
, BOOL quiet
);
165 /* mark a block of memory as free for debugging purposes */
166 static __inline
void mark_block_free( void *ptr
, SIZE_T size
)
168 if (TRACE_ON(heap
)) memset( ptr
, ARENA_FREE_FILLER
, size
);
169 #ifdef VALGRIND_MAKE_NOACCESS
170 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr
, size
));
174 /* mark a block of memory as initialized for debugging purposes */
175 static __inline
void mark_block_initialized( void *ptr
, SIZE_T size
)
177 #ifdef VALGRIND_MAKE_READABLE
178 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr
, size
));
182 /* mark a block of memory as uninitialized for debugging purposes */
183 static __inline
void mark_block_uninitialized( void *ptr
, SIZE_T size
)
185 #ifdef VALGRIND_MAKE_WRITABLE
186 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr
, size
));
190 memset( ptr
, ARENA_INUSE_FILLER
, size
);
191 #ifdef VALGRIND_MAKE_WRITABLE
192 /* make it uninitialized to valgrind again */
193 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr
, size
));
198 /* clear contents of a block of memory */
199 static __inline
void clear_block( void *ptr
, SIZE_T size
)
201 mark_block_initialized( ptr
, size
);
202 memset( ptr
, 0, size
);
205 /* locate a free list entry of the appropriate size */
206 /* size is the size of the whole block including the arena header */
207 static __inline
unsigned int get_freelist_index( SIZE_T size
)
211 size
-= sizeof(ARENA_FREE
);
212 for (i
= 0; i
< HEAP_NB_FREE_LISTS
- 1; i
++) if (size
<= HEAP_freeListSizes
[i
]) break;
216 /* get the memory protection type to use for a given heap */
217 static inline ULONG
get_protection_type( DWORD flags
)
219 return (flags
& HEAP_CREATE_ENABLE_EXECUTE
) ? PAGE_EXECUTE_READWRITE
: PAGE_READWRITE
;
222 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug
=
224 0, 0, NULL
, /* will be set later */
225 { &process_heap_critsect_debug
.ProcessLocksList
, &process_heap_critsect_debug
.ProcessLocksList
},
229 /***********************************************************************
232 static void HEAP_Dump( HEAP
*heap
)
238 DPRINTF( "Heap: %p\n", heap
);
239 DPRINTF( "Next: %p Sub-heaps: %p",
240 LIST_ENTRY( heap
->entry
.next
, HEAP
, entry
), &heap
->subheap
);
241 subheap
= &heap
->subheap
;
242 while (subheap
->next
)
244 DPRINTF( " -> %p", subheap
->next
);
245 subheap
= subheap
->next
;
248 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
249 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
250 DPRINTF( "%p free %08lx prev=%p next=%p\n",
251 &heap
->freeList
[i
].arena
, HEAP_freeListSizes
[i
],
252 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.prev
, ARENA_FREE
, entry
),
253 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.next
, ARENA_FREE
, entry
));
255 subheap
= &heap
->subheap
;
258 SIZE_T freeSize
= 0, usedSize
= 0, arenaSize
= subheap
->headerSize
;
259 DPRINTF( "\n\nSub-heap %p: size=%08lx committed=%08lx\n",
260 subheap
, subheap
->size
, subheap
->commitSize
);
262 DPRINTF( "\n Block Stat Size Id\n" );
263 ptr
= (char*)subheap
+ subheap
->headerSize
;
264 while (ptr
< (char *)subheap
+ subheap
->size
)
266 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
268 ARENA_FREE
*pArena
= (ARENA_FREE
*)ptr
;
269 DPRINTF( "%p free %08lx prev=%p next=%p\n",
270 pArena
, pArena
->size
& ARENA_SIZE_MASK
,
271 LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
),
272 LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
) );
273 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
274 arenaSize
+= sizeof(ARENA_FREE
);
275 freeSize
+= pArena
->size
& ARENA_SIZE_MASK
;
277 else if (*(DWORD
*)ptr
& ARENA_FLAG_PREV_FREE
)
279 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
280 DPRINTF( "%p Used %08lx back=%p\n",
281 pArena
, pArena
->size
& ARENA_SIZE_MASK
, *((ARENA_FREE
**)pArena
- 1) );
282 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
283 arenaSize
+= sizeof(ARENA_INUSE
);
284 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
288 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
289 DPRINTF( "%p used %08lx\n", pArena
, pArena
->size
& ARENA_SIZE_MASK
);
290 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
291 arenaSize
+= sizeof(ARENA_INUSE
);
292 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
295 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
296 subheap
->size
, subheap
->commitSize
, freeSize
, usedSize
,
297 arenaSize
, (arenaSize
* 100) / subheap
->size
);
298 subheap
= subheap
->next
;
303 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry
)
306 TRACE( "Dumping entry %p\n", entry
);
307 TRACE( "lpData\t\t: %p\n", entry
->lpData
);
308 TRACE( "cbData\t\t: %08lx\n", entry
->cbData
);
309 TRACE( "cbOverhead\t: %08x\n", entry
->cbOverhead
);
310 TRACE( "iRegionIndex\t: %08x\n", entry
->iRegionIndex
);
311 TRACE( "WFlags\t\t: ");
312 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
313 TRACE( "PROCESS_HEAP_REGION ");
314 if (entry
->wFlags
& PROCESS_HEAP_UNCOMMITTED_RANGE
)
315 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
316 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
317 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
318 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
)
319 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
320 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_DDESHARE
)
321 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
322 rem_flags
= entry
->wFlags
&
323 ~(PROCESS_HEAP_REGION
| PROCESS_HEAP_UNCOMMITTED_RANGE
|
324 PROCESS_HEAP_ENTRY_BUSY
| PROCESS_HEAP_ENTRY_MOVEABLE
|
325 PROCESS_HEAP_ENTRY_DDESHARE
);
327 TRACE( "Unknown %08x", rem_flags
);
329 if ((entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
330 && (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
))
333 TRACE( "BLOCK->hMem\t\t:%p\n", entry
->Block
.hMem
);
335 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
337 TRACE( "Region.dwCommittedSize\t:%08lx\n",entry
->Region
.dwCommittedSize
);
338 TRACE( "Region.dwUnCommittedSize\t:%08lx\n",entry
->Region
.dwUnCommittedSize
);
339 TRACE( "Region.lpFirstBlock\t:%p\n",entry
->Region
.lpFirstBlock
);
340 TRACE( "Region.lpLastBlock\t:%p\n",entry
->Region
.lpLastBlock
);
345 static PHEAP_USER_DATA
HEAP_GetUserData(HEAP
*heapPtr
, PVOID BaseAddress
)
347 PLIST_ENTRY CurrentEntry
;
348 PHEAP_USER_DATA udata
;
350 CurrentEntry
= heapPtr
->UserDataHead
.Flink
;
351 while (CurrentEntry
!= &heapPtr
->UserDataHead
)
353 udata
= CONTAINING_RECORD(CurrentEntry
, HEAP_USER_DATA
, ListEntry
);
354 if (udata
->BaseAddress
== BaseAddress
)
356 CurrentEntry
= CurrentEntry
->Flink
;
361 static PHEAP_USER_DATA
HEAP_AllocUserData(HEAP
*heapPtr
, PVOID BaseAddress
)
363 /* Allocate user data entry */
365 PHEAP_USER_DATA udata
= RtlAllocateHeap(heapPtr
, 0, sizeof(HEAP_USER_DATA
));
366 if (!udata
) return NULL
;
367 udata
->BaseAddress
= BaseAddress
;
368 InsertTailList(&heapPtr
->UserDataHead
, &udata
->ListEntry
);
369 pInUse
= (ARENA_INUSE
*)BaseAddress
- 1;
370 pInUse
->has_user_data
= 1;
374 /***********************************************************************
377 * Pointer to the heap
380 static HEAP
*HEAP_GetPtr(
381 HANDLE heap
/* [in] Handle to the heap */
383 HEAP
*heapPtr
= (HEAP
*)heap
;
384 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
387 ERR("Invalid heap %p, magic:%.4s!\n", heap
, &heapPtr
->magic
);
389 ERR("Invalid heap %p!\n", heap
);
390 //KeDumpStackFrames(NULL);
393 if (TRACE_ON(heap
) && !HEAP_IsRealArena( heapPtr
, 0, NULL
, NOISY
))
395 HEAP_Dump( heapPtr
);
403 /***********************************************************************
404 * HEAP_InsertFreeBlock
406 * Insert a free block into the free list.
408 static __inline
void HEAP_InsertFreeBlock( HEAP
*heap
, ARENA_FREE
*pArena
, BOOL last
)
410 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( pArena
->size
+ sizeof(*pArena
) );
413 /* insert at end of free list, i.e. before the next free list entry */
415 if (pEntry
== &heap
->freeList
[HEAP_NB_FREE_LISTS
]) pEntry
= heap
->freeList
;
416 list_add_before( &pEntry
->arena
.entry
, &pArena
->entry
);
420 /* insert at head of free list */
421 list_add_after( &pEntry
->arena
.entry
, &pArena
->entry
);
423 pArena
->size
|= ARENA_FLAG_FREE
;
427 /***********************************************************************
429 * Find the sub-heap containing a given address.
435 static SUBHEAP
*HEAP_FindSubHeap(
436 const HEAP
*heap
, /* [in] Heap pointer */
437 LPCVOID ptr
/* [in] Address */
439 const SUBHEAP
*sub
= &heap
->subheap
;
442 if (((const char *)ptr
>= (const char *)sub
) &&
443 ((const char *)ptr
< (const char *)sub
+ sub
->size
)) return (SUBHEAP
*)sub
;
449 /***********************************************************************
452 * Make sure the heap storage is committed for a given size in the specified arena.
454 static __inline BOOL
HEAP_Commit( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T data_size
)
457 void *ptr
= (char *)(pArena
+ 1) + data_size
+ sizeof(ARENA_FREE
);
458 SIZE_T size
= (char *)ptr
- (char *)subheap
;
459 size
= (size
+ COMMIT_MASK
) & ~COMMIT_MASK
;
460 if (size
> subheap
->size
) size
= subheap
->size
;
461 if (size
<= subheap
->commitSize
) return TRUE
;
462 size
-= subheap
->commitSize
;
463 ptr
= (char *)subheap
+ subheap
->commitSize
;
464 if (subheap
->heap
->commitRoutine
!= NULL
)
466 Status
= subheap
->heap
->commitRoutine(subheap
->heap
, &ptr
, &size
);
470 Status
= ZwAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0,
471 &size
, MEM_COMMIT
, get_protection_type(subheap
->heap
->flags
) );
473 if (!NT_SUCCESS(Status
))
475 WARN("Could not commit %08lx bytes at %p for heap %p\n",
476 size
, ptr
, subheap
->heap
);
479 subheap
->commitSize
+= size
;
484 /***********************************************************************
487 * If possible, decommit the heap storage from (including) 'ptr'.
489 static inline BOOL
HEAP_Decommit( SUBHEAP
*subheap
, void *ptr
)
492 SIZE_T decommit_size
;
493 SIZE_T size
= (char *)ptr
- (char *)subheap
;
495 /* round to next block and add one full block */
496 size
= ((size
+ COMMIT_MASK
) & ~COMMIT_MASK
) + COMMIT_MASK
+ 1;
497 if (size
>= subheap
->commitSize
) return TRUE
;
498 decommit_size
= subheap
->commitSize
- size
;
499 addr
= (char *)subheap
+ size
;
501 if (ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &decommit_size
, MEM_DECOMMIT
))
503 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
504 decommit_size
, (char *)subheap
+ size
, subheap
->heap
);
507 subheap
->commitSize
-= decommit_size
;
512 /***********************************************************************
513 * HEAP_CreateFreeBlock
515 * Create a free block at a specified address. 'size' is the size of the
516 * whole block, including the new arena.
518 static void HEAP_CreateFreeBlock( SUBHEAP
*subheap
, void *ptr
, SIZE_T size
)
524 /* Create a free arena */
525 mark_block_uninitialized( ptr
, sizeof( ARENA_FREE
) );
526 pFree
= (ARENA_FREE
*)ptr
;
527 pFree
->magic
= ARENA_FREE_MAGIC
;
529 /* If debugging, erase the freed block content */
531 pEnd
= (char *)ptr
+ size
;
532 if (pEnd
> (char *)subheap
+ subheap
->commitSize
) pEnd
= (char *)subheap
+ subheap
->commitSize
;
533 if (pEnd
> (char *)(pFree
+ 1)) mark_block_free( pFree
+ 1, pEnd
- (char *)(pFree
+ 1) );
535 /* Check if next block is free also */
537 if (((char *)ptr
+ size
< (char *)subheap
+ subheap
->size
) &&
538 (*(DWORD
*)((char *)ptr
+ size
) & ARENA_FLAG_FREE
))
540 /* Remove the next arena from the free list */
541 ARENA_FREE
*pNext
= (ARENA_FREE
*)((char *)ptr
+ size
);
542 list_remove( &pNext
->entry
);
543 size
+= (pNext
->size
& ARENA_SIZE_MASK
) + sizeof(*pNext
);
544 mark_block_free( pNext
, sizeof(ARENA_FREE
) );
547 /* Set the next block PREV_FREE flag and pointer */
549 last
= ((char *)ptr
+ size
>= (char *)subheap
+ subheap
->size
);
552 DWORD
*pNext
= (DWORD
*)((char *)ptr
+ size
);
553 *pNext
|= ARENA_FLAG_PREV_FREE
;
554 mark_block_initialized( pNext
- 1, sizeof( ARENA_FREE
* ) );
555 *((ARENA_FREE
**)pNext
- 1) = pFree
;
558 /* Last, insert the new block into the free list */
560 pFree
->size
= size
- sizeof(*pFree
);
561 HEAP_InsertFreeBlock( subheap
->heap
, pFree
, last
);
565 /***********************************************************************
566 * HEAP_MakeInUseBlockFree
568 * Turn an in-use block into a free block. Can also decommit the end of
569 * the heap, and possibly even free the sub-heap altogether.
571 static void HEAP_MakeInUseBlockFree( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
)
574 SIZE_T size
= (pArena
->size
& ARENA_SIZE_MASK
) + sizeof(*pArena
);
575 PHEAP_USER_DATA udata
;
577 /* Find and free user data */
578 if (pArena
->has_user_data
)
580 udata
= HEAP_GetUserData(subheap
->heap
, pArena
+ 1);
583 RemoveEntryList(&udata
->ListEntry
);
584 RtlFreeHeap(subheap
->heap
, 0, udata
);
588 /* Check if we can merge with previous block */
590 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
592 pFree
= *((ARENA_FREE
**)pArena
- 1);
593 size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
594 /* Remove it from the free list */
595 list_remove( &pFree
->entry
);
597 else pFree
= (ARENA_FREE
*)pArena
;
599 /* Create a free block */
601 HEAP_CreateFreeBlock( subheap
, pFree
, size
);
602 size
= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
603 if ((char *)pFree
+ size
< (char *)subheap
+ subheap
->size
)
604 return; /* Not the last block, so nothing more to do */
606 /* Free the whole sub-heap if it's empty and not the original one */
608 if (((char *)pFree
== (char *)subheap
+ subheap
->headerSize
) &&
609 (subheap
!= &subheap
->heap
->subheap
))
612 SUBHEAP
*pPrev
= &subheap
->heap
->subheap
;
613 /* Remove the free block from the list */
614 list_remove( &pFree
->entry
);
615 /* Remove the subheap from the list */
616 while (pPrev
&& (pPrev
->next
!= subheap
)) pPrev
= pPrev
->next
;
617 if (pPrev
) pPrev
->next
= subheap
->next
;
618 /* Free the memory */
620 ZwFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap
, &size
, MEM_RELEASE
);
624 /* Decommit the end of the heap */
627 /***********************************************************************
630 * Shrink an in-use block.
632 static void HEAP_ShrinkBlock(SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T size
)
634 if ((pArena
->size
& ARENA_SIZE_MASK
) >= size
+ HEAP_MIN_SHRINK_SIZE
)
636 HEAP_CreateFreeBlock( subheap
, (char *)(pArena
+ 1) + size
,
637 (pArena
->size
& ARENA_SIZE_MASK
) - size
);
638 /* assign size plus previous arena flags */
639 pArena
->size
= size
| (pArena
->size
& ~ARENA_SIZE_MASK
);
643 /* Turn off PREV_FREE flag in next block */
644 char *pNext
= (char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
);
645 if (pNext
< (char *)subheap
+ subheap
->size
)
646 *(DWORD
*)pNext
&= ~ARENA_FLAG_PREV_FREE
;
650 /***********************************************************************
653 static BOOL
HEAP_InitSubHeap( HEAP
*heap
, LPVOID address
, DWORD flags
,
654 SIZE_T commitSize
, SIZE_T totalSize
,
655 PRTL_HEAP_PARAMETERS Parameters
)
658 FREE_LIST_ENTRY
*pEntry
;
662 if (!address
&& ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0,
663 &commitSize
, MEM_COMMIT
, get_protection_type(flags
) ))
665 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize
, address
);
669 /* Fill the sub-heap structure */
671 subheap
= (SUBHEAP
*)address
;
672 subheap
->heap
= heap
;
673 subheap
->size
= totalSize
;
674 subheap
->commitSize
= commitSize
;
675 subheap
->magic
= SUBHEAP_MAGIC
;
677 if ( subheap
!= (SUBHEAP
*)heap
)
679 /* If this is a secondary subheap, insert it into list */
681 subheap
->headerSize
= ROUND_SIZE( sizeof(SUBHEAP
) );
682 subheap
->next
= heap
->subheap
.next
;
683 heap
->subheap
.next
= subheap
;
687 /* If this is a primary subheap, initialize main heap */
689 subheap
->headerSize
= ROUND_SIZE( sizeof(HEAP
) );
690 subheap
->next
= NULL
;
692 heap
->magic
= HEAP_MAGIC
;
694 heap
->commitRoutine
= Parameters
->CommitRoutine
;
696 heap
->commitRoutine
= NULL
;
697 InitializeListHead(&heap
->UserDataHead
);
699 /* Build the free lists */
701 list_init( &heap
->freeList
[0].arena
.entry
);
702 for (i
= 0, pEntry
= heap
->freeList
; i
< HEAP_NB_FREE_LISTS
; i
++, pEntry
++)
704 pEntry
->arena
.size
= 0 | ARENA_FLAG_FREE
;
705 pEntry
->arena
.magic
= ARENA_FREE_MAGIC
;
706 if (i
) list_add_after( &pEntry
[-1].arena
.entry
, &pEntry
->arena
.entry
);
709 /* Initialize critical section */
711 if (RtlpGetMode() == UserMode
)
713 if (!processHeap
) /* do it by hand to avoid memory allocations */
715 heap
->critSection
.DebugInfo
= &process_heap_critsect_debug
;
716 heap
->critSection
.LockCount
= -1;
717 heap
->critSection
.RecursionCount
= 0;
718 heap
->critSection
.OwningThread
= 0;
719 heap
->critSection
.LockSemaphore
= 0;
720 heap
->critSection
.SpinCount
= 0;
721 process_heap_critsect_debug
.CriticalSection
= &heap
->critSection
;
723 else RtlInitializeHeapLock( &heap
->critSection
);
728 if (heap
->commitRoutine
)
730 if (subheap
!= (SUBHEAP
*)heap
)
732 Status
= heap
->commitRoutine(heap
, &address
, &commitSize
);
736 /* the caller is responsible for committing the first page! */
737 Status
= STATUS_SUCCESS
;
742 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
747 get_protection_type(flags
));
749 if (!NT_SUCCESS(Status
))
751 DPRINT("Could not commit %08lx bytes for sub-heap %p\n",
752 commitSize
, address
);
756 /* Create the first free block */
758 HEAP_CreateFreeBlock( subheap
, (LPBYTE
)subheap
+ subheap
->headerSize
,
759 subheap
->size
- subheap
->headerSize
);
764 /***********************************************************************
767 * Create a sub-heap of the given size.
768 * If heap == NULL, creates a main heap.
770 static SUBHEAP
*HEAP_CreateSubHeap( HEAP
*heap
, void *base
, DWORD flags
,
771 SIZE_T commitSize
, SIZE_T totalSize
,
772 IN PRTL_HEAP_PARAMETERS Parameters
)
774 LPVOID address
= base
;
776 /* round-up sizes on a 64K boundary */
777 totalSize
= (totalSize
+ 0xffff) & 0xffff0000;
778 commitSize
= (commitSize
+ 0xffff) & 0xffff0000;
779 if (!commitSize
) commitSize
= 0x10000;
780 totalSize
= min( totalSize
, 0xffff0000 ); /* don't allow a heap larger than 4Gb */
781 if (totalSize
< commitSize
) totalSize
= commitSize
;
785 /* allocate the memory block */
786 if (ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0, &totalSize
,
787 MEM_RESERVE
| MEM_COMMIT
, get_protection_type(flags
) ))
789 WARN("Could not allocate %08lx bytes\n", totalSize
);
794 /* Initialize subheap */
796 if (!HEAP_InitSubHeap( heap
? heap
: (HEAP
*)address
,
797 address
, flags
, commitSize
, totalSize
, Parameters
))
800 if (!base
) ZwFreeVirtualMemory( NtCurrentProcess(), &address
, &size
, MEM_RELEASE
);
804 return (SUBHEAP
*)address
;
808 /***********************************************************************
811 * Find a free block at least as large as the requested size, and make sure
812 * the requested size is committed.
814 static ARENA_FREE
*HEAP_FindFreeBlock( HEAP
*heap
, SIZE_T size
,
815 SUBHEAP
**ppSubHeap
)
820 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( size
+ sizeof(ARENA_INUSE
) );
822 /* Find a suitable free list, and in it find a block large enough */
824 ptr
= &pEntry
->arena
.entry
;
825 while ((ptr
= list_next( &heap
->freeList
[0].arena
.entry
, ptr
)))
827 ARENA_FREE
*pArena
= LIST_ENTRY( ptr
, ARENA_FREE
, entry
);
828 SIZE_T arena_size
= (pArena
->size
& ARENA_SIZE_MASK
) +
829 sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
830 if (arena_size
>= size
)
832 subheap
= HEAP_FindSubHeap( heap
, pArena
);
833 if (!HEAP_Commit( subheap
, (ARENA_INUSE
*)pArena
, size
)) return NULL
;
834 *ppSubHeap
= subheap
;
839 /* If no block was found, attempt to grow the heap */
841 if (!(heap
->flags
& HEAP_GROWABLE
))
843 ERR("Not enough space in heap %p for %08lx bytes\n", heap
, size
);
846 /* make sure that we have a big enough size *committed* to fit another
847 * last free arena in !
848 * So just one heap struct, one first free arena which will eventually
849 * get used, and a second free arena that might get assigned all remaining
850 * free space in HEAP_ShrinkBlock() */
851 total_size
= size
+ ROUND_SIZE(sizeof(SUBHEAP
)) + sizeof(ARENA_INUSE
) + sizeof(ARENA_FREE
);
852 if (total_size
< size
) return NULL
; /* overflow */
854 if (!(subheap
= HEAP_CreateSubHeap( heap
, NULL
, heap
->flags
, total_size
,
855 max( HEAP_DEF_SIZE
, total_size
), NULL
)))
858 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
859 subheap
, size
, heap
);
861 *ppSubHeap
= subheap
;
862 return (ARENA_FREE
*)(subheap
+ 1);
865 /***********************************************************************
866 * HEAP_IsValidArenaPtr
868 * Check that the pointer is inside the range possible for arenas.
870 static BOOL
HEAP_IsValidArenaPtr( const HEAP
*heap
, const void *ptr
)
873 const SUBHEAP
*subheap
= HEAP_FindSubHeap( heap
, ptr
);
874 if (!subheap
) return FALSE
;
875 if ((const char *)ptr
>= (const char *)subheap
+ subheap
->headerSize
) return TRUE
;
876 if (subheap
!= &heap
->subheap
) return FALSE
;
877 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
878 if (ptr
== (const void *)&heap
->freeList
[i
].arena
) return TRUE
;
883 /***********************************************************************
884 * HEAP_ValidateFreeArena
886 static BOOL
HEAP_ValidateFreeArena( SUBHEAP
*subheap
, ARENA_FREE
*pArena
)
888 ARENA_FREE
*prev
, *next
;
889 char *heapEnd
= (char *)subheap
+ subheap
->size
;
891 /* Check for unaligned pointers */
892 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= ARENA_OFFSET
)
894 ERR("Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
898 /* Check magic number */
899 if (pArena
->magic
!= ARENA_FREE_MAGIC
)
901 ERR("Heap %p: invalid free arena magic for %p\n", subheap
->heap
, pArena
);
904 /* Check size flags */
905 if (!(pArena
->size
& ARENA_FLAG_FREE
) ||
906 (pArena
->size
& ARENA_FLAG_PREV_FREE
))
908 ERR("Heap %p: bad flags %08lx for free arena %p\n",
909 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
912 /* Check arena size */
913 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
915 ERR("Heap %p: bad size %08lx for free arena %p\n",
916 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
919 /* Check that next pointer is valid */
920 next
= LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
);
921 if (!HEAP_IsValidArenaPtr( subheap
->heap
, next
))
923 ERR("Heap %p: bad next ptr %p for arena %p\n",
924 subheap
->heap
, next
, pArena
);
927 /* Check that next arena is free */
928 if (!(next
->size
& ARENA_FLAG_FREE
) || (next
->magic
!= ARENA_FREE_MAGIC
))
930 ERR("Heap %p: next arena %p invalid for %p\n",
931 subheap
->heap
, next
, pArena
);
934 /* Check that prev pointer is valid */
935 prev
= LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
);
936 if (!HEAP_IsValidArenaPtr( subheap
->heap
, prev
))
938 ERR("Heap %p: bad prev ptr %p for arena %p\n",
939 subheap
->heap
, prev
, pArena
);
942 /* Check that prev arena is free */
943 if (!(prev
->size
& ARENA_FLAG_FREE
) || (prev
->magic
!= ARENA_FREE_MAGIC
))
945 /* this often means that the prev arena got overwritten
946 * by a memory write before that prev arena */
947 ERR("Heap %p: prev arena %p invalid for %p\n",
948 subheap
->heap
, prev
, pArena
);
951 /* Check that next block has PREV_FREE flag */
952 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
)
954 if (!(*(DWORD
*)((char *)(pArena
+ 1) +
955 (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
957 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
958 subheap
->heap
, pArena
);
961 /* Check next block back pointer */
962 if (*((ARENA_FREE
**)((char *)(pArena
+ 1) +
963 (pArena
->size
& ARENA_SIZE_MASK
)) - 1) != pArena
)
965 ERR("Heap %p: arena %p has wrong back ptr %p\n",
966 subheap
->heap
, pArena
,
967 *((ARENA_FREE
**)((char *)(pArena
+1) + (pArena
->size
& ARENA_SIZE_MASK
)) - 1));
974 /***********************************************************************
975 * HEAP_ValidateInUseArena
977 static BOOL
HEAP_ValidateInUseArena( const SUBHEAP
*subheap
, const ARENA_INUSE
*pArena
, BOOL quiet
)
979 const char *heapEnd
= (const char *)subheap
+ subheap
->size
;
981 /* Check for unaligned pointers */
982 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= ARENA_OFFSET
)
984 if ( quiet
== NOISY
)
986 ERR( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
987 if ( TRACE_ON(heap
) )
988 HEAP_Dump( subheap
->heap
);
990 else if ( WARN_ON(heap
) )
992 WARN( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
993 if ( TRACE_ON(heap
) )
994 HEAP_Dump( subheap
->heap
);
999 /* Check magic number */
1000 if (pArena
->magic
!= ARENA_INUSE_MAGIC
)
1002 if (quiet
== NOISY
) {
1003 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
1005 HEAP_Dump( subheap
->heap
);
1006 } else if (WARN_ON(heap
)) {
1007 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
1009 HEAP_Dump( subheap
->heap
);
1013 /* Check size flags */
1014 if (pArena
->size
& ARENA_FLAG_FREE
)
1016 ERR("Heap %p: bad flags %08lx for in-use arena %p\n",
1017 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
1020 /* Check arena size */
1021 if ((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
1023 ERR("Heap %p: bad size %08lx for in-use arena %p\n",
1024 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
1027 /* Check next arena PREV_FREE flag */
1028 if (((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
) &&
1029 (*(const DWORD
*)((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
1031 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
1032 subheap
->heap
, pArena
);
1035 /* Check prev free arena */
1036 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
1038 const ARENA_FREE
*pPrev
= *((const ARENA_FREE
* const*)pArena
- 1);
1039 /* Check prev pointer */
1040 if (!HEAP_IsValidArenaPtr( subheap
->heap
, pPrev
))
1042 ERR("Heap %p: bad back ptr %p for arena %p\n",
1043 subheap
->heap
, pPrev
, pArena
);
1046 /* Check that prev arena is free */
1047 if (!(pPrev
->size
& ARENA_FLAG_FREE
) ||
1048 (pPrev
->magic
!= ARENA_FREE_MAGIC
))
1050 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1051 subheap
->heap
, pPrev
, pArena
);
1054 /* Check that prev arena is really the previous block */
1055 if ((const char *)(pPrev
+ 1) + (pPrev
->size
& ARENA_SIZE_MASK
) != (const char *)pArena
)
1057 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1058 subheap
->heap
, pPrev
, pArena
);
1065 /***********************************************************************
1066 * HEAP_IsRealArena [Internal]
1067 * Validates a block is a valid arena.
1073 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, /* [in] ptr to the heap */
1074 DWORD flags
, /* [in] Bit flags that control access during operation */
1075 LPCVOID block
, /* [in] Optional pointer to memory block to validate */
1076 BOOL quiet
) /* [in] Flag - if true, HEAP_ValidateInUseArena
1077 * does not complain */
1082 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
1084 ERR("Invalid heap %p!\n", heapPtr
);
1088 flags
&= HEAP_NO_SERIALIZE
;
1089 flags
|= heapPtr
->flags
;
1090 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1091 if (!(flags
& HEAP_NO_SERIALIZE
))
1092 RtlEnterHeapLock( &heapPtr
->critSection
);
1096 /* Only check this single memory block */
1098 if (!(subheap
= HEAP_FindSubHeap( heapPtr
, block
)) ||
1099 ((const char *)block
< (char *)subheap
+ subheap
->headerSize
1100 + sizeof(ARENA_INUSE
)))
1103 ERR("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1104 else if (WARN_ON(heap
))
1105 WARN("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1108 ret
= HEAP_ValidateInUseArena( subheap
, (const ARENA_INUSE
*)block
- 1, quiet
);
1110 if (!(flags
& HEAP_NO_SERIALIZE
))
1111 RtlLeaveHeapLock( &heapPtr
->critSection
);
1115 subheap
= &heapPtr
->subheap
;
1116 while (subheap
&& ret
)
1118 char *ptr
= (char *)subheap
+ subheap
->headerSize
;
1119 while (ptr
< (char *)subheap
+ subheap
->size
)
1121 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
1123 if (!HEAP_ValidateFreeArena( subheap
, (ARENA_FREE
*)ptr
)) {
1127 ptr
+= sizeof(ARENA_FREE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1131 if (!HEAP_ValidateInUseArena( subheap
, (ARENA_INUSE
*)ptr
, NOISY
)) {
1135 ptr
+= sizeof(ARENA_INUSE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1138 subheap
= subheap
->next
;
1141 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1146 /***********************************************************************
1147 * HeapCreate (KERNEL32.336)
1149 * Handle of heap: Success
1155 RtlCreateHeap(ULONG flags
,
1160 PRTL_HEAP_PARAMETERS Parameters
)
1164 /* Allocate the heap block */
1168 totalSize
= HEAP_DEF_SIZE
;
1169 flags
|= HEAP_GROWABLE
;
1171 if (!(subheap
= HEAP_CreateSubHeap( NULL
, addr
, flags
, commitSize
, totalSize
, Parameters
))) return 0;
1173 if (RtlpGetMode() == UserMode
)
1175 /* link it into the per-process heap list */
1178 HEAP
*heapPtr
= subheap
->heap
;
1179 RtlEnterHeapLock( &processHeap
->critSection
);
1180 list_add_head( &processHeap
->entry
, &heapPtr
->entry
);
1181 RtlLeaveHeapLock( &processHeap
->critSection
);
1185 processHeap
= subheap
->heap
; /* assume the first heap we create is the process main heap */
1186 list_init( &processHeap
->entry
);
1187 assert( (ULONG_PTR
)processHeap
->freeList
% ALIGNMENT
== ARENA_OFFSET
);
1191 return (HANDLE
)subheap
;
1194 /***********************************************************************
1195 * HeapDestroy (KERNEL32.337)
1203 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1204 * Failure: The Heap handle, if heap is the process heap.
1207 RtlDestroyHeap(HANDLE heap
) /* [in] Handle of heap */
1209 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1212 DPRINT("%p\n", heap
);
1216 if (RtlpGetMode() == UserMode
)
1218 if (heap
== NtCurrentPeb()->ProcessHeap
)
1219 return heap
; /* cannot delete the main process heap */
1221 /* remove it from the per-process list */
1222 RtlEnterHeapLock( &processHeap
->critSection
);
1223 list_remove( &heapPtr
->entry
);
1224 RtlLeaveHeapLock( &processHeap
->critSection
);
1227 RtlDeleteHeapLock( &heapPtr
->critSection
);
1228 subheap
= &heapPtr
->subheap
;
1231 SUBHEAP
*next
= subheap
->next
;
1233 void *addr
= subheap
;
1234 ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &size
, MEM_RELEASE
);
1237 return (HANDLE
)NULL
;
1241 /***********************************************************************
1242 * HeapAlloc (KERNEL32.334)
1244 * Pointer to allocated memory block
1246 * 0x7d030f60--invalid flags in RtlHeapAllocate
1250 RtlAllocateHeap(HANDLE heap
, /* [in] Handle of private heap block */
1251 ULONG flags
, /* [in] Heap allocation control flags */
1252 ULONG size
) /* [in] Number of bytes to allocate */
1255 ARENA_INUSE
*pInUse
;
1257 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1258 SIZE_T rounded_size
;
1260 /* Validate the parameters */
1264 if (flags
& HEAP_GENERATE_EXCEPTIONS
)
1265 RtlRaiseStatus( STATUS_NO_MEMORY
);
1268 //flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1269 flags
|= heapPtr
->flags
;
1270 rounded_size
= ROUND_SIZE(size
);
1271 if (rounded_size
< size
) /* overflow */
1273 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1277 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1279 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1280 /* Locate a suitable free block */
1281 if (!(pArena
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &subheap
)))
1283 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1284 heap
, flags
, size
);
1285 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1286 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1290 /* Remove the arena from the free list */
1292 list_remove( &pArena
->entry
);
1294 /* Build the in-use arena */
1296 pInUse
= (ARENA_INUSE
*)pArena
;
1298 /* in-use arena is smaller than free arena,
1299 * so we have to add the difference to the size */
1300 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
) + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1301 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1302 pInUse
->has_user_data
= 0;
1304 /* Shrink the block */
1306 HEAP_ShrinkBlock( subheap
, pInUse
, rounded_size
);
1307 pInUse
->unused_bytes
= (pInUse
->size
& ARENA_SIZE_MASK
) - size
;
1309 if (flags
& HEAP_ZERO_MEMORY
)
1311 clear_block( pInUse
+ 1, size
);
1312 mark_block_uninitialized( (char *)(pInUse
+ 1) + size
, pInUse
->unused_bytes
);
1315 mark_block_uninitialized( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1317 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1319 TRACE("(%p,%08lx,%08lx): returning %p\n", heap
, flags
, size
, pInUse
+ 1 );
1320 return (LPVOID
)(pInUse
+ 1);
1324 /***********************************************************************
1325 * HeapFree (KERNEL32.338)
1332 BOOLEAN NTAPI
RtlFreeHeap(
1333 HANDLE heap
, /* [in] Handle of heap */
1334 ULONG flags
, /* [in] Heap freeing flags */
1335 PVOID ptr
/* [in] Address of memory to free */
1338 ARENA_INUSE
*pInUse
;
1342 /* Validate the parameters */
1344 if (!ptr
) return TRUE
; /* freeing a NULL ptr isn't an error in Win2k */
1346 heapPtr
= HEAP_GetPtr( heap
);
1349 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1353 flags
&= HEAP_NO_SERIALIZE
;
1354 flags
|= heapPtr
->flags
;
1355 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1356 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1358 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1359 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1360 TRACE("(%p,%08lx,%p): returning FALSE\n", heap
, flags
, ptr
);
1364 /* Some sanity checks */
1365 pInUse
= (ARENA_INUSE
*)ptr
- 1;
1366 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1367 if ((char *)pInUse
< (char *)subheap
+ subheap
->headerSize
) goto error
;
1368 if (!HEAP_ValidateInUseArena( subheap
, pInUse
, QUIET
)) goto error
;
1370 /* Turn the block into a free block */
1372 HEAP_MakeInUseBlockFree( subheap
, pInUse
);
1374 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1376 TRACE("(%p,%08lx,%p): returning TRUE\n", heap
, flags
, ptr
);
1380 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1381 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1382 TRACE("(%p,%08x,%p): returning FALSE\n", heap
, flags
, ptr
);
1387 /***********************************************************************
1390 * Heap [in] Handle of heap block
1391 * Flags [in] Heap reallocation flags
1392 * Ptr, [in] Address of memory to reallocate
1393 * Size [in] Number of bytes to reallocate
1396 * Pointer to reallocated memory block
1398 * 0x7d030f60--invalid flags in RtlHeapAllocate
1401 PVOID NTAPI
RtlReAllocateHeap(
1408 ARENA_INUSE
*pArena
;
1411 SIZE_T oldBlockSize
, oldActualSize
, rounded_size
;
1413 if (!ptr
) return NULL
;
1414 if (!(heapPtr
= HEAP_GetPtr( heap
)))
1416 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1420 /* Validate the parameters */
1422 //Flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1423 // HEAP_REALLOC_IN_PLACE_ONLY;
1424 flags
|= heapPtr
->flags
;
1425 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1427 rounded_size
= ROUND_SIZE(size
);
1428 if (rounded_size
< size
) goto oom
; /* overflow */
1429 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1431 pArena
= (ARENA_INUSE
*)ptr
- 1;
1432 if(!(subheap
= HEAP_FindSubHeap( heapPtr
, pArena
))) goto done
;
1433 if ((char *)pArena
< (char *)subheap
+ subheap
->headerSize
) goto error
;
1434 if (!HEAP_ValidateInUseArena( subheap
, pArena
, QUIET
)) goto error
;
1436 oldBlockSize
= (pArena
->size
& ARENA_SIZE_MASK
);
1437 oldActualSize
= (pArena
->size
& ARENA_SIZE_MASK
) - pArena
->unused_bytes
;
1439 if (rounded_size
> oldBlockSize
)
1441 char *pNext
= (char *)(pArena
+ 1) + oldBlockSize
;
1442 if ((pNext
< (char *)subheap
+ subheap
->size
) &&
1443 (*(DWORD
*)pNext
& ARENA_FLAG_FREE
) &&
1444 (oldBlockSize
+ (*(DWORD
*)pNext
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
) >= rounded_size
))
1446 ARENA_FREE
*pFree
= (ARENA_FREE
*)pNext
;
1447 list_remove( &pFree
->entry
);
1448 pArena
->size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(*pFree
);
1450 if (!HEAP_Commit( subheap
, pArena
, rounded_size
)) goto oom
;
1452 HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
);
1453 mark_block_initialized( pArena
+ 1, oldActualSize
);
1455 else /* Do it the hard way */
1458 ARENA_INUSE
*pInUse
;
1459 SUBHEAP
*newsubheap
;
1460 if ((flags
& HEAP_REALLOC_IN_PLACE_ONLY
) ||
1461 !(pNew
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &newsubheap
)))
1464 /* Build the in-use arena */
1466 list_remove( &pNew
->entry
);
1467 pInUse
= (ARENA_INUSE
*)pNew
;
1468 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
)
1469 + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1470 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1471 HEAP_ShrinkBlock( newsubheap
, pInUse
, rounded_size
);
1473 mark_block_initialized( pInUse
+ 1, oldActualSize
);
1474 memcpy( pInUse
+ 1, pArena
+ 1, oldActualSize
);
1476 /* Free the previous block */
1478 HEAP_MakeInUseBlockFree( subheap
, pArena
);
1479 subheap
= newsubheap
;
1485 HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
); /* Shrink the block */
1486 mark_block_initialized( pArena
+ 1, size
);
1489 pArena
->unused_bytes
= (pArena
->size
& ARENA_SIZE_MASK
) - size
;
1491 /* Clear the extra bytes if needed */
1493 if (size
> oldActualSize
)
1495 if (flags
& HEAP_ZERO_MEMORY
)
1497 clear_block( (char *)(pArena
+ 1) + oldActualSize
, size
- oldActualSize
);
1498 mark_block_uninitialized( (char *)(pArena
+ 1) + size
,
1499 (pArena
->size
& ARENA_SIZE_MASK
) - oldActualSize
);
1502 mark_block_uninitialized( (char *)(pArena
+ 1) + oldActualSize
,
1503 (pArena
->size
& ARENA_SIZE_MASK
) - oldActualSize
);
1506 /* Return the new arena */
1508 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1509 TRACE("(%p,%08lx,%p,%08lx): returning %p\n", heap
, flags
, ptr
, size
, pArena
+ 1 );
1510 return (LPVOID
)(pArena
+ 1);
1513 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1514 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1515 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1516 TRACE("(%p,%08x,%p,%08lx): returning oom\n", heap
, flags
, ptr
, size
);
1520 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1521 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1522 TRACE("(%p,%08x,%p,%08lx): returning error\n", heap
, flags
, ptr
, size
);
1527 /***********************************************************************
1533 RtlCompactHeap(HANDLE Heap
,
1541 /***********************************************************************
1543 * Attempts to acquire the critical section object for a specified heap.
1546 * Heap [in] Handle of heap to lock for exclusive access
1555 RtlLockHeap(IN HANDLE Heap
)
1557 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1560 RtlEnterHeapLock( &heapPtr
->critSection
);
1565 /***********************************************************************
1567 * Releases ownership of the critical section object.
1570 * Heap [in] Handle to the heap to unlock
1579 RtlUnlockHeap(HANDLE Heap
)
1581 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1584 RtlLeaveHeapLock( &heapPtr
->critSection
);
1589 /***********************************************************************
1592 * Heap [in] Handle of heap
1593 * Flags [in] Heap size control flags
1594 * Ptr [in] Address of memory to return size for
1597 * Size in bytes of allocated memory
1598 * 0xffffffff: Failure
1610 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1614 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1617 flags
&= HEAP_NO_SERIALIZE
;
1618 flags
|= heapPtr
->flags
;
1619 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1620 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1622 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1627 const ARENA_INUSE
*pArena
= (const ARENA_INUSE
*)ptr
- 1;
1628 ret
= (pArena
->size
& ARENA_SIZE_MASK
) - pArena
->unused_bytes
;
1630 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1632 TRACE("(%p,%08lx,%p): returning %08lx\n", heap
, flags
, ptr
, ret
);
1637 /***********************************************************************
1639 * Validates a specified heap.
1642 * Heap [in] Handle to the heap
1643 * Flags [in] Bit flags that control access during operation
1644 * Block [in] Optional pointer to memory block to validate
1655 BOOLEAN NTAPI
RtlValidateHeap(
1661 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1664 return HEAP_IsRealArena( heapPtr
, Flags
, Block
, QUIET
);
1668 RtlInitializeHeapManager(VOID
)
1672 Peb
= NtCurrentPeb();
1674 Peb
->NumberOfHeaps
= 0;
1675 Peb
->MaximumNumberOfHeaps
= -1; /* no limit */
1676 Peb
->ProcessHeaps
= NULL
;
1678 //RtlInitializeHeapLock(&RtlpProcessHeapsListLock);
1686 RtlEnumProcessHeaps(PHEAP_ENUMERATION_ROUTINE HeapEnumerationRoutine
,
1689 NTSTATUS Status
= STATUS_SUCCESS
;
1691 struct list
*ptr
=NULL
;
1692 RtlEnterHeapLock(&processHeap
->critSection
);
1693 Status
=HeapEnumerationRoutine(processHeap
,lParam
);
1695 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1697 if (!NT_SUCCESS(Status
)) break;
1698 Status
= HeapEnumerationRoutine(ptr
,lParam
);
1701 RtlLeaveHeapLock(&processHeap
->critSection
);
1711 RtlGetProcessHeaps(ULONG count
,
1714 ULONG total
= 1; /* main heap */
1717 RtlEnterHeapLock( &processHeap
->critSection
);
1718 LIST_FOR_EACH( ptr
, &processHeap
->entry
) total
++;
1719 //if (total <= count)
1721 *(heaps
++) = processHeap
;
1723 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1725 if (i
>= count
) break;
1727 *(heaps
++) = LIST_ENTRY( ptr
, HEAP
, entry
);
1730 RtlLeaveHeapLock( &processHeap
->critSection
);
1739 RtlValidateProcessHeaps(VOID
)
1741 BOOLEAN Result
= TRUE
;
1744 RtlEnterHeapLock( &processHeap
->critSection
);
1746 for (pptr
= (HEAP
**)&NtCurrentPeb()->ProcessHeaps
; *pptr
; pptr
++)
1748 if (!RtlValidateHeap(*pptr
, 0, NULL
))
1755 RtlLeaveHeapLock( &processHeap
->critSection
);
1765 IN PVOID HeapHandle
,
1778 RtlSetUserValueHeap(IN PVOID HeapHandle
,
1780 IN PVOID BaseAddress
,
1784 PHEAP_USER_DATA udata
;
1786 heapPtr
= HEAP_GetPtr(HeapHandle
);
1789 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1792 udata
= HEAP_GetUserData(heapPtr
, BaseAddress
);
1795 udata
= HEAP_AllocUserData(heapPtr
, BaseAddress
);
1796 if (!udata
) return FALSE
;
1798 udata
->UserValue
= UserValue
;
1807 RtlSetUserFlagsHeap(IN PVOID HeapHandle
,
1809 IN PVOID BaseAddress
,
1813 PHEAP_USER_DATA udata
;
1815 heapPtr
= HEAP_GetPtr(HeapHandle
);
1818 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1821 udata
= HEAP_GetUserData(heapPtr
, BaseAddress
);
1824 udata
= HEAP_AllocUserData(heapPtr
, BaseAddress
);
1825 if (!udata
) return FALSE
;
1827 udata
->UserFlags
= UserFlags
& HEAP_SETTABLE_USER_FLAGS
;
1836 RtlGetUserInfoHeap(IN PVOID HeapHandle
,
1838 IN PVOID BaseAddress
,
1839 OUT PVOID
*UserValue
,
1840 OUT PULONG UserFlags
)
1843 PHEAP_USER_DATA udata
;
1845 heapPtr
= HEAP_GetPtr(HeapHandle
);
1848 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1851 udata
= HEAP_GetUserData(heapPtr
, BaseAddress
);
1854 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1857 if (UserValue
) *UserValue
= udata
->UserValue
;
1858 if (UserFlags
) *UserFlags
= udata
->UserFlags
;
1867 RtlUsageHeap(IN HANDLE Heap
,
1869 OUT PRTL_HEAP_USAGE Usage
)
1873 return STATUS_NOT_IMPLEMENTED
;
1878 RtlQueryTagHeap(IN PVOID HeapHandle
,
1881 IN BOOLEAN ResetCounters
,
1882 OUT PRTL_HEAP_TAG_INFO HeapTagInfo
)
1891 RtlExtendHeap(IN HANDLE Heap
,
1903 RtlCreateTagHeap(IN HANDLE HeapHandle
,
1906 IN PWSTR TagSubName
)
1915 RtlWalkHeap(IN HANDLE HeapHandle
,
1919 return STATUS_NOT_IMPLEMENTED
;
1924 RtlProtectHeap(IN PVOID HeapHandle
,
1925 IN BOOLEAN ReadOnly
)
1933 RtlSetHeapInformation(IN HANDLE HeapHandle OPTIONAL
,
1934 IN HEAP_INFORMATION_CLASS HeapInformationClass
,
1935 IN PVOID HeapInformation
,
1936 IN SIZE_T HeapInformationLength
)
1944 RtlQueryHeapInformation(HANDLE HeapHandle
,
1945 HEAP_INFORMATION_CLASS HeapInformationClass
,
1946 PVOID HeapInformation OPTIONAL
,
1947 SIZE_T HeapInformationLength OPTIONAL
,
1948 PSIZE_T ReturnLength OPTIONAL
)
1956 RtlMultipleAllocateHeap(IN PVOID HeapHandle
,
1968 RtlMultipleFreeHeap(IN PVOID HeapHandle
,