1 /* COPYRIGHT: See COPYING in the top level directory
2 * PROJECT: ReactOS system libraries
3 * FILE: lib/rtl/image.c
4 * PURPOSE: Image handling functions
5 * PROGRAMMERS: Copyright 1996 Alexandre Julliard
6 * Copyright 1998 Ulrich Weigand
10 // Note: This is a slightly modified implementation of WINE's.
12 // WINE's implementation is a hack based on Windows 95's heap implementation,
13 // itself a hack of DOS memory management.It supports 3 out of the 18 possible
14 // NT Heap Flags, does not support custom allocation/deallocation routines,
15 // and is about 50-80x slower with fragmentation rates up to 500x higher when
16 // compared to NT's LFH. WINE is lucky because the advanced NT Heap features are
17 // used in kernel-mode usually, not in user-mode, and they are crossing their
18 // fingers for this being the same. Note that several high-end SQL/Database
19 // applications would significantly benefit from custom heap features provided
22 // ROS's changes include:
23 // - Using Zw instead of Nt calls, because this matters when in Kernel Mode
24 // - Not using per-process heap lists while in Kernel Mode
25 // - Using a macro to handle the Critical Section, because it's meaningless
27 // - Crappy support for a custom Commit routine.
28 // - Crappy support for User-defined flags and the User-defined value.
29 // - Ripping out all the code for shared heaps, because those don't exist on NT.
31 // Be aware of these changes when you try to sync something back.
34 /* INCLUDES *****************************************************************/
38 #undef LIST_FOR_EACH_SAFE
39 #include <wine/list.h>
47 #define DPRINTF DPRINT
49 /* FUNCTIONS *****************************************************************/
51 #define WARN_ON(x) (1)
54 #define TRACE_ON(x) (0)
56 #define TRACE_ON(x) (1)
59 /* Note: the heap data structures are based on what Pietrek describes in his
60 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
61 * the same, but could be easily adapted if it turns out some programs
65 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
66 * that there is no unaligned accesses to structure fields.
69 typedef struct tagARENA_INUSE
71 DWORD size
; /* Block size; must be the first field */
72 DWORD magic
: 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 DWORD 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 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
94 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
96 #define QUIET 1 /* Suppress messages */
97 #define NOISY 0 /* Report all errors */
99 /* minimum data size (without arenas) of an allocated block */
100 #define HEAP_MIN_DATA_SIZE 16
101 /* minimum size that must remain to shrink an allocated block */
102 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
104 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
106 /* Max size of the blocks on the free lists */
107 static const DWORD HEAP_freeListSizes
[HEAP_NB_FREE_LISTS
] =
109 0x20, 0x80, 0x200, ~0UL
119 typedef struct tagSUBHEAP
121 DWORD size
; /* Size of the whole sub-heap */
122 DWORD commitSize
; /* Committed size of the sub-heap */
123 DWORD headerSize
; /* Size of the heap header */
124 struct tagSUBHEAP
*next
; /* Next sub-heap */
125 struct tagHEAP
*heap
; /* Main heap structure */
126 DWORD magic
; /* Magic number */
129 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
131 typedef struct tagHEAP_USER_DATA
133 LIST_ENTRY ListEntry
;
137 } HEAP_USER_DATA
, *PHEAP_USER_DATA
;
139 typedef struct tagHEAP
141 SUBHEAP subheap
; /* First sub-heap */
142 struct list entry
; /* Entry in process heap list */
143 RTL_CRITICAL_SECTION critSection
; /* Critical section for serialization */
144 FREE_LIST_ENTRY freeList
[HEAP_NB_FREE_LISTS
]; /* Free lists */
145 DWORD flags
; /* Heap flags */
146 DWORD magic
; /* Magic number */
147 PRTL_HEAP_COMMIT_ROUTINE commitRoutine
;
148 LIST_ENTRY UserDataHead
;
151 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
153 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
154 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
156 static HEAP
*processHeap
; /* main process heap */
158 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, DWORD flags
, LPCVOID block
, BOOL quiet
);
160 /* mark a block of memory as free for debugging purposes */
161 static __inline
void mark_block_free( void *ptr
, SIZE_T size
)
163 if (TRACE_ON(heap
)) memset( ptr
, ARENA_FREE_FILLER
, size
);
164 #ifdef VALGRIND_MAKE_NOACCESS
165 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr
, size
));
169 /* mark a block of memory as initialized for debugging purposes */
170 static __inline
void mark_block_initialized( void *ptr
, SIZE_T size
)
172 #ifdef VALGRIND_MAKE_READABLE
173 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr
, size
));
177 /* mark a block of memory as uninitialized for debugging purposes */
178 static __inline
void mark_block_uninitialized( void *ptr
, SIZE_T size
)
180 #ifdef VALGRIND_MAKE_WRITABLE
181 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr
, size
));
185 memset( ptr
, ARENA_INUSE_FILLER
, size
);
186 #ifdef VALGRIND_MAKE_WRITABLE
187 /* make it uninitialized to valgrind again */
188 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr
, size
));
193 /* clear contents of a block of memory */
194 static __inline
void clear_block( void *ptr
, SIZE_T size
)
196 mark_block_initialized( ptr
, size
);
197 memset( ptr
, 0, size
);
200 /* locate a free list entry of the appropriate size */
201 /* size is the size of the whole block including the arena header */
202 static __inline
unsigned int get_freelist_index( SIZE_T size
)
206 size
-= sizeof(ARENA_FREE
);
207 for (i
= 0; i
< HEAP_NB_FREE_LISTS
- 1; i
++) if (size
<= HEAP_freeListSizes
[i
]) break;
211 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug
=
213 0, 0, NULL
, /* will be set later */
214 { &process_heap_critsect_debug
.ProcessLocksList
, &process_heap_critsect_debug
.ProcessLocksList
},
218 /***********************************************************************
221 static void HEAP_Dump( HEAP
*heap
)
227 DPRINTF( "Heap: %p\n", heap
);
228 DPRINTF( "Next: %p Sub-heaps: %p",
229 LIST_ENTRY( heap
->entry
.next
, HEAP
, entry
), &heap
->subheap
);
230 subheap
= &heap
->subheap
;
231 while (subheap
->next
)
233 DPRINTF( " -> %p", subheap
->next
);
234 subheap
= subheap
->next
;
237 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
238 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
239 DPRINTF( "%p free %08lx prev=%p next=%p\n",
240 &heap
->freeList
[i
].arena
, HEAP_freeListSizes
[i
],
241 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.prev
, ARENA_FREE
, entry
),
242 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.next
, ARENA_FREE
, entry
));
244 subheap
= &heap
->subheap
;
247 SIZE_T freeSize
= 0, usedSize
= 0, arenaSize
= subheap
->headerSize
;
248 DPRINTF( "\n\nSub-heap %p: size=%08lx committed=%08lx\n",
249 subheap
, subheap
->size
, subheap
->commitSize
);
251 DPRINTF( "\n Block Stat Size Id\n" );
252 ptr
= (char*)subheap
+ subheap
->headerSize
;
253 while (ptr
< (char *)subheap
+ subheap
->size
)
255 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
257 ARENA_FREE
*pArena
= (ARENA_FREE
*)ptr
;
258 DPRINTF( "%p free %08lx prev=%p next=%p\n",
259 pArena
, pArena
->size
& ARENA_SIZE_MASK
,
260 LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
),
261 LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
) );
262 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
263 arenaSize
+= sizeof(ARENA_FREE
);
264 freeSize
+= pArena
->size
& ARENA_SIZE_MASK
;
266 else if (*(DWORD
*)ptr
& ARENA_FLAG_PREV_FREE
)
268 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
269 DPRINTF( "%p Used %08lx back=%p\n",
270 pArena
, pArena
->size
& ARENA_SIZE_MASK
, *((ARENA_FREE
**)pArena
- 1) );
271 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
272 arenaSize
+= sizeof(ARENA_INUSE
);
273 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
277 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
278 DPRINTF( "%p used %08lx\n", pArena
, pArena
->size
& ARENA_SIZE_MASK
);
279 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
280 arenaSize
+= sizeof(ARENA_INUSE
);
281 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
284 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
285 subheap
->size
, subheap
->commitSize
, freeSize
, usedSize
,
286 arenaSize
, (arenaSize
* 100) / subheap
->size
);
287 subheap
= subheap
->next
;
292 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry
)
295 TRACE( "Dumping entry %p\n", entry
);
296 TRACE( "lpData\t\t: %p\n", entry
->lpData
);
297 TRACE( "cbData\t\t: %08lx\n", entry
->cbData
);
298 TRACE( "cbOverhead\t: %08x\n", entry
->cbOverhead
);
299 TRACE( "iRegionIndex\t: %08x\n", entry
->iRegionIndex
);
300 TRACE( "WFlags\t\t: ");
301 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
302 TRACE( "PROCESS_HEAP_REGION ");
303 if (entry
->wFlags
& PROCESS_HEAP_UNCOMMITTED_RANGE
)
304 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
305 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
306 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
307 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
)
308 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
309 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_DDESHARE
)
310 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
311 rem_flags
= entry
->wFlags
&
312 ~(PROCESS_HEAP_REGION
| PROCESS_HEAP_UNCOMMITTED_RANGE
|
313 PROCESS_HEAP_ENTRY_BUSY
| PROCESS_HEAP_ENTRY_MOVEABLE
|
314 PROCESS_HEAP_ENTRY_DDESHARE
);
316 TRACE( "Unknown %08x", rem_flags
);
318 if ((entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
319 && (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
))
322 TRACE( "BLOCK->hMem\t\t:%p\n", entry
->Block
.hMem
);
324 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
326 TRACE( "Region.dwCommittedSize\t:%08lx\n",entry
->Region
.dwCommittedSize
);
327 TRACE( "Region.dwUnCommittedSize\t:%08lx\n",entry
->Region
.dwUnCommittedSize
);
328 TRACE( "Region.lpFirstBlock\t:%p\n",entry
->Region
.lpFirstBlock
);
329 TRACE( "Region.lpLastBlock\t:%p\n",entry
->Region
.lpLastBlock
);
334 static PHEAP_USER_DATA
HEAP_GetUserData(HEAP
*heapPtr
, PVOID BaseAddress
)
336 PLIST_ENTRY CurrentEntry
;
337 PHEAP_USER_DATA udata
;
339 CurrentEntry
= heapPtr
->UserDataHead
.Flink
;
340 while (CurrentEntry
!= &heapPtr
->UserDataHead
)
342 udata
= CONTAINING_RECORD(CurrentEntry
, HEAP_USER_DATA
, ListEntry
);
343 if (udata
->BaseAddress
== BaseAddress
)
345 CurrentEntry
= CurrentEntry
->Flink
;
350 static PHEAP_USER_DATA
HEAP_AllocUserData(HEAP
*heapPtr
, PVOID BaseAddress
)
352 /* Allocate user data entry */
354 PHEAP_USER_DATA udata
= RtlAllocateHeap(heapPtr
, 0, sizeof(HEAP_USER_DATA
));
355 if (!udata
) return NULL
;
356 udata
->BaseAddress
= BaseAddress
;
357 InsertTailList(&heapPtr
->UserDataHead
, &udata
->ListEntry
);
358 pInUse
= (ARENA_INUSE
*)BaseAddress
- 1;
359 pInUse
->has_user_data
= 1;
363 /***********************************************************************
366 * Pointer to the heap
369 static HEAP
*HEAP_GetPtr(
370 HANDLE heap
/* [in] Handle to the heap */
372 HEAP
*heapPtr
= (HEAP
*)heap
;
373 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
376 ERR("Invalid heap %p, magic:%.4s!\n", heap
, &heapPtr
->magic
);
378 ERR("Invalid heap %p!\n", heap
);
379 //KeDumpStackFrames(NULL);
382 if (TRACE_ON(heap
) && !HEAP_IsRealArena( heapPtr
, 0, NULL
, NOISY
))
384 HEAP_Dump( heapPtr
);
392 /***********************************************************************
393 * HEAP_InsertFreeBlock
395 * Insert a free block into the free list.
397 static __inline
void HEAP_InsertFreeBlock( HEAP
*heap
, ARENA_FREE
*pArena
, BOOL last
)
399 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( pArena
->size
+ sizeof(*pArena
) );
402 /* insert at end of free list, i.e. before the next free list entry */
404 if (pEntry
== &heap
->freeList
[HEAP_NB_FREE_LISTS
]) pEntry
= heap
->freeList
;
405 list_add_before( &pEntry
->arena
.entry
, &pArena
->entry
);
409 /* insert at head of free list */
410 list_add_after( &pEntry
->arena
.entry
, &pArena
->entry
);
412 pArena
->size
|= ARENA_FLAG_FREE
;
416 /***********************************************************************
418 * Find the sub-heap containing a given address.
424 static SUBHEAP
*HEAP_FindSubHeap(
425 const HEAP
*heap
, /* [in] Heap pointer */
426 LPCVOID ptr
/* [in] Address */
428 const SUBHEAP
*sub
= &heap
->subheap
;
431 if (((const char *)ptr
>= (const char *)sub
) &&
432 ((const char *)ptr
< (const char *)sub
+ sub
->size
)) return (SUBHEAP
*)sub
;
438 /***********************************************************************
441 * Make sure the heap storage is committed for a given size in the specified arena.
443 static __inline BOOL
HEAP_Commit( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T data_size
)
446 void *ptr
= (char *)(pArena
+ 1) + data_size
+ sizeof(ARENA_FREE
);
447 SIZE_T size
= (char *)ptr
- (char *)subheap
;
448 size
= (size
+ COMMIT_MASK
) & ~COMMIT_MASK
;
449 if (size
> subheap
->size
) size
= subheap
->size
;
450 if (size
<= subheap
->commitSize
) return TRUE
;
451 size
-= subheap
->commitSize
;
452 ptr
= (char *)subheap
+ subheap
->commitSize
;
453 if (subheap
->heap
->commitRoutine
!= NULL
)
455 Status
= subheap
->heap
->commitRoutine(subheap
->heap
, &ptr
, &size
);
459 Status
= ZwAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0,
460 &size
, MEM_COMMIT
, PAGE_READWRITE
);
462 if (!NT_SUCCESS(Status
))
464 WARN("Could not commit %08lx bytes at %p for heap %p\n",
465 size
, ptr
, subheap
->heap
);
468 subheap
->commitSize
+= size
;
473 /***********************************************************************
476 * If possible, decommit the heap storage from (including) 'ptr'.
478 static inline BOOL
HEAP_Decommit( SUBHEAP
*subheap
, void *ptr
)
481 SIZE_T decommit_size
;
482 SIZE_T size
= (char *)ptr
- (char *)subheap
;
484 /* round to next block and add one full block */
485 size
= ((size
+ COMMIT_MASK
) & ~COMMIT_MASK
) + COMMIT_MASK
+ 1;
486 if (size
>= subheap
->commitSize
) return TRUE
;
487 decommit_size
= subheap
->commitSize
- size
;
488 addr
= (char *)subheap
+ size
;
490 if (ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &decommit_size
, MEM_DECOMMIT
))
492 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
493 decommit_size
, (char *)subheap
+ size
, subheap
->heap
);
496 subheap
->commitSize
-= decommit_size
;
501 /***********************************************************************
502 * HEAP_CreateFreeBlock
504 * Create a free block at a specified address. 'size' is the size of the
505 * whole block, including the new arena.
507 static void HEAP_CreateFreeBlock( SUBHEAP
*subheap
, void *ptr
, SIZE_T size
)
513 /* Create a free arena */
514 mark_block_uninitialized( ptr
, sizeof( ARENA_FREE
) );
515 pFree
= (ARENA_FREE
*)ptr
;
516 pFree
->magic
= ARENA_FREE_MAGIC
;
518 /* If debugging, erase the freed block content */
520 pEnd
= (char *)ptr
+ size
;
521 if (pEnd
> (char *)subheap
+ subheap
->commitSize
) pEnd
= (char *)subheap
+ subheap
->commitSize
;
522 if (pEnd
> (char *)(pFree
+ 1)) mark_block_free( pFree
+ 1, pEnd
- (char *)(pFree
+ 1) );
524 /* Check if next block is free also */
526 if (((char *)ptr
+ size
< (char *)subheap
+ subheap
->size
) &&
527 (*(DWORD
*)((char *)ptr
+ size
) & ARENA_FLAG_FREE
))
529 /* Remove the next arena from the free list */
530 ARENA_FREE
*pNext
= (ARENA_FREE
*)((char *)ptr
+ size
);
531 list_remove( &pNext
->entry
);
532 size
+= (pNext
->size
& ARENA_SIZE_MASK
) + sizeof(*pNext
);
533 mark_block_free( pNext
, sizeof(ARENA_FREE
) );
536 /* Set the next block PREV_FREE flag and pointer */
538 last
= ((char *)ptr
+ size
>= (char *)subheap
+ subheap
->size
);
541 DWORD
*pNext
= (DWORD
*)((char *)ptr
+ size
);
542 *pNext
|= ARENA_FLAG_PREV_FREE
;
543 mark_block_initialized( pNext
- 1, sizeof( ARENA_FREE
* ) );
544 *((ARENA_FREE
**)pNext
- 1) = pFree
;
547 /* Last, insert the new block into the free list */
549 pFree
->size
= size
- sizeof(*pFree
);
550 HEAP_InsertFreeBlock( subheap
->heap
, pFree
, last
);
554 /***********************************************************************
555 * HEAP_MakeInUseBlockFree
557 * Turn an in-use block into a free block. Can also decommit the end of
558 * the heap, and possibly even free the sub-heap altogether.
560 static void HEAP_MakeInUseBlockFree( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
)
563 SIZE_T size
= (pArena
->size
& ARENA_SIZE_MASK
) + sizeof(*pArena
);
564 PHEAP_USER_DATA udata
;
566 /* Find and free user data */
567 if (pArena
->has_user_data
)
569 udata
= HEAP_GetUserData(subheap
->heap
, pArena
+ 1);
572 RemoveEntryList(&udata
->ListEntry
);
573 RtlFreeHeap(subheap
->heap
, 0, udata
);
577 /* Check if we can merge with previous block */
579 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
581 pFree
= *((ARENA_FREE
**)pArena
- 1);
582 size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
583 /* Remove it from the free list */
584 list_remove( &pFree
->entry
);
586 else pFree
= (ARENA_FREE
*)pArena
;
588 /* Create a free block */
590 HEAP_CreateFreeBlock( subheap
, pFree
, size
);
591 size
= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
592 if ((char *)pFree
+ size
< (char *)subheap
+ subheap
->size
)
593 return; /* Not the last block, so nothing more to do */
595 /* Free the whole sub-heap if it's empty and not the original one */
597 if (((char *)pFree
== (char *)subheap
+ subheap
->headerSize
) &&
598 (subheap
!= &subheap
->heap
->subheap
))
601 SUBHEAP
*pPrev
= &subheap
->heap
->subheap
;
602 /* Remove the free block from the list */
603 list_remove( &pFree
->entry
);
604 /* Remove the subheap from the list */
605 while (pPrev
&& (pPrev
->next
!= subheap
)) pPrev
= pPrev
->next
;
606 if (pPrev
) pPrev
->next
= subheap
->next
;
607 /* Free the memory */
609 ZwFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap
, &size
, MEM_RELEASE
);
613 /* Decommit the end of the heap */
616 /***********************************************************************
619 * Shrink an in-use block.
621 static void HEAP_ShrinkBlock(SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T size
)
623 if ((pArena
->size
& ARENA_SIZE_MASK
) >= size
+ HEAP_MIN_SHRINK_SIZE
)
625 HEAP_CreateFreeBlock( subheap
, (char *)(pArena
+ 1) + size
,
626 (pArena
->size
& ARENA_SIZE_MASK
) - size
);
627 /* assign size plus previous arena flags */
628 pArena
->size
= size
| (pArena
->size
& ~ARENA_SIZE_MASK
);
632 /* Turn off PREV_FREE flag in next block */
633 char *pNext
= (char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
);
634 if (pNext
< (char *)subheap
+ subheap
->size
)
635 *(DWORD
*)pNext
&= ~ARENA_FLAG_PREV_FREE
;
639 /***********************************************************************
642 static BOOL
HEAP_InitSubHeap( HEAP
*heap
, LPVOID address
, DWORD flags
,
643 SIZE_T commitSize
, SIZE_T totalSize
,
644 PRTL_HEAP_PARAMETERS Parameters
)
647 FREE_LIST_ENTRY
*pEntry
;
651 if (!address
&& ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0,
652 &commitSize
, MEM_COMMIT
, PAGE_READWRITE
))
654 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize
, address
);
658 /* Fill the sub-heap structure */
660 subheap
= (SUBHEAP
*)address
;
661 subheap
->heap
= heap
;
662 subheap
->size
= totalSize
;
663 subheap
->commitSize
= commitSize
;
664 subheap
->magic
= SUBHEAP_MAGIC
;
666 if ( subheap
!= (SUBHEAP
*)heap
)
668 /* If this is a secondary subheap, insert it into list */
670 subheap
->headerSize
= ROUND_SIZE( sizeof(SUBHEAP
) );
671 subheap
->next
= heap
->subheap
.next
;
672 heap
->subheap
.next
= subheap
;
676 /* If this is a primary subheap, initialize main heap */
678 subheap
->headerSize
= ROUND_SIZE( sizeof(HEAP
) );
679 subheap
->next
= NULL
;
681 heap
->magic
= HEAP_MAGIC
;
683 heap
->commitRoutine
= Parameters
->CommitRoutine
;
685 heap
->commitRoutine
= NULL
;
686 InitializeListHead(&heap
->UserDataHead
);
688 /* Build the free lists */
690 list_init( &heap
->freeList
[0].arena
.entry
);
691 for (i
= 0, pEntry
= heap
->freeList
; i
< HEAP_NB_FREE_LISTS
; i
++, pEntry
++)
693 pEntry
->arena
.size
= 0 | ARENA_FLAG_FREE
;
694 pEntry
->arena
.magic
= ARENA_FREE_MAGIC
;
695 if (i
) list_add_after( &pEntry
[-1].arena
.entry
, &pEntry
->arena
.entry
);
698 /* Initialize critical section */
700 if (RtlpGetMode() == UserMode
)
702 if (!processHeap
) /* do it by hand to avoid memory allocations */
704 heap
->critSection
.DebugInfo
= &process_heap_critsect_debug
;
705 heap
->critSection
.LockCount
= -1;
706 heap
->critSection
.RecursionCount
= 0;
707 heap
->critSection
.OwningThread
= 0;
708 heap
->critSection
.LockSemaphore
= 0;
709 heap
->critSection
.SpinCount
= 0;
710 process_heap_critsect_debug
.CriticalSection
= &heap
->critSection
;
712 else RtlInitializeHeapLock( &heap
->critSection
);
717 if (heap
->commitRoutine
)
719 if (subheap
!= (SUBHEAP
*)heap
)
721 Status
= heap
->commitRoutine(heap
, &address
, &commitSize
);
725 /* the caller is responsible for committing the first page! */
726 Status
= STATUS_SUCCESS
;
731 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
736 PAGE_EXECUTE_READWRITE
);
738 if (!NT_SUCCESS(Status
))
740 DPRINT("Could not commit %08lx bytes for sub-heap %p\n",
741 commitSize
, address
);
745 /* Create the first free block */
747 HEAP_CreateFreeBlock( subheap
, (LPBYTE
)subheap
+ subheap
->headerSize
,
748 subheap
->size
- subheap
->headerSize
);
753 /***********************************************************************
756 * Create a sub-heap of the given size.
757 * If heap == NULL, creates a main heap.
759 static SUBHEAP
*HEAP_CreateSubHeap( HEAP
*heap
, void *base
, DWORD flags
,
760 SIZE_T commitSize
, SIZE_T totalSize
,
761 IN PRTL_HEAP_PARAMETERS Parameters
)
763 LPVOID address
= base
;
765 /* round-up sizes on a 64K boundary */
766 totalSize
= (totalSize
+ 0xffff) & 0xffff0000;
767 commitSize
= (commitSize
+ 0xffff) & 0xffff0000;
768 if (!commitSize
) commitSize
= 0x10000;
769 if (totalSize
< commitSize
) totalSize
= commitSize
;
773 /* allocate the memory block */
774 if (ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0, &totalSize
,
775 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
))
777 WARN("Could not allocate %08lx bytes\n", totalSize
);
782 /* Initialize subheap */
784 if (!HEAP_InitSubHeap( heap
? heap
: (HEAP
*)address
,
785 address
, flags
, commitSize
, totalSize
, Parameters
))
788 if (!base
) ZwFreeVirtualMemory( NtCurrentProcess(), &address
, &size
, MEM_RELEASE
);
792 return (SUBHEAP
*)address
;
796 /***********************************************************************
799 * Find a free block at least as large as the requested size, and make sure
800 * the requested size is committed.
802 static ARENA_FREE
*HEAP_FindFreeBlock( HEAP
*heap
, SIZE_T size
,
803 SUBHEAP
**ppSubHeap
)
807 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( size
+ sizeof(ARENA_INUSE
) );
809 /* Find a suitable free list, and in it find a block large enough */
811 ptr
= &pEntry
->arena
.entry
;
812 while ((ptr
= list_next( &heap
->freeList
[0].arena
.entry
, ptr
)))
814 ARENA_FREE
*pArena
= LIST_ENTRY( ptr
, ARENA_FREE
, entry
);
815 SIZE_T arena_size
= (pArena
->size
& ARENA_SIZE_MASK
) +
816 sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
817 if (arena_size
>= size
)
819 subheap
= HEAP_FindSubHeap( heap
, pArena
);
820 if (!HEAP_Commit( subheap
, (ARENA_INUSE
*)pArena
, size
)) return NULL
;
821 *ppSubHeap
= subheap
;
826 /* If no block was found, attempt to grow the heap */
828 if (!(heap
->flags
& HEAP_GROWABLE
))
830 ERR("Not enough space in heap %p for %08lx bytes\n", heap
, size
);
833 /* make sure that we have a big enough size *committed* to fit another
834 * last free arena in !
835 * So just one heap struct, one first free arena which will eventually
836 * get used, and a second free arena that might get assigned all remaining
837 * free space in HEAP_ShrinkBlock() */
838 size
+= ROUND_SIZE(sizeof(SUBHEAP
)) + sizeof(ARENA_INUSE
) + sizeof(ARENA_FREE
);
839 if (!(subheap
= HEAP_CreateSubHeap( heap
, NULL
, heap
->flags
, size
,
840 max( HEAP_DEF_SIZE
, size
), NULL
)))
843 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
844 subheap
, size
, heap
);
846 *ppSubHeap
= subheap
;
847 return (ARENA_FREE
*)(subheap
+ 1);
850 /***********************************************************************
851 * HEAP_IsValidArenaPtr
853 * Check that the pointer is inside the range possible for arenas.
855 static BOOL
HEAP_IsValidArenaPtr( const HEAP
*heap
, const void *ptr
)
858 const SUBHEAP
*subheap
= HEAP_FindSubHeap( heap
, ptr
);
859 if (!subheap
) return FALSE
;
860 if ((const char *)ptr
>= (const char *)subheap
+ subheap
->headerSize
) return TRUE
;
861 if (subheap
!= &heap
->subheap
) return FALSE
;
862 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
863 if (ptr
== (const void *)&heap
->freeList
[i
].arena
) return TRUE
;
868 /***********************************************************************
869 * HEAP_ValidateFreeArena
871 static BOOL
HEAP_ValidateFreeArena( SUBHEAP
*subheap
, ARENA_FREE
*pArena
)
873 ARENA_FREE
*prev
, *next
;
874 char *heapEnd
= (char *)subheap
+ subheap
->size
;
876 /* Check for unaligned pointers */
877 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= 0 )
879 ERR("Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
883 /* Check magic number */
884 if (pArena
->magic
!= ARENA_FREE_MAGIC
)
886 ERR("Heap %p: invalid free arena magic for %p\n", subheap
->heap
, pArena
);
889 /* Check size flags */
890 if (!(pArena
->size
& ARENA_FLAG_FREE
) ||
891 (pArena
->size
& ARENA_FLAG_PREV_FREE
))
893 ERR("Heap %p: bad flags %08lx for free arena %p\n",
894 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
897 /* Check arena size */
898 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
900 ERR("Heap %p: bad size %08lx for free arena %p\n",
901 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
904 /* Check that next pointer is valid */
905 next
= LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
);
906 if (!HEAP_IsValidArenaPtr( subheap
->heap
, next
))
908 ERR("Heap %p: bad next ptr %p for arena %p\n",
909 subheap
->heap
, next
, pArena
);
912 /* Check that next arena is free */
913 if (!(next
->size
& ARENA_FLAG_FREE
) || (next
->magic
!= ARENA_FREE_MAGIC
))
915 ERR("Heap %p: next arena %p invalid for %p\n",
916 subheap
->heap
, next
, pArena
);
919 /* Check that prev pointer is valid */
920 prev
= LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
);
921 if (!HEAP_IsValidArenaPtr( subheap
->heap
, prev
))
923 ERR("Heap %p: bad prev ptr %p for arena %p\n",
924 subheap
->heap
, prev
, pArena
);
927 /* Check that prev arena is free */
928 if (!(prev
->size
& ARENA_FLAG_FREE
) || (prev
->magic
!= ARENA_FREE_MAGIC
))
930 /* this often means that the prev arena got overwritten
931 * by a memory write before that prev arena */
932 ERR("Heap %p: prev arena %p invalid for %p\n",
933 subheap
->heap
, prev
, pArena
);
936 /* Check that next block has PREV_FREE flag */
937 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
)
939 if (!(*(DWORD
*)((char *)(pArena
+ 1) +
940 (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
942 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
943 subheap
->heap
, pArena
);
946 /* Check next block back pointer */
947 if (*((ARENA_FREE
**)((char *)(pArena
+ 1) +
948 (pArena
->size
& ARENA_SIZE_MASK
)) - 1) != pArena
)
950 ERR("Heap %p: arena %p has wrong back ptr %p\n",
951 subheap
->heap
, pArena
,
952 *((ARENA_FREE
**)((char *)(pArena
+1) + (pArena
->size
& ARENA_SIZE_MASK
)) - 1));
959 /***********************************************************************
960 * HEAP_ValidateInUseArena
962 static BOOL
HEAP_ValidateInUseArena( const SUBHEAP
*subheap
, const ARENA_INUSE
*pArena
, BOOL quiet
)
964 const char *heapEnd
= (const char *)subheap
+ subheap
->size
;
966 /* Check for unaligned pointers */
967 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= 0 )
969 if ( quiet
== NOISY
)
971 ERR( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
972 if ( TRACE_ON(heap
) )
973 HEAP_Dump( subheap
->heap
);
975 else if ( WARN_ON(heap
) )
977 WARN( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
978 if ( TRACE_ON(heap
) )
979 HEAP_Dump( subheap
->heap
);
984 /* Check magic number */
985 if (pArena
->magic
!= ARENA_INUSE_MAGIC
)
987 if (quiet
== NOISY
) {
988 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
990 HEAP_Dump( subheap
->heap
);
991 } else if (WARN_ON(heap
)) {
992 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
994 HEAP_Dump( subheap
->heap
);
998 /* Check size flags */
999 if (pArena
->size
& ARENA_FLAG_FREE
)
1001 ERR("Heap %p: bad flags %08lx for in-use arena %p\n",
1002 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
1005 /* Check arena size */
1006 if ((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
1008 ERR("Heap %p: bad size %08lx for in-use arena %p\n",
1009 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
1012 /* Check next arena PREV_FREE flag */
1013 if (((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
) &&
1014 (*(const DWORD
*)((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
1016 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
1017 subheap
->heap
, pArena
);
1020 /* Check prev free arena */
1021 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
1023 const ARENA_FREE
*pPrev
= *((const ARENA_FREE
* const*)pArena
- 1);
1024 /* Check prev pointer */
1025 if (!HEAP_IsValidArenaPtr( subheap
->heap
, pPrev
))
1027 ERR("Heap %p: bad back ptr %p for arena %p\n",
1028 subheap
->heap
, pPrev
, pArena
);
1031 /* Check that prev arena is free */
1032 if (!(pPrev
->size
& ARENA_FLAG_FREE
) ||
1033 (pPrev
->magic
!= ARENA_FREE_MAGIC
))
1035 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
1036 subheap
->heap
, pPrev
, pArena
);
1039 /* Check that prev arena is really the previous block */
1040 if ((const char *)(pPrev
+ 1) + (pPrev
->size
& ARENA_SIZE_MASK
) != (const char *)pArena
)
1042 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
1043 subheap
->heap
, pPrev
, pArena
);
1050 /***********************************************************************
1051 * HEAP_IsRealArena [Internal]
1052 * Validates a block is a valid arena.
1058 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, /* [in] ptr to the heap */
1059 DWORD flags
, /* [in] Bit flags that control access during operation */
1060 LPCVOID block
, /* [in] Optional pointer to memory block to validate */
1061 BOOL quiet
) /* [in] Flag - if true, HEAP_ValidateInUseArena
1062 * does not complain */
1067 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
1069 ERR("Invalid heap %p!\n", heapPtr
);
1073 flags
&= HEAP_NO_SERIALIZE
;
1074 flags
|= heapPtr
->flags
;
1075 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1076 if (!(flags
& HEAP_NO_SERIALIZE
))
1077 RtlEnterHeapLock( &heapPtr
->critSection
);
1081 /* Only check this single memory block */
1083 if (!(subheap
= HEAP_FindSubHeap( heapPtr
, block
)) ||
1084 ((const char *)block
< (char *)subheap
+ subheap
->headerSize
1085 + sizeof(ARENA_INUSE
)))
1088 ERR("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1089 else if (WARN_ON(heap
))
1090 WARN("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1093 ret
= HEAP_ValidateInUseArena( subheap
, (const ARENA_INUSE
*)block
- 1, quiet
);
1095 if (!(flags
& HEAP_NO_SERIALIZE
))
1096 RtlLeaveHeapLock( &heapPtr
->critSection
);
1100 subheap
= &heapPtr
->subheap
;
1101 while (subheap
&& ret
)
1103 char *ptr
= (char *)subheap
+ subheap
->headerSize
;
1104 while (ptr
< (char *)subheap
+ subheap
->size
)
1106 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
1108 if (!HEAP_ValidateFreeArena( subheap
, (ARENA_FREE
*)ptr
)) {
1112 ptr
+= sizeof(ARENA_FREE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1116 if (!HEAP_ValidateInUseArena( subheap
, (ARENA_INUSE
*)ptr
, NOISY
)) {
1120 ptr
+= sizeof(ARENA_INUSE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1123 subheap
= subheap
->next
;
1126 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1131 /***********************************************************************
1132 * HeapCreate (KERNEL32.336)
1134 * Handle of heap: Success
1140 RtlCreateHeap(ULONG flags
,
1145 PRTL_HEAP_PARAMETERS Parameters
)
1149 /* Allocate the heap block */
1153 totalSize
= HEAP_DEF_SIZE
;
1154 flags
|= HEAP_GROWABLE
;
1156 if (!(subheap
= HEAP_CreateSubHeap( NULL
, addr
, flags
, commitSize
, totalSize
, Parameters
))) return 0;
1158 if (RtlpGetMode() == UserMode
)
1160 /* link it into the per-process heap list */
1163 HEAP
*heapPtr
= subheap
->heap
;
1164 RtlEnterHeapLock( &processHeap
->critSection
);
1165 list_add_head( &processHeap
->entry
, &heapPtr
->entry
);
1166 RtlLeaveHeapLock( &processHeap
->critSection
);
1170 processHeap
= subheap
->heap
; /* assume the first heap we create is the process main heap */
1171 list_init( &processHeap
->entry
);
1175 return (HANDLE
)subheap
;
1178 /***********************************************************************
1179 * HeapDestroy (KERNEL32.337)
1187 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1188 * Failure: The Heap handle, if heap is the process heap.
1191 RtlDestroyHeap(HANDLE heap
) /* [in] Handle of heap */
1193 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1196 DPRINT("%p\n", heap
);
1200 if (RtlpGetMode() == UserMode
)
1202 if (heap
== NtCurrentPeb()->ProcessHeap
)
1203 return heap
; /* cannot delete the main process heap */
1205 /* remove it from the per-process list */
1206 RtlEnterHeapLock( &processHeap
->critSection
);
1207 list_remove( &heapPtr
->entry
);
1208 RtlLeaveHeapLock( &processHeap
->critSection
);
1211 RtlDeleteHeapLock( &heapPtr
->critSection
);
1212 subheap
= &heapPtr
->subheap
;
1215 SUBHEAP
*next
= subheap
->next
;
1217 void *addr
= subheap
;
1218 ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &size
, MEM_RELEASE
);
1221 return (HANDLE
)NULL
;
1225 /***********************************************************************
1226 * HeapAlloc (KERNEL32.334)
1228 * Pointer to allocated memory block
1230 * 0x7d030f60--invalid flags in RtlHeapAllocate
1234 RtlAllocateHeap(HANDLE heap
, /* [in] Handle of private heap block */
1235 ULONG flags
, /* [in] Heap allocation control flags */
1236 ULONG size
) /* [in] Number of bytes to allocate */
1239 ARENA_INUSE
*pInUse
;
1241 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1242 SIZE_T rounded_size
;
1244 /* Validate the parameters */
1248 if (flags
& HEAP_GENERATE_EXCEPTIONS
)
1249 RtlRaiseStatus( STATUS_NO_MEMORY
);
1252 //flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1253 flags
|= heapPtr
->flags
;
1254 rounded_size
= ROUND_SIZE(size
);
1255 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1257 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1258 /* Locate a suitable free block */
1260 /* Locate a suitable free block */
1262 if (!(pArena
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &subheap
)))
1264 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1265 heap
, flags
, size
);
1266 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1267 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1271 /* Remove the arena from the free list */
1273 list_remove( &pArena
->entry
);
1275 /* Build the in-use arena */
1277 pInUse
= (ARENA_INUSE
*)pArena
;
1279 /* in-use arena is smaller than free arena,
1280 * so we have to add the difference to the size */
1281 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
) + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1282 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1283 pInUse
->has_user_data
= 0;
1285 /* Shrink the block */
1287 HEAP_ShrinkBlock( subheap
, pInUse
, rounded_size
);
1288 pInUse
->unused_bytes
= (pInUse
->size
& ARENA_SIZE_MASK
) - size
;
1290 if (flags
& HEAP_ZERO_MEMORY
)
1291 clear_block( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1293 mark_block_uninitialized( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1295 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1297 TRACE("(%p,%08lx,%08lx): returning %p\n", heap
, flags
, size
, pInUse
+ 1 );
1298 return (LPVOID
)(pInUse
+ 1);
1302 /***********************************************************************
1303 * HeapFree (KERNEL32.338)
1310 BOOLEAN NTAPI
RtlFreeHeap(
1311 HANDLE heap
, /* [in] Handle of heap */
1312 ULONG flags
, /* [in] Heap freeing flags */
1313 PVOID ptr
/* [in] Address of memory to free */
1316 ARENA_INUSE
*pInUse
;
1320 /* Validate the parameters */
1322 if (!ptr
) return TRUE
; /* freeing a NULL ptr isn't an error in Win2k */
1324 heapPtr
= HEAP_GetPtr( heap
);
1327 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1331 flags
&= HEAP_NO_SERIALIZE
;
1332 flags
|= heapPtr
->flags
;
1333 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1334 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1336 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1337 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1338 TRACE("(%p,%08lx,%p): returning FALSE\n", heap
, flags
, ptr
);
1342 /* Turn the block into a free block */
1344 pInUse
= (ARENA_INUSE
*)ptr
- 1;
1345 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1346 HEAP_MakeInUseBlockFree( subheap
, pInUse
);
1348 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1350 TRACE("(%p,%08lx,%p): returning TRUE\n", heap
, flags
, ptr
);
1355 /***********************************************************************
1358 * Heap [in] Handle of heap block
1359 * Flags [in] Heap reallocation flags
1360 * Ptr, [in] Address of memory to reallocate
1361 * Size [in] Number of bytes to reallocate
1364 * Pointer to reallocated memory block
1366 * 0x7d030f60--invalid flags in RtlHeapAllocate
1369 PVOID NTAPI
RtlReAllocateHeap(
1376 ARENA_INUSE
*pArena
;
1379 SIZE_T oldSize
, rounded_size
;
1381 if (!ptr
) return NULL
;
1382 if (!(heapPtr
= HEAP_GetPtr( heap
)))
1384 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1388 /* Validate the parameters */
1390 //Flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1391 // HEAP_REALLOC_IN_PLACE_ONLY;
1392 flags
|= heapPtr
->flags
;
1393 rounded_size
= ROUND_SIZE(size
);
1394 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1396 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1397 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1399 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1400 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1401 TRACE("(%p,%08lx,%p,%08lx): returning NULL\n", heap
, flags
, ptr
, size
);
1405 pArena
= (ARENA_INUSE
*)ptr
- 1;
1406 subheap
= HEAP_FindSubHeap( heapPtr
, pArena
);
1407 oldSize
= (pArena
->size
& ARENA_SIZE_MASK
);
1408 if (rounded_size
> oldSize
)
1410 char *pNext
= (char *)(pArena
+ 1) + oldSize
;
1411 if ((pNext
< (char *)subheap
+ subheap
->size
) &&
1412 (*(DWORD
*)pNext
& ARENA_FLAG_FREE
) &&
1413 (oldSize
+ (*(DWORD
*)pNext
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
) >= rounded_size
))
1415 /* The next block is free and large enough */
1416 ARENA_FREE
*pFree
= (ARENA_FREE
*)pNext
;
1417 list_remove( &pFree
->entry
);
1418 pArena
->size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(*pFree
);
1419 if (!HEAP_Commit( subheap
, pArena
, rounded_size
))
1421 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1422 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1423 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1426 HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
);
1428 else /* Do it the hard way */
1431 ARENA_INUSE
*pInUse
;
1432 SUBHEAP
*newsubheap
;
1434 if ((flags
& HEAP_REALLOC_IN_PLACE_ONLY
) ||
1435 !(pNew
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &newsubheap
)))
1437 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1438 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1439 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1443 /* Build the in-use arena */
1445 list_remove( &pNew
->entry
);
1446 pInUse
= (ARENA_INUSE
*)pNew
;
1447 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
)
1448 + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1449 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1450 HEAP_ShrinkBlock( newsubheap
, pInUse
, rounded_size
);
1451 mark_block_initialized( pInUse
+ 1, oldSize
);
1452 memcpy( pInUse
+ 1, pArena
+ 1, oldSize
);
1454 /* Free the previous block */
1456 HEAP_MakeInUseBlockFree( subheap
, pArena
);
1457 subheap
= newsubheap
;
1461 else HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
); /* Shrink the block */
1463 pArena
->unused_bytes
= (pArena
->size
& ARENA_SIZE_MASK
) - size
;
1465 /* Clear the extra bytes if needed */
1467 if (rounded_size
> oldSize
)
1469 if (flags
& HEAP_ZERO_MEMORY
)
1470 clear_block( (char *)(pArena
+ 1) + oldSize
,
1471 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1473 mark_block_uninitialized( (char *)(pArena
+ 1) + oldSize
,
1474 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1477 /* Return the new arena */
1479 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1481 TRACE("(%p,%08lx,%p,%08lx): returning %p\n", heap
, flags
, ptr
, size
, pArena
+ 1 );
1482 return (LPVOID
)(pArena
+ 1);
1486 /***********************************************************************
1492 RtlCompactHeap(HANDLE Heap
,
1500 /***********************************************************************
1502 * Attempts to acquire the critical section object for a specified heap.
1505 * Heap [in] Handle of heap to lock for exclusive access
1514 RtlLockHeap(IN HANDLE Heap
)
1516 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1519 RtlEnterHeapLock( &heapPtr
->critSection
);
1524 /***********************************************************************
1526 * Releases ownership of the critical section object.
1529 * Heap [in] Handle to the heap to unlock
1538 RtlUnlockHeap(HANDLE Heap
)
1540 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1543 RtlLeaveHeapLock( &heapPtr
->critSection
);
1548 /***********************************************************************
1551 * Heap [in] Handle of heap
1552 * Flags [in] Heap size control flags
1553 * Ptr [in] Address of memory to return size for
1556 * Size in bytes of allocated memory
1557 * 0xffffffff: Failure
1569 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1573 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1576 flags
&= HEAP_NO_SERIALIZE
;
1577 flags
|= heapPtr
->flags
;
1578 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1579 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1581 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1586 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
- 1;
1587 ret
= (pArena
->size
& ARENA_SIZE_MASK
) - pArena
->unused_bytes
;
1589 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1591 TRACE("(%p,%08lx,%p): returning %08lx\n", heap
, flags
, ptr
, ret
);
1596 /***********************************************************************
1598 * Validates a specified heap.
1601 * Heap [in] Handle to the heap
1602 * Flags [in] Bit flags that control access during operation
1603 * Block [in] Optional pointer to memory block to validate
1614 BOOLEAN NTAPI
RtlValidateHeap(
1620 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1623 return HEAP_IsRealArena( heapPtr
, Flags
, Block
, QUIET
);
1627 RtlInitializeHeapManager(VOID
)
1631 Peb
= NtCurrentPeb();
1633 Peb
->NumberOfHeaps
= 0;
1634 Peb
->MaximumNumberOfHeaps
= -1; /* no limit */
1635 Peb
->ProcessHeaps
= NULL
;
1637 //RtlInitializeHeapLock(&RtlpProcessHeapsListLock);
1645 RtlEnumProcessHeaps(PHEAP_ENUMERATION_ROUTINE HeapEnumerationRoutine
,
1648 NTSTATUS Status
= STATUS_SUCCESS
;
1650 struct list
*ptr
=NULL
;
1651 RtlEnterHeapLock(&processHeap
->critSection
);
1652 Status
=HeapEnumerationRoutine(processHeap
,lParam
);
1654 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1656 if (!NT_SUCCESS(Status
)) break;
1657 Status
= HeapEnumerationRoutine(ptr
,lParam
);
1660 RtlLeaveHeapLock(&processHeap
->critSection
);
1670 RtlGetProcessHeaps(ULONG count
,
1673 ULONG total
= 1; /* main heap */
1676 RtlEnterHeapLock( &processHeap
->critSection
);
1677 LIST_FOR_EACH( ptr
, &processHeap
->entry
) total
++;
1678 //if (total <= count)
1680 *(heaps
++) = processHeap
;
1682 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1684 if (i
>= count
) break;
1686 *(heaps
++) = LIST_ENTRY( ptr
, HEAP
, entry
);
1689 RtlLeaveHeapLock( &processHeap
->critSection
);
1698 RtlValidateProcessHeaps(VOID
)
1700 BOOLEAN Result
= TRUE
;
1703 RtlEnterHeapLock( &processHeap
->critSection
);
1705 for (pptr
= (HEAP
**)&NtCurrentPeb()->ProcessHeaps
; *pptr
; pptr
++)
1707 if (!RtlValidateHeap(*pptr
, 0, NULL
))
1714 RtlLeaveHeapLock( &processHeap
->critSection
);
1724 IN PVOID HeapHandle
,
1737 RtlSetUserValueHeap(IN PVOID HeapHandle
,
1739 IN PVOID BaseAddress
,
1743 PHEAP_USER_DATA udata
;
1745 heapPtr
= HEAP_GetPtr(HeapHandle
);
1748 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1751 udata
= HEAP_GetUserData(heapPtr
, BaseAddress
);
1754 udata
= HEAP_AllocUserData(heapPtr
, BaseAddress
);
1755 if (!udata
) return FALSE
;
1757 udata
->UserValue
= UserValue
;
1766 RtlSetUserFlagsHeap(IN PVOID HeapHandle
,
1768 IN PVOID BaseAddress
,
1772 PHEAP_USER_DATA udata
;
1774 heapPtr
= HEAP_GetPtr(HeapHandle
);
1777 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1780 udata
= HEAP_GetUserData(heapPtr
, BaseAddress
);
1783 udata
= HEAP_AllocUserData(heapPtr
, BaseAddress
);
1784 if (!udata
) return FALSE
;
1786 udata
->UserFlags
= UserFlags
& HEAP_SETTABLE_USER_FLAGS
;
1795 RtlGetUserInfoHeap(IN PVOID HeapHandle
,
1797 IN PVOID BaseAddress
,
1798 OUT PVOID
*UserValue
,
1799 OUT PULONG UserFlags
)
1802 PHEAP_USER_DATA udata
;
1804 heapPtr
= HEAP_GetPtr(HeapHandle
);
1807 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1810 udata
= HEAP_GetUserData(heapPtr
, BaseAddress
);
1813 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1816 if (UserValue
) *UserValue
= udata
->UserValue
;
1817 if (UserFlags
) *UserFlags
= udata
->UserFlags
;
1826 RtlUsageHeap(IN HANDLE Heap
,
1828 OUT PRTL_HEAP_USAGE Usage
)
1832 return STATUS_NOT_IMPLEMENTED
;
1837 RtlQueryTagHeap(IN PVOID HeapHandle
,
1840 IN BOOLEAN ResetCounters
,
1841 OUT PRTL_HEAP_TAG_INFO HeapTagInfo
)
1850 RtlExtendHeap(IN HANDLE Heap
,
1862 RtlCreateTagHeap(IN HANDLE HeapHandle
,
1865 IN PWSTR TagSubName
)
1874 RtlWalkHeap(IN HANDLE HeapHandle
,
1878 return STATUS_NOT_IMPLEMENTED
;
1883 RtlProtectHeap(IN PVOID HeapHandle
,
1884 IN BOOLEAN ReadOnly
)
1892 RtlSetHeapInformation(IN HANDLE HeapHandle OPTIONAL
,
1893 IN HEAP_INFORMATION_CLASS HeapInformationClass
,
1894 IN PVOID HeapInformation
,
1895 IN SIZE_T HeapInformationLength
)
1903 RtlQueryHeapInformation(HANDLE HeapHandle
,
1904 HEAP_INFORMATION_CLASS HeapInformationClass
,
1905 PVOID HeapInformation OPTIONAL
,
1906 SIZE_T HeapInformationLength OPTIONAL
,
1907 PSIZE_T ReturnLength OPTIONAL
)
1915 RtlMultipleAllocateHeap(IN PVOID HeapHandle
,
1927 RtlMultipleFreeHeap(IN PVOID HeapHandle
,