1 /* COPYRIGHT: See COPYING in the top level directory
2 * PROJECT: ReactOS system libraries
3 * FILE: lib/rtl/image.c
4 * PURPOSE: Image handling functions
5 * PROGRAMMERS: Copyright 1996 Alexandre Julliard
6 * Copyright 1998 Ulrich Weigand
10 // Note: This is a slightly modified implementation of WINE's.
12 // WINE's implementation is a hack based on Windows 95's heap implementation,
13 // itself a hack of DOS memory management.It supports 3 out of the 18 possible
14 // NT Heap Flags, does not support custom allocation/deallocation routines,
15 // and is about 50-80x slower with fragmentation rates up to 500x higher when
16 // compared to NT's LFH. WINE is lucky because the advanced NT Heap features are
17 // used in kernel-mode usually, not in user-mode, and they are crossing their
18 // fingers for this being the same. Note that several high-end SQL/Database
19 // applications would significantly benefit from custom heap features provided
22 // ROS's changes include:
23 // - Using Zw instead of Nt calls, because this matters when in Kernel Mode
24 // - Not using per-process heap lists while in Kernel Mode
25 // - Using a macro to handle the Critical Section, because it's meaningless
27 // - Crappy support for a custom Commit routine.
28 // - Crappy support for User-defined flags and the User-defined value.
29 // - Ripping out all the code for shared heaps, because those don't exist on NT.
31 // Be aware of these changes when you try to sync something back.
34 /* INCLUDES *****************************************************************/
38 #undef LIST_FOR_EACH_SAFE
39 #include <wine/list.h>
47 #define DPRINTF DPRINT
49 /* FUNCTIONS *****************************************************************/
51 #define WARN_ON(x) (1)
54 #define TRACE_ON(x) (0)
56 #define TRACE_ON(x) (1)
59 /* Note: the heap data structures are based on what Pietrek describes in his
60 * book 'Windows 95 System Programming Secrets'. The layout is not exactly
61 * the same, but could be easily adapted if it turns out some programs
65 /* FIXME: use SIZE_T for 'size' structure members, but we need to make sure
66 * that there is no unaligned accesses to structure fields.
69 typedef struct tagARENA_INUSE
71 DWORD size
; /* Block size; must be the first field */
72 DWORD magic
: 24; /* Magic number */
73 DWORD unused_bytes
: 8; /* Number of bytes in the block not used by user data (max value is HEAP_MIN_DATA_SIZE+HEAP_MIN_SHRINK_SIZE) */
76 typedef struct tagARENA_FREE
78 DWORD size
; /* Block size; must be the first field */
79 DWORD magic
; /* Magic number */
80 struct list entry
; /* Entry in free list */
83 #define ARENA_FLAG_FREE 0x00000001 /* flags OR'ed with arena size */
84 #define ARENA_FLAG_PREV_FREE 0x00000002
85 #define ARENA_SIZE_MASK (~3)
86 #define ARENA_INUSE_MAGIC 0x455355 /* Value for arena 'magic' field */
87 #define ARENA_FREE_MAGIC 0x45455246 /* Value for arena 'magic' field */
89 #define ARENA_INUSE_FILLER 0x55
90 #define ARENA_FREE_FILLER 0xaa
92 #define ALIGNMENT 8 /* everything is aligned on 8 byte boundaries */
93 #define ROUND_SIZE(size) (((size) + ALIGNMENT - 1) & ~(ALIGNMENT-1))
95 #define QUIET 1 /* Suppress messages */
96 #define NOISY 0 /* Report all errors */
98 /* minimum data size (without arenas) of an allocated block */
99 #define HEAP_MIN_DATA_SIZE 16
100 /* minimum size that must remain to shrink an allocated block */
101 #define HEAP_MIN_SHRINK_SIZE (HEAP_MIN_DATA_SIZE+sizeof(ARENA_FREE))
103 #define HEAP_NB_FREE_LISTS 4 /* Number of free lists */
105 /* Max size of the blocks on the free lists */
106 static const DWORD HEAP_freeListSizes
[HEAP_NB_FREE_LISTS
] =
108 0x20, 0x80, 0x200, ~0UL
118 typedef struct tagSUBHEAP
120 DWORD size
; /* Size of the whole sub-heap */
121 DWORD commitSize
; /* Committed size of the sub-heap */
122 DWORD headerSize
; /* Size of the heap header */
123 struct tagSUBHEAP
*next
; /* Next sub-heap */
124 struct tagHEAP
*heap
; /* Main heap structure */
125 DWORD magic
; /* Magic number */
130 #define SUBHEAP_MAGIC ((DWORD)('S' | ('U'<<8) | ('B'<<16) | ('H'<<24)))
132 typedef struct tagHEAP
134 SUBHEAP subheap
; /* First sub-heap */
135 struct list entry
; /* Entry in process heap list */
136 RTL_CRITICAL_SECTION critSection
; /* Critical section for serialization */
137 FREE_LIST_ENTRY freeList
[HEAP_NB_FREE_LISTS
]; /* Free lists */
138 DWORD flags
; /* Heap flags */
139 DWORD magic
; /* Magic number */
140 PRTL_HEAP_COMMIT_ROUTINE commitRoutine
;
143 #define HEAP_MAGIC ((DWORD)('H' | ('E'<<8) | ('A'<<16) | ('P'<<24)))
145 #define HEAP_DEF_SIZE 0x110000 /* Default heap size = 1Mb + 64Kb */
146 #define COMMIT_MASK 0xffff /* bitmask for commit/decommit granularity */
148 static HEAP
*processHeap
; /* main process heap */
150 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, DWORD flags
, LPCVOID block
, BOOL quiet
);
152 /* mark a block of memory as free for debugging purposes */
153 static __inline
void mark_block_free( void *ptr
, SIZE_T size
)
155 if (TRACE_ON(heap
)) memset( ptr
, ARENA_FREE_FILLER
, size
);
156 #ifdef VALGRIND_MAKE_NOACCESS
157 VALGRIND_DISCARD( VALGRIND_MAKE_NOACCESS( ptr
, size
));
161 /* mark a block of memory as initialized for debugging purposes */
162 static __inline
void mark_block_initialized( void *ptr
, SIZE_T size
)
164 #ifdef VALGRIND_MAKE_READABLE
165 VALGRIND_DISCARD( VALGRIND_MAKE_READABLE( ptr
, size
));
169 /* mark a block of memory as uninitialized for debugging purposes */
170 static __inline
void mark_block_uninitialized( void *ptr
, SIZE_T size
)
172 #ifdef VALGRIND_MAKE_WRITABLE
173 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr
, size
));
177 memset( ptr
, ARENA_INUSE_FILLER
, size
);
178 #ifdef VALGRIND_MAKE_WRITABLE
179 /* make it uninitialized to valgrind again */
180 VALGRIND_DISCARD( VALGRIND_MAKE_WRITABLE( ptr
, size
));
185 /* clear contents of a block of memory */
186 static __inline
void clear_block( void *ptr
, SIZE_T size
)
188 mark_block_initialized( ptr
, size
);
189 memset( ptr
, 0, size
);
192 /* locate a free list entry of the appropriate size */
193 /* size is the size of the whole block including the arena header */
194 static __inline
unsigned int get_freelist_index( SIZE_T size
)
198 size
-= sizeof(ARENA_FREE
);
199 for (i
= 0; i
< HEAP_NB_FREE_LISTS
- 1; i
++) if (size
<= HEAP_freeListSizes
[i
]) break;
203 static RTL_CRITICAL_SECTION_DEBUG process_heap_critsect_debug
=
205 0, 0, NULL
, /* will be set later */
206 { &process_heap_critsect_debug
.ProcessLocksList
, &process_heap_critsect_debug
.ProcessLocksList
},
210 /***********************************************************************
213 static void HEAP_Dump( HEAP
*heap
)
219 DPRINTF( "Heap: %p\n", heap
);
220 DPRINTF( "Next: %p Sub-heaps: %p",
221 LIST_ENTRY( heap
->entry
.next
, HEAP
, entry
), &heap
->subheap
);
222 subheap
= &heap
->subheap
;
223 while (subheap
->next
)
225 DPRINTF( " -> %p", subheap
->next
);
226 subheap
= subheap
->next
;
229 DPRINTF( "\nFree lists:\n Block Stat Size Id\n" );
230 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
231 DPRINTF( "%p free %08lx prev=%p next=%p\n",
232 &heap
->freeList
[i
].arena
, HEAP_freeListSizes
[i
],
233 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.prev
, ARENA_FREE
, entry
),
234 LIST_ENTRY( heap
->freeList
[i
].arena
.entry
.next
, ARENA_FREE
, entry
));
236 subheap
= &heap
->subheap
;
239 SIZE_T freeSize
= 0, usedSize
= 0, arenaSize
= subheap
->headerSize
;
240 DPRINTF( "\n\nSub-heap %p: size=%08lx committed=%08lx\n",
241 subheap
, subheap
->size
, subheap
->commitSize
);
243 DPRINTF( "\n Block Stat Size Id\n" );
244 ptr
= (char*)subheap
+ subheap
->headerSize
;
245 while (ptr
< (char *)subheap
+ subheap
->size
)
247 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
249 ARENA_FREE
*pArena
= (ARENA_FREE
*)ptr
;
250 DPRINTF( "%p free %08lx prev=%p next=%p\n",
251 pArena
, pArena
->size
& ARENA_SIZE_MASK
,
252 LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
),
253 LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
) );
254 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
255 arenaSize
+= sizeof(ARENA_FREE
);
256 freeSize
+= pArena
->size
& ARENA_SIZE_MASK
;
258 else if (*(DWORD
*)ptr
& ARENA_FLAG_PREV_FREE
)
260 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
261 DPRINTF( "%p Used %08lx back=%p\n",
262 pArena
, pArena
->size
& ARENA_SIZE_MASK
, *((ARENA_FREE
**)pArena
- 1) );
263 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
264 arenaSize
+= sizeof(ARENA_INUSE
);
265 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
269 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
;
270 DPRINTF( "%p used %08lx\n", pArena
, pArena
->size
& ARENA_SIZE_MASK
);
271 ptr
+= sizeof(*pArena
) + (pArena
->size
& ARENA_SIZE_MASK
);
272 arenaSize
+= sizeof(ARENA_INUSE
);
273 usedSize
+= pArena
->size
& ARENA_SIZE_MASK
;
276 DPRINTF( "\nTotal: Size=%08lx Committed=%08lx Free=%08lx Used=%08lx Arenas=%08lx (%ld%%)\n\n",
277 subheap
->size
, subheap
->commitSize
, freeSize
, usedSize
,
278 arenaSize
, (arenaSize
* 100) / subheap
->size
);
279 subheap
= subheap
->next
;
284 static void HEAP_DumpEntry( LPPROCESS_HEAP_ENTRY entry
)
287 TRACE( "Dumping entry %p\n", entry
);
288 TRACE( "lpData\t\t: %p\n", entry
->lpData
);
289 TRACE( "cbData\t\t: %08lx\n", entry
->cbData
);
290 TRACE( "cbOverhead\t: %08x\n", entry
->cbOverhead
);
291 TRACE( "iRegionIndex\t: %08x\n", entry
->iRegionIndex
);
292 TRACE( "WFlags\t\t: ");
293 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
294 TRACE( "PROCESS_HEAP_REGION ");
295 if (entry
->wFlags
& PROCESS_HEAP_UNCOMMITTED_RANGE
)
296 TRACE( "PROCESS_HEAP_UNCOMMITTED_RANGE ");
297 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
298 TRACE( "PROCESS_HEAP_ENTRY_BUSY ");
299 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
)
300 TRACE( "PROCESS_HEAP_ENTRY_MOVEABLE ");
301 if (entry
->wFlags
& PROCESS_HEAP_ENTRY_DDESHARE
)
302 TRACE( "PROCESS_HEAP_ENTRY_DDESHARE ");
303 rem_flags
= entry
->wFlags
&
304 ~(PROCESS_HEAP_REGION
| PROCESS_HEAP_UNCOMMITTED_RANGE
|
305 PROCESS_HEAP_ENTRY_BUSY
| PROCESS_HEAP_ENTRY_MOVEABLE
|
306 PROCESS_HEAP_ENTRY_DDESHARE
);
308 TRACE( "Unknown %08x", rem_flags
);
310 if ((entry
->wFlags
& PROCESS_HEAP_ENTRY_BUSY
)
311 && (entry
->wFlags
& PROCESS_HEAP_ENTRY_MOVEABLE
))
314 TRACE( "BLOCK->hMem\t\t:%p\n", entry
->Block
.hMem
);
316 if (entry
->wFlags
& PROCESS_HEAP_REGION
)
318 TRACE( "Region.dwCommittedSize\t:%08lx\n",entry
->Region
.dwCommittedSize
);
319 TRACE( "Region.dwUnCommittedSize\t:%08lx\n",entry
->Region
.dwUnCommittedSize
);
320 TRACE( "Region.lpFirstBlock\t:%p\n",entry
->Region
.lpFirstBlock
);
321 TRACE( "Region.lpLastBlock\t:%p\n",entry
->Region
.lpLastBlock
);
326 /***********************************************************************
329 * Pointer to the heap
332 static HEAP
*HEAP_GetPtr(
333 HANDLE heap
/* [in] Handle to the heap */
335 HEAP
*heapPtr
= (HEAP
*)heap
;
336 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
338 ERR("Invalid heap %p, magic:%4s!\n", heap
,heapPtr
->magic
);
339 //KeDumpStackFrames(NULL);
342 if (TRACE_ON(heap
) && !HEAP_IsRealArena( heapPtr
, 0, NULL
, NOISY
))
344 HEAP_Dump( heapPtr
);
352 /***********************************************************************
353 * HEAP_InsertFreeBlock
355 * Insert a free block into the free list.
357 static __inline
void HEAP_InsertFreeBlock( HEAP
*heap
, ARENA_FREE
*pArena
, BOOL last
)
359 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( pArena
->size
+ sizeof(*pArena
) );
362 /* insert at end of free list, i.e. before the next free list entry */
364 if (pEntry
== &heap
->freeList
[HEAP_NB_FREE_LISTS
]) pEntry
= heap
->freeList
;
365 list_add_before( &pEntry
->arena
.entry
, &pArena
->entry
);
369 /* insert at head of free list */
370 list_add_after( &pEntry
->arena
.entry
, &pArena
->entry
);
372 pArena
->size
|= ARENA_FLAG_FREE
;
376 /***********************************************************************
378 * Find the sub-heap containing a given address.
384 static SUBHEAP
*HEAP_FindSubHeap(
385 const HEAP
*heap
, /* [in] Heap pointer */
386 LPCVOID ptr
/* [in] Address */
388 const SUBHEAP
*sub
= &heap
->subheap
;
391 if (((const char *)ptr
>= (const char *)sub
) &&
392 ((const char *)ptr
< (const char *)sub
+ sub
->size
)) return (SUBHEAP
*)sub
;
398 /***********************************************************************
401 * Make sure the heap storage is committed for a given size in the specified arena.
403 static __inline BOOL
HEAP_Commit( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T data_size
)
406 void *ptr
= (char *)(pArena
+ 1) + data_size
+ sizeof(ARENA_FREE
);
407 SIZE_T size
= (char *)ptr
- (char *)subheap
;
408 size
= (size
+ COMMIT_MASK
) & ~COMMIT_MASK
;
409 if (size
> subheap
->size
) size
= subheap
->size
;
410 if (size
<= subheap
->commitSize
) return TRUE
;
411 size
-= subheap
->commitSize
;
412 ptr
= (char *)subheap
+ subheap
->commitSize
;
413 if (subheap
->heap
->commitRoutine
!= NULL
)
415 Status
= subheap
->heap
->commitRoutine(subheap
->heap
, &ptr
, &size
);
419 Status
= ZwAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0,
420 &size
, MEM_COMMIT
, PAGE_READWRITE
);
422 if (!NT_SUCCESS(Status
))
424 WARN("Could not commit %08lx bytes at %p for heap %p\n",
425 size
, ptr
, subheap
->heap
);
428 subheap
->commitSize
+= size
;
433 /***********************************************************************
436 * If possible, decommit the heap storage from (including) 'ptr'.
438 static inline BOOL
HEAP_Decommit( SUBHEAP
*subheap
, void *ptr
)
441 SIZE_T decommit_size
;
442 SIZE_T size
= (char *)ptr
- (char *)subheap
;
444 /* round to next block and add one full block */
445 size
= ((size
+ COMMIT_MASK
) & ~COMMIT_MASK
) + COMMIT_MASK
+ 1;
446 if (size
>= subheap
->commitSize
) return TRUE
;
447 decommit_size
= subheap
->commitSize
- size
;
448 addr
= (char *)subheap
+ size
;
450 if (ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &decommit_size
, MEM_DECOMMIT
))
452 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
453 decommit_size
, (char *)subheap
+ size
, subheap
->heap
);
456 subheap
->commitSize
-= decommit_size
;
461 /***********************************************************************
462 * HEAP_CreateFreeBlock
464 * Create a free block at a specified address. 'size' is the size of the
465 * whole block, including the new arena.
467 static void HEAP_CreateFreeBlock( SUBHEAP
*subheap
, void *ptr
, SIZE_T size
)
473 /* Create a free arena */
474 mark_block_uninitialized( ptr
, sizeof( ARENA_FREE
) );
475 pFree
= (ARENA_FREE
*)ptr
;
476 pFree
->magic
= ARENA_FREE_MAGIC
;
478 /* If debugging, erase the freed block content */
480 pEnd
= (char *)ptr
+ size
;
481 if (pEnd
> (char *)subheap
+ subheap
->commitSize
) pEnd
= (char *)subheap
+ subheap
->commitSize
;
482 if (pEnd
> (char *)(pFree
+ 1)) mark_block_free( pFree
+ 1, pEnd
- (char *)(pFree
+ 1) );
484 /* Check if next block is free also */
486 if (((char *)ptr
+ size
< (char *)subheap
+ subheap
->size
) &&
487 (*(DWORD
*)((char *)ptr
+ size
) & ARENA_FLAG_FREE
))
489 /* Remove the next arena from the free list */
490 ARENA_FREE
*pNext
= (ARENA_FREE
*)((char *)ptr
+ size
);
491 list_remove( &pNext
->entry
);
492 size
+= (pNext
->size
& ARENA_SIZE_MASK
) + sizeof(*pNext
);
493 mark_block_free( pNext
, sizeof(ARENA_FREE
) );
496 /* Set the next block PREV_FREE flag and pointer */
498 last
= ((char *)ptr
+ size
>= (char *)subheap
+ subheap
->size
);
501 DWORD
*pNext
= (DWORD
*)((char *)ptr
+ size
);
502 *pNext
|= ARENA_FLAG_PREV_FREE
;
503 mark_block_initialized( pNext
- 1, sizeof( ARENA_FREE
* ) );
504 *((ARENA_FREE
**)pNext
- 1) = pFree
;
507 /* Last, insert the new block into the free list */
509 pFree
->size
= size
- sizeof(*pFree
);
510 HEAP_InsertFreeBlock( subheap
->heap
, pFree
, last
);
514 /***********************************************************************
515 * HEAP_MakeInUseBlockFree
517 * Turn an in-use block into a free block. Can also decommit the end of
518 * the heap, and possibly even free the sub-heap altogether.
520 static void HEAP_MakeInUseBlockFree( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
)
523 SIZE_T size
= (pArena
->size
& ARENA_SIZE_MASK
) + sizeof(*pArena
);
525 /* Check if we can merge with previous block */
527 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
529 pFree
= *((ARENA_FREE
**)pArena
- 1);
530 size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
531 /* Remove it from the free list */
532 list_remove( &pFree
->entry
);
534 else pFree
= (ARENA_FREE
*)pArena
;
536 /* Create a free block */
538 HEAP_CreateFreeBlock( subheap
, pFree
, size
);
539 size
= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
540 if ((char *)pFree
+ size
< (char *)subheap
+ subheap
->size
)
541 return; /* Not the last block, so nothing more to do */
543 /* Free the whole sub-heap if it's empty and not the original one */
545 if (((char *)pFree
== (char *)subheap
+ subheap
->headerSize
) &&
546 (subheap
!= &subheap
->heap
->subheap
))
549 SUBHEAP
*pPrev
= &subheap
->heap
->subheap
;
550 /* Remove the free block from the list */
551 list_remove( &pFree
->entry
);
552 /* Remove the subheap from the list */
553 while (pPrev
&& (pPrev
->next
!= subheap
)) pPrev
= pPrev
->next
;
554 if (pPrev
) pPrev
->next
= subheap
->next
;
555 /* Free the memory */
557 ZwFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap
, &size
, MEM_RELEASE
);
561 /* Decommit the end of the heap */
564 /***********************************************************************
567 * Shrink an in-use block.
569 static void HEAP_ShrinkBlock(SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T size
)
571 if ((pArena
->size
& ARENA_SIZE_MASK
) >= size
+ HEAP_MIN_SHRINK_SIZE
)
573 HEAP_CreateFreeBlock( subheap
, (char *)(pArena
+ 1) + size
,
574 (pArena
->size
& ARENA_SIZE_MASK
) - size
);
575 /* assign size plus previous arena flags */
576 pArena
->size
= size
| (pArena
->size
& ~ARENA_SIZE_MASK
);
580 /* Turn off PREV_FREE flag in next block */
581 char *pNext
= (char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
);
582 if (pNext
< (char *)subheap
+ subheap
->size
)
583 *(DWORD
*)pNext
&= ~ARENA_FLAG_PREV_FREE
;
587 /***********************************************************************
590 static BOOL
HEAP_InitSubHeap( HEAP
*heap
, LPVOID address
, DWORD flags
,
591 SIZE_T commitSize
, SIZE_T totalSize
,
592 PRTL_HEAP_PARAMETERS Parameters
)
595 FREE_LIST_ENTRY
*pEntry
;
599 if (!address
&& ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0,
600 &commitSize
, MEM_COMMIT
, PAGE_READWRITE
))
602 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize
, address
);
606 /* Fill the sub-heap structure */
608 subheap
= (SUBHEAP
*)address
;
609 subheap
->heap
= heap
;
610 subheap
->size
= totalSize
;
611 subheap
->commitSize
= commitSize
;
612 subheap
->magic
= SUBHEAP_MAGIC
;
614 if ( subheap
!= (SUBHEAP
*)heap
)
616 /* If this is a secondary subheap, insert it into list */
618 subheap
->headerSize
= ROUND_SIZE( sizeof(SUBHEAP
) );
619 subheap
->next
= heap
->subheap
.next
;
620 heap
->subheap
.next
= subheap
;
624 /* If this is a primary subheap, initialize main heap */
626 subheap
->headerSize
= ROUND_SIZE( sizeof(HEAP
) );
627 subheap
->next
= NULL
;
629 heap
->magic
= HEAP_MAGIC
;
631 heap
->commitRoutine
= Parameters
->CommitRoutine
;
633 heap
->commitRoutine
= NULL
;
635 /* Build the free lists */
637 list_init( &heap
->freeList
[0].arena
.entry
);
638 for (i
= 0, pEntry
= heap
->freeList
; i
< HEAP_NB_FREE_LISTS
; i
++, pEntry
++)
640 pEntry
->arena
.size
= 0 | ARENA_FLAG_FREE
;
641 pEntry
->arena
.magic
= ARENA_FREE_MAGIC
;
642 if (i
) list_add_after( &pEntry
[-1].arena
.entry
, &pEntry
->arena
.entry
);
645 /* Initialize critical section */
647 if (RtlpGetMode() == UserMode
)
649 if (!processHeap
) /* do it by hand to avoid memory allocations */
651 heap
->critSection
.DebugInfo
= &process_heap_critsect_debug
;
652 heap
->critSection
.LockCount
= -1;
653 heap
->critSection
.RecursionCount
= 0;
654 heap
->critSection
.OwningThread
= 0;
655 heap
->critSection
.LockSemaphore
= 0;
656 heap
->critSection
.SpinCount
= 0;
657 process_heap_critsect_debug
.CriticalSection
= &heap
->critSection
;
659 else RtlInitializeHeapLock( &heap
->critSection
);
664 if (heap
->commitRoutine
)
666 if (subheap
!= (SUBHEAP
*)heap
)
668 Status
= heap
->commitRoutine(heap
, &address
, &commitSize
);
672 /* the caller is responsible for committing the first page! */
673 Status
= STATUS_SUCCESS
;
678 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
683 PAGE_EXECUTE_READWRITE
);
685 if (!NT_SUCCESS(Status
))
687 DPRINT("Could not commit %08lx bytes for sub-heap %p\n",
688 commitSize
, address
);
692 /* Create the first free block */
694 HEAP_CreateFreeBlock( subheap
, (LPBYTE
)subheap
+ subheap
->headerSize
,
695 subheap
->size
- subheap
->headerSize
);
700 /***********************************************************************
703 * Create a sub-heap of the given size.
704 * If heap == NULL, creates a main heap.
706 static SUBHEAP
*HEAP_CreateSubHeap( HEAP
*heap
, void *base
, DWORD flags
,
707 SIZE_T commitSize
, SIZE_T totalSize
,
708 IN PRTL_HEAP_PARAMETERS Parameters
)
710 LPVOID address
= base
;
712 /* round-up sizes on a 64K boundary */
713 totalSize
= (totalSize
+ 0xffff) & 0xffff0000;
714 commitSize
= (commitSize
+ 0xffff) & 0xffff0000;
715 if (!commitSize
) commitSize
= 0x10000;
716 if (totalSize
< commitSize
) totalSize
= commitSize
;
720 /* allocate the memory block */
721 if (ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0, &totalSize
,
722 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
))
724 WARN("Could not allocate %08lx bytes\n", totalSize
);
729 /* Initialize subheap */
731 if (!HEAP_InitSubHeap( heap
? heap
: (HEAP
*)address
,
732 address
, flags
, commitSize
, totalSize
, Parameters
))
735 if (!base
) ZwFreeVirtualMemory( NtCurrentProcess(), &address
, &size
, MEM_RELEASE
);
739 return (SUBHEAP
*)address
;
743 /***********************************************************************
746 * Find a free block at least as large as the requested size, and make sure
747 * the requested size is committed.
749 static ARENA_FREE
*HEAP_FindFreeBlock( HEAP
*heap
, SIZE_T size
,
750 SUBHEAP
**ppSubHeap
)
754 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( size
+ sizeof(ARENA_INUSE
) );
756 /* Find a suitable free list, and in it find a block large enough */
758 ptr
= &pEntry
->arena
.entry
;
759 while ((ptr
= list_next( &heap
->freeList
[0].arena
.entry
, ptr
)))
761 ARENA_FREE
*pArena
= LIST_ENTRY( ptr
, ARENA_FREE
, entry
);
762 SIZE_T arena_size
= (pArena
->size
& ARENA_SIZE_MASK
) +
763 sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
764 if (arena_size
>= size
)
766 subheap
= HEAP_FindSubHeap( heap
, pArena
);
767 if (!HEAP_Commit( subheap
, (ARENA_INUSE
*)pArena
, size
)) return NULL
;
768 *ppSubHeap
= subheap
;
773 /* If no block was found, attempt to grow the heap */
775 if (!(heap
->flags
& HEAP_GROWABLE
))
777 ERR("Not enough space in heap %p for %08lx bytes\n", heap
, size
);
780 /* make sure that we have a big enough size *committed* to fit another
781 * last free arena in !
782 * So just one heap struct, one first free arena which will eventually
783 * get used, and a second free arena that might get assigned all remaining
784 * free space in HEAP_ShrinkBlock() */
785 size
+= ROUND_SIZE(sizeof(SUBHEAP
)) + sizeof(ARENA_INUSE
) + sizeof(ARENA_FREE
);
786 if (!(subheap
= HEAP_CreateSubHeap( heap
, NULL
, heap
->flags
, size
,
787 max( HEAP_DEF_SIZE
, size
), NULL
)))
790 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
791 subheap
, size
, heap
);
793 *ppSubHeap
= subheap
;
794 return (ARENA_FREE
*)(subheap
+ 1);
797 /***********************************************************************
798 * HEAP_IsValidArenaPtr
800 * Check that the pointer is inside the range possible for arenas.
802 static BOOL
HEAP_IsValidArenaPtr( const HEAP
*heap
, const void *ptr
)
805 const SUBHEAP
*subheap
= HEAP_FindSubHeap( heap
, ptr
);
806 if (!subheap
) return FALSE
;
807 if ((const char *)ptr
>= (const char *)subheap
+ subheap
->headerSize
) return TRUE
;
808 if (subheap
!= &heap
->subheap
) return FALSE
;
809 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
810 if (ptr
== (const void *)&heap
->freeList
[i
].arena
) return TRUE
;
815 /***********************************************************************
816 * HEAP_ValidateFreeArena
818 static BOOL
HEAP_ValidateFreeArena( SUBHEAP
*subheap
, ARENA_FREE
*pArena
)
820 ARENA_FREE
*prev
, *next
;
821 char *heapEnd
= (char *)subheap
+ subheap
->size
;
823 /* Check for unaligned pointers */
824 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= 0 )
826 ERR("Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
830 /* Check magic number */
831 if (pArena
->magic
!= ARENA_FREE_MAGIC
)
833 ERR("Heap %p: invalid free arena magic for %p\n", subheap
->heap
, pArena
);
836 /* Check size flags */
837 if (!(pArena
->size
& ARENA_FLAG_FREE
) ||
838 (pArena
->size
& ARENA_FLAG_PREV_FREE
))
840 ERR("Heap %p: bad flags %08lx for free arena %p\n",
841 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
844 /* Check arena size */
845 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
847 ERR("Heap %p: bad size %08lx for free arena %p\n",
848 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
851 /* Check that next pointer is valid */
852 next
= LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
);
853 if (!HEAP_IsValidArenaPtr( subheap
->heap
, next
))
855 ERR("Heap %p: bad next ptr %p for arena %p\n",
856 subheap
->heap
, next
, pArena
);
859 /* Check that next arena is free */
860 if (!(next
->size
& ARENA_FLAG_FREE
) || (next
->magic
!= ARENA_FREE_MAGIC
))
862 ERR("Heap %p: next arena %p invalid for %p\n",
863 subheap
->heap
, next
, pArena
);
866 /* Check that prev pointer is valid */
867 prev
= LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
);
868 if (!HEAP_IsValidArenaPtr( subheap
->heap
, prev
))
870 ERR("Heap %p: bad prev ptr %p for arena %p\n",
871 subheap
->heap
, prev
, pArena
);
874 /* Check that prev arena is free */
875 if (!(prev
->size
& ARENA_FLAG_FREE
) || (prev
->magic
!= ARENA_FREE_MAGIC
))
877 /* this often means that the prev arena got overwritten
878 * by a memory write before that prev arena */
879 ERR("Heap %p: prev arena %p invalid for %p\n",
880 subheap
->heap
, prev
, pArena
);
883 /* Check that next block has PREV_FREE flag */
884 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
)
886 if (!(*(DWORD
*)((char *)(pArena
+ 1) +
887 (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
889 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
890 subheap
->heap
, pArena
);
893 /* Check next block back pointer */
894 if (*((ARENA_FREE
**)((char *)(pArena
+ 1) +
895 (pArena
->size
& ARENA_SIZE_MASK
)) - 1) != pArena
)
897 ERR("Heap %p: arena %p has wrong back ptr %p\n",
898 subheap
->heap
, pArena
,
899 *((ARENA_FREE
**)((char *)(pArena
+1) + (pArena
->size
& ARENA_SIZE_MASK
)) - 1));
906 /***********************************************************************
907 * HEAP_ValidateInUseArena
909 static BOOL
HEAP_ValidateInUseArena( const SUBHEAP
*subheap
, const ARENA_INUSE
*pArena
, BOOL quiet
)
911 const char *heapEnd
= (const char *)subheap
+ subheap
->size
;
913 /* Check for unaligned pointers */
914 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= 0 )
916 if ( quiet
== NOISY
)
918 ERR( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
919 if ( TRACE_ON(heap
) )
920 HEAP_Dump( subheap
->heap
);
922 else if ( WARN_ON(heap
) )
924 WARN( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
925 if ( TRACE_ON(heap
) )
926 HEAP_Dump( subheap
->heap
);
931 /* Check magic number */
932 if (pArena
->magic
!= ARENA_INUSE_MAGIC
)
934 if (quiet
== NOISY
) {
935 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
937 HEAP_Dump( subheap
->heap
);
938 } else if (WARN_ON(heap
)) {
939 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
941 HEAP_Dump( subheap
->heap
);
945 /* Check size flags */
946 if (pArena
->size
& ARENA_FLAG_FREE
)
948 ERR("Heap %p: bad flags %08lx for in-use arena %p\n",
949 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
952 /* Check arena size */
953 if ((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
955 ERR("Heap %p: bad size %08lx for in-use arena %p\n",
956 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
959 /* Check next arena PREV_FREE flag */
960 if (((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
) &&
961 (*(const DWORD
*)((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
963 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
964 subheap
->heap
, pArena
);
967 /* Check prev free arena */
968 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
970 const ARENA_FREE
*pPrev
= *((const ARENA_FREE
* const*)pArena
- 1);
971 /* Check prev pointer */
972 if (!HEAP_IsValidArenaPtr( subheap
->heap
, pPrev
))
974 ERR("Heap %p: bad back ptr %p for arena %p\n",
975 subheap
->heap
, pPrev
, pArena
);
978 /* Check that prev arena is free */
979 if (!(pPrev
->size
& ARENA_FLAG_FREE
) ||
980 (pPrev
->magic
!= ARENA_FREE_MAGIC
))
982 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
983 subheap
->heap
, pPrev
, pArena
);
986 /* Check that prev arena is really the previous block */
987 if ((const char *)(pPrev
+ 1) + (pPrev
->size
& ARENA_SIZE_MASK
) != (const char *)pArena
)
989 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
990 subheap
->heap
, pPrev
, pArena
);
997 /***********************************************************************
998 * HEAP_IsRealArena [Internal]
999 * Validates a block is a valid arena.
1005 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, /* [in] ptr to the heap */
1006 DWORD flags
, /* [in] Bit flags that control access during operation */
1007 LPCVOID block
, /* [in] Optional pointer to memory block to validate */
1008 BOOL quiet
) /* [in] Flag - if true, HEAP_ValidateInUseArena
1009 * does not complain */
1014 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
1016 ERR("Invalid heap %p!\n", heapPtr
);
1020 flags
&= HEAP_NO_SERIALIZE
;
1021 flags
|= heapPtr
->flags
;
1022 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1023 if (!(flags
& HEAP_NO_SERIALIZE
))
1024 RtlEnterHeapLock( &heapPtr
->critSection
);
1028 /* Only check this single memory block */
1030 if (!(subheap
= HEAP_FindSubHeap( heapPtr
, block
)) ||
1031 ((const char *)block
< (char *)subheap
+ subheap
->headerSize
1032 + sizeof(ARENA_INUSE
)))
1035 ERR("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1036 else if (WARN_ON(heap
))
1037 WARN("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1040 ret
= HEAP_ValidateInUseArena( subheap
, (const ARENA_INUSE
*)block
- 1, quiet
);
1042 if (!(flags
& HEAP_NO_SERIALIZE
))
1043 RtlLeaveHeapLock( &heapPtr
->critSection
);
1047 subheap
= &heapPtr
->subheap
;
1048 while (subheap
&& ret
)
1050 char *ptr
= (char *)subheap
+ subheap
->headerSize
;
1051 while (ptr
< (char *)subheap
+ subheap
->size
)
1053 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
1055 if (!HEAP_ValidateFreeArena( subheap
, (ARENA_FREE
*)ptr
)) {
1059 ptr
+= sizeof(ARENA_FREE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1063 if (!HEAP_ValidateInUseArena( subheap
, (ARENA_INUSE
*)ptr
, NOISY
)) {
1067 ptr
+= sizeof(ARENA_INUSE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1070 subheap
= subheap
->next
;
1073 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1078 /***********************************************************************
1079 * HeapCreate (KERNEL32.336)
1081 * Handle of heap: Success
1087 RtlCreateHeap(ULONG flags
,
1092 PRTL_HEAP_PARAMETERS Parameters
)
1096 /* Allocate the heap block */
1100 totalSize
= HEAP_DEF_SIZE
;
1101 flags
|= HEAP_GROWABLE
;
1103 if (!(subheap
= HEAP_CreateSubHeap( NULL
, addr
, flags
, commitSize
, totalSize
, Parameters
))) return 0;
1105 if (RtlpGetMode() == UserMode
)
1107 /* link it into the per-process heap list */
1110 HEAP
*heapPtr
= subheap
->heap
;
1111 RtlEnterHeapLock( &processHeap
->critSection
);
1112 list_add_head( &processHeap
->entry
, &heapPtr
->entry
);
1113 RtlLeaveHeapLock( &processHeap
->critSection
);
1117 processHeap
= subheap
->heap
; /* assume the first heap we create is the process main heap */
1118 list_init( &processHeap
->entry
);
1122 return (HANDLE
)subheap
;
1125 /***********************************************************************
1126 * HeapDestroy (KERNEL32.337)
1134 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1135 * Failure: The Heap handle, if heap is the process heap.
1138 RtlDestroyHeap(HANDLE heap
) /* [in] Handle of heap */
1140 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1143 DPRINT("%p\n", heap
);
1147 if (RtlpGetMode() == UserMode
)
1149 if (heap
== NtCurrentPeb()->ProcessHeap
)
1150 return heap
; /* cannot delete the main process heap */
1152 /* remove it from the per-process list */
1153 RtlEnterHeapLock( &processHeap
->critSection
);
1154 list_remove( &heapPtr
->entry
);
1155 RtlLeaveHeapLock( &processHeap
->critSection
);
1158 RtlDeleteHeapLock( &heapPtr
->critSection
);
1159 subheap
= &heapPtr
->subheap
;
1162 SUBHEAP
*next
= subheap
->next
;
1164 void *addr
= subheap
;
1165 ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &size
, MEM_RELEASE
);
1168 return (HANDLE
)NULL
;
1172 /***********************************************************************
1173 * HeapAlloc (KERNEL32.334)
1175 * Pointer to allocated memory block
1177 * 0x7d030f60--invalid flags in RtlHeapAllocate
1181 RtlAllocateHeap(HANDLE heap
, /* [in] Handle of private heap block */
1182 ULONG flags
, /* [in] Heap allocation control flags */
1183 ULONG size
) /* [in] Number of bytes to allocate */
1186 ARENA_INUSE
*pInUse
;
1188 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1189 SIZE_T rounded_size
;
1191 /* Validate the parameters */
1195 if (flags
& HEAP_GENERATE_EXCEPTIONS
)
1196 RtlRaiseStatus( STATUS_NO_MEMORY
);
1199 //flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1200 flags
|= heapPtr
->flags
;
1201 rounded_size
= ROUND_SIZE(size
);
1202 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1204 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1205 /* Locate a suitable free block */
1207 /* Locate a suitable free block */
1209 if (!(pArena
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &subheap
)))
1211 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1212 heap
, flags
, size
);
1213 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1214 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1218 /* Remove the arena from the free list */
1220 list_remove( &pArena
->entry
);
1222 /* Build the in-use arena */
1224 pInUse
= (ARENA_INUSE
*)pArena
;
1226 /* in-use arena is smaller than free arena,
1227 * so we have to add the difference to the size */
1228 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
) + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1229 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1231 /* Save user flags */
1232 subheap
->UserFlags
= flags
& HEAP_SETTABLE_USER_FLAGS
;
1234 /* Shrink the block */
1236 HEAP_ShrinkBlock( subheap
, pInUse
, rounded_size
);
1237 pInUse
->unused_bytes
= (pInUse
->size
& ARENA_SIZE_MASK
) - size
;
1239 if (flags
& HEAP_ZERO_MEMORY
)
1240 clear_block( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1242 mark_block_uninitialized( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1244 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1246 TRACE("(%p,%08lx,%08lx): returning %p\n", heap
, flags
, size
, pInUse
+ 1 );
1247 return (LPVOID
)(pInUse
+ 1);
1251 /***********************************************************************
1252 * HeapFree (KERNEL32.338)
1259 BOOLEAN NTAPI
RtlFreeHeap(
1260 HANDLE heap
, /* [in] Handle of heap */
1261 ULONG flags
, /* [in] Heap freeing flags */
1262 PVOID ptr
/* [in] Address of memory to free */
1265 ARENA_INUSE
*pInUse
;
1269 /* Validate the parameters */
1271 if (!ptr
) return TRUE
; /* freeing a NULL ptr isn't an error in Win2k */
1273 heapPtr
= HEAP_GetPtr( heap
);
1276 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1280 flags
&= HEAP_NO_SERIALIZE
;
1281 flags
|= heapPtr
->flags
;
1282 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1283 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1285 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1286 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1287 TRACE("(%p,%08lx,%p): returning FALSE\n", heap
, flags
, ptr
);
1291 /* Turn the block into a free block */
1293 pInUse
= (ARENA_INUSE
*)ptr
- 1;
1294 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1295 HEAP_MakeInUseBlockFree( subheap
, pInUse
);
1297 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1299 TRACE("(%p,%08lx,%p): returning TRUE\n", heap
, flags
, ptr
);
1304 /***********************************************************************
1307 * Heap [in] Handle of heap block
1308 * Flags [in] Heap reallocation flags
1309 * Ptr, [in] Address of memory to reallocate
1310 * Size [in] Number of bytes to reallocate
1313 * Pointer to reallocated memory block
1315 * 0x7d030f60--invalid flags in RtlHeapAllocate
1318 PVOID NTAPI
RtlReAllocateHeap(
1325 ARENA_INUSE
*pArena
;
1328 SIZE_T oldSize
, rounded_size
;
1330 if (!ptr
) return NULL
;
1331 if (!(heapPtr
= HEAP_GetPtr( heap
)))
1333 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1337 /* Validate the parameters */
1339 //Flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1340 // HEAP_REALLOC_IN_PLACE_ONLY;
1341 flags
|= heapPtr
->flags
;
1342 rounded_size
= ROUND_SIZE(size
);
1343 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1345 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1346 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1348 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1349 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1350 TRACE("(%p,%08lx,%p,%08lx): returning NULL\n", heap
, flags
, ptr
, size
);
1354 pArena
= (ARENA_INUSE
*)ptr
- 1;
1355 subheap
= HEAP_FindSubHeap( heapPtr
, pArena
);
1356 oldSize
= (pArena
->size
& ARENA_SIZE_MASK
);
1357 if (rounded_size
> oldSize
)
1359 char *pNext
= (char *)(pArena
+ 1) + oldSize
;
1360 if ((pNext
< (char *)subheap
+ subheap
->size
) &&
1361 (*(DWORD
*)pNext
& ARENA_FLAG_FREE
) &&
1362 (oldSize
+ (*(DWORD
*)pNext
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
) >= rounded_size
))
1364 /* The next block is free and large enough */
1365 ARENA_FREE
*pFree
= (ARENA_FREE
*)pNext
;
1366 list_remove( &pFree
->entry
);
1367 pArena
->size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(*pFree
);
1368 if (!HEAP_Commit( subheap
, pArena
, rounded_size
))
1370 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1371 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1372 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1375 HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
);
1377 else /* Do it the hard way */
1380 ARENA_INUSE
*pInUse
;
1381 SUBHEAP
*newsubheap
;
1383 if ((flags
& HEAP_REALLOC_IN_PLACE_ONLY
) ||
1384 !(pNew
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &newsubheap
)))
1386 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1387 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1388 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1392 /* Build the in-use arena */
1394 list_remove( &pNew
->entry
);
1395 pInUse
= (ARENA_INUSE
*)pNew
;
1396 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
)
1397 + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1398 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1399 HEAP_ShrinkBlock( newsubheap
, pInUse
, rounded_size
);
1400 mark_block_initialized( pInUse
+ 1, oldSize
);
1401 memcpy( pInUse
+ 1, pArena
+ 1, oldSize
);
1403 /* Free the previous block */
1405 HEAP_MakeInUseBlockFree( subheap
, pArena
);
1406 subheap
= newsubheap
;
1410 else HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
); /* Shrink the block */
1412 pArena
->unused_bytes
= (pArena
->size
& ARENA_SIZE_MASK
) - size
;
1414 /* Clear the extra bytes if needed */
1416 if (rounded_size
> oldSize
)
1418 if (flags
& HEAP_ZERO_MEMORY
)
1419 clear_block( (char *)(pArena
+ 1) + oldSize
,
1420 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1422 mark_block_uninitialized( (char *)(pArena
+ 1) + oldSize
,
1423 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1426 /* Return the new arena */
1428 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1430 TRACE("(%p,%08lx,%p,%08lx): returning %p\n", heap
, flags
, ptr
, size
, pArena
+ 1 );
1431 return (LPVOID
)(pArena
+ 1);
1435 /***********************************************************************
1441 RtlCompactHeap(HANDLE Heap
,
1449 /***********************************************************************
1451 * Attempts to acquire the critical section object for a specified heap.
1454 * Heap [in] Handle of heap to lock for exclusive access
1463 RtlLockHeap(IN HANDLE Heap
)
1465 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1468 RtlEnterHeapLock( &heapPtr
->critSection
);
1473 /***********************************************************************
1475 * Releases ownership of the critical section object.
1478 * Heap [in] Handle to the heap to unlock
1487 RtlUnlockHeap(HANDLE Heap
)
1489 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1492 RtlLeaveHeapLock( &heapPtr
->critSection
);
1497 /***********************************************************************
1500 * Heap [in] Handle of heap
1501 * Flags [in] Heap size control flags
1502 * Ptr [in] Address of memory to return size for
1505 * Size in bytes of allocated memory
1506 * 0xffffffff: Failure
1518 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1522 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1525 flags
&= HEAP_NO_SERIALIZE
;
1526 flags
|= heapPtr
->flags
;
1527 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1528 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1530 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1535 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
- 1;
1536 ret
= (pArena
->size
& ARENA_SIZE_MASK
) - pArena
->unused_bytes
;
1538 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1540 TRACE("(%p,%08lx,%p): returning %08lx\n", heap
, flags
, ptr
, ret
);
1545 /***********************************************************************
1547 * Validates a specified heap.
1550 * Heap [in] Handle to the heap
1551 * Flags [in] Bit flags that control access during operation
1552 * Block [in] Optional pointer to memory block to validate
1563 BOOLEAN NTAPI
RtlValidateHeap(
1569 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1572 return HEAP_IsRealArena( heapPtr
, Flags
, Block
, QUIET
);
1576 RtlInitializeHeapManager(VOID
)
1580 Peb
= NtCurrentPeb();
1582 Peb
->NumberOfHeaps
= 0;
1583 Peb
->MaximumNumberOfHeaps
= -1; /* no limit */
1584 Peb
->ProcessHeaps
= NULL
;
1586 //RtlInitializeHeapLock(&RtlpProcessHeapsListLock);
1594 RtlEnumProcessHeaps(PHEAP_ENUMERATION_ROUTINE HeapEnumerationRoutine
,
1597 NTSTATUS Status
= STATUS_SUCCESS
;
1599 struct list
*ptr
=NULL
;
1600 RtlEnterHeapLock(&processHeap
->critSection
);
1601 Status
=HeapEnumerationRoutine(processHeap
,lParam
);
1603 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1605 if (!NT_SUCCESS(Status
)) break;
1606 Status
= HeapEnumerationRoutine(ptr
,lParam
);
1609 RtlLeaveHeapLock(&processHeap
->critSection
);
1619 RtlGetProcessHeaps(ULONG count
,
1622 ULONG total
= 1; /* main heap */
1625 RtlEnterHeapLock( &processHeap
->critSection
);
1626 LIST_FOR_EACH( ptr
, &processHeap
->entry
) total
++;
1627 //if (total <= count)
1629 *(heaps
++) = processHeap
;
1631 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1633 if (i
>= count
) break;
1635 *(heaps
++) = LIST_ENTRY( ptr
, HEAP
, entry
);
1638 RtlLeaveHeapLock( &processHeap
->critSection
);
1647 RtlValidateProcessHeaps(VOID
)
1649 BOOLEAN Result
= TRUE
;
1652 RtlEnterHeapLock( &processHeap
->critSection
);
1654 for (pptr
= (HEAP
**)&NtCurrentPeb()->ProcessHeaps
; *pptr
; pptr
++)
1656 if (!RtlValidateHeap(*pptr
, 0, NULL
))
1663 RtlLeaveHeapLock( &processHeap
->critSection
);
1673 IN PVOID HeapHandle
,
1686 RtlSetUserValueHeap(IN PVOID HeapHandle
,
1688 IN PVOID BaseAddress
,
1691 HEAP
*heapPtr
= HEAP_GetPtr(HeapHandle
);
1692 ARENA_INUSE
*pInUse
;
1695 /* Get the subheap */
1696 pInUse
= (ARENA_INUSE
*)BaseAddress
- 1;
1697 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1700 subheap
->UserValue
= UserValue
;
1709 RtlGetUserInfoHeap(IN PVOID HeapHandle
,
1711 IN PVOID BaseAddress
,
1712 OUT PVOID
*UserValue
,
1713 OUT PULONG UserFlags
)
1715 HEAP
*heapPtr
= HEAP_GetPtr(HeapHandle
);
1716 ARENA_INUSE
*pInUse
;
1719 /* Get the subheap */
1720 pInUse
= (ARENA_INUSE
*)BaseAddress
- 1;
1721 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1724 DPRINT1("V/F: %lx %p\n", subheap
->UserValue
, subheap
->UserFlags
);
1725 if (UserValue
) *UserValue
= subheap
->UserValue
;
1726 if (UserFlags
) *UserFlags
= subheap
->UserFlags
;
1735 RtlUsageHeap(IN HANDLE Heap
,
1737 OUT PRTL_HEAP_USAGE Usage
)
1741 return STATUS_NOT_IMPLEMENTED
;
1746 RtlQueryTagHeap(IN PVOID HeapHandle
,
1749 IN BOOLEAN ResetCounters
,
1750 OUT PRTL_HEAP_TAG_INFO HeapTagInfo
)
1759 RtlExtendHeap(IN HANDLE Heap
,
1771 RtlCreateTagHeap(IN HANDLE HeapHandle
,
1774 IN PWSTR TagSubName
)