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!\n", heap
);
341 if (TRACE_ON(heap
) && !HEAP_IsRealArena( heapPtr
, 0, NULL
, NOISY
))
343 HEAP_Dump( heapPtr
);
351 /***********************************************************************
352 * HEAP_InsertFreeBlock
354 * Insert a free block into the free list.
356 static __inline
void HEAP_InsertFreeBlock( HEAP
*heap
, ARENA_FREE
*pArena
, BOOL last
)
358 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( pArena
->size
+ sizeof(*pArena
) );
361 /* insert at end of free list, i.e. before the next free list entry */
363 if (pEntry
== &heap
->freeList
[HEAP_NB_FREE_LISTS
]) pEntry
= heap
->freeList
;
364 list_add_before( &pEntry
->arena
.entry
, &pArena
->entry
);
368 /* insert at head of free list */
369 list_add_after( &pEntry
->arena
.entry
, &pArena
->entry
);
371 pArena
->size
|= ARENA_FLAG_FREE
;
375 /***********************************************************************
377 * Find the sub-heap containing a given address.
383 static SUBHEAP
*HEAP_FindSubHeap(
384 const HEAP
*heap
, /* [in] Heap pointer */
385 LPCVOID ptr
/* [in] Address */
387 const SUBHEAP
*sub
= &heap
->subheap
;
390 if (((const char *)ptr
>= (const char *)sub
) &&
391 ((const char *)ptr
< (const char *)sub
+ sub
->size
)) return (SUBHEAP
*)sub
;
397 /***********************************************************************
400 * Make sure the heap storage is committed for a given size in the specified arena.
402 static __inline BOOL
HEAP_Commit( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T data_size
)
405 void *ptr
= (char *)(pArena
+ 1) + data_size
+ sizeof(ARENA_FREE
);
406 SIZE_T size
= (char *)ptr
- (char *)subheap
;
407 size
= (size
+ COMMIT_MASK
) & ~COMMIT_MASK
;
408 if (size
> subheap
->size
) size
= subheap
->size
;
409 if (size
<= subheap
->commitSize
) return TRUE
;
410 size
-= subheap
->commitSize
;
411 ptr
= (char *)subheap
+ subheap
->commitSize
;
412 if (subheap
->heap
->commitRoutine
!= NULL
)
414 Status
= subheap
->heap
->commitRoutine(subheap
->heap
, &ptr
, &size
);
418 Status
= ZwAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0,
419 &size
, MEM_COMMIT
, PAGE_READWRITE
);
421 if (!NT_SUCCESS(Status
))
423 WARN("Could not commit %08lx bytes at %p for heap %p\n",
424 size
, ptr
, subheap
->heap
);
427 subheap
->commitSize
+= size
;
432 /***********************************************************************
435 * If possible, decommit the heap storage from (including) 'ptr'.
437 static inline BOOL
HEAP_Decommit( SUBHEAP
*subheap
, void *ptr
)
440 SIZE_T decommit_size
;
441 SIZE_T size
= (char *)ptr
- (char *)subheap
;
443 /* round to next block and add one full block */
444 size
= ((size
+ COMMIT_MASK
) & ~COMMIT_MASK
) + COMMIT_MASK
+ 1;
445 if (size
>= subheap
->commitSize
) return TRUE
;
446 decommit_size
= subheap
->commitSize
- size
;
447 addr
= (char *)subheap
+ size
;
449 if (ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &decommit_size
, MEM_DECOMMIT
))
451 WARN("Could not decommit %08lx bytes at %p for heap %p\n",
452 decommit_size
, (char *)subheap
+ size
, subheap
->heap
);
455 subheap
->commitSize
-= decommit_size
;
460 /***********************************************************************
461 * HEAP_CreateFreeBlock
463 * Create a free block at a specified address. 'size' is the size of the
464 * whole block, including the new arena.
466 static void HEAP_CreateFreeBlock( SUBHEAP
*subheap
, void *ptr
, SIZE_T size
)
472 /* Create a free arena */
473 mark_block_uninitialized( ptr
, sizeof( ARENA_FREE
) );
474 pFree
= (ARENA_FREE
*)ptr
;
475 pFree
->magic
= ARENA_FREE_MAGIC
;
477 /* If debugging, erase the freed block content */
479 pEnd
= (char *)ptr
+ size
;
480 if (pEnd
> (char *)subheap
+ subheap
->commitSize
) pEnd
= (char *)subheap
+ subheap
->commitSize
;
481 if (pEnd
> (char *)(pFree
+ 1)) mark_block_free( pFree
+ 1, pEnd
- (char *)(pFree
+ 1) );
483 /* Check if next block is free also */
485 if (((char *)ptr
+ size
< (char *)subheap
+ subheap
->size
) &&
486 (*(DWORD
*)((char *)ptr
+ size
) & ARENA_FLAG_FREE
))
488 /* Remove the next arena from the free list */
489 ARENA_FREE
*pNext
= (ARENA_FREE
*)((char *)ptr
+ size
);
490 list_remove( &pNext
->entry
);
491 size
+= (pNext
->size
& ARENA_SIZE_MASK
) + sizeof(*pNext
);
492 mark_block_free( pNext
, sizeof(ARENA_FREE
) );
495 /* Set the next block PREV_FREE flag and pointer */
497 last
= ((char *)ptr
+ size
>= (char *)subheap
+ subheap
->size
);
500 DWORD
*pNext
= (DWORD
*)((char *)ptr
+ size
);
501 *pNext
|= ARENA_FLAG_PREV_FREE
;
502 mark_block_initialized( pNext
- 1, sizeof( ARENA_FREE
* ) );
503 *((ARENA_FREE
**)pNext
- 1) = pFree
;
506 /* Last, insert the new block into the free list */
508 pFree
->size
= size
- sizeof(*pFree
);
509 HEAP_InsertFreeBlock( subheap
->heap
, pFree
, last
);
513 /***********************************************************************
514 * HEAP_MakeInUseBlockFree
516 * Turn an in-use block into a free block. Can also decommit the end of
517 * the heap, and possibly even free the sub-heap altogether.
519 static void HEAP_MakeInUseBlockFree( SUBHEAP
*subheap
, ARENA_INUSE
*pArena
)
522 SIZE_T size
= (pArena
->size
& ARENA_SIZE_MASK
) + sizeof(*pArena
);
524 /* Check if we can merge with previous block */
526 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
528 pFree
= *((ARENA_FREE
**)pArena
- 1);
529 size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
530 /* Remove it from the free list */
531 list_remove( &pFree
->entry
);
533 else pFree
= (ARENA_FREE
*)pArena
;
535 /* Create a free block */
537 HEAP_CreateFreeBlock( subheap
, pFree
, size
);
538 size
= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
);
539 if ((char *)pFree
+ size
< (char *)subheap
+ subheap
->size
)
540 return; /* Not the last block, so nothing more to do */
542 /* Free the whole sub-heap if it's empty and not the original one */
544 if (((char *)pFree
== (char *)subheap
+ subheap
->headerSize
) &&
545 (subheap
!= &subheap
->heap
->subheap
))
548 SUBHEAP
*pPrev
= &subheap
->heap
->subheap
;
549 /* Remove the free block from the list */
550 list_remove( &pFree
->entry
);
551 /* Remove the subheap from the list */
552 while (pPrev
&& (pPrev
->next
!= subheap
)) pPrev
= pPrev
->next
;
553 if (pPrev
) pPrev
->next
= subheap
->next
;
554 /* Free the memory */
556 ZwFreeVirtualMemory( NtCurrentProcess(), (void **)&subheap
, &size
, MEM_RELEASE
);
560 /* Decommit the end of the heap */
563 /***********************************************************************
566 * Shrink an in-use block.
568 static void HEAP_ShrinkBlock(SUBHEAP
*subheap
, ARENA_INUSE
*pArena
, SIZE_T size
)
570 if ((pArena
->size
& ARENA_SIZE_MASK
) >= size
+ HEAP_MIN_SHRINK_SIZE
)
572 HEAP_CreateFreeBlock( subheap
, (char *)(pArena
+ 1) + size
,
573 (pArena
->size
& ARENA_SIZE_MASK
) - size
);
574 /* assign size plus previous arena flags */
575 pArena
->size
= size
| (pArena
->size
& ~ARENA_SIZE_MASK
);
579 /* Turn off PREV_FREE flag in next block */
580 char *pNext
= (char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
);
581 if (pNext
< (char *)subheap
+ subheap
->size
)
582 *(DWORD
*)pNext
&= ~ARENA_FLAG_PREV_FREE
;
586 /***********************************************************************
589 static BOOL
HEAP_InitSubHeap( HEAP
*heap
, LPVOID address
, DWORD flags
,
590 SIZE_T commitSize
, SIZE_T totalSize
,
591 PRTL_HEAP_PARAMETERS Parameters
)
594 FREE_LIST_ENTRY
*pEntry
;
599 if (ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0,
600 &commitSize
, MEM_COMMIT
, PAGE_READWRITE
))
602 WARN("Could not commit %08lx bytes for sub-heap %p\n", commitSize
, address
);
607 /* Fill the sub-heap structure */
609 subheap
= (SUBHEAP
*)address
;
610 subheap
->heap
= heap
;
611 subheap
->size
= totalSize
;
612 subheap
->commitSize
= commitSize
;
613 subheap
->magic
= SUBHEAP_MAGIC
;
615 if ( subheap
!= (SUBHEAP
*)heap
)
617 /* If this is a secondary subheap, insert it into list */
619 subheap
->headerSize
= ROUND_SIZE( sizeof(SUBHEAP
) );
620 subheap
->next
= heap
->subheap
.next
;
621 heap
->subheap
.next
= subheap
;
625 /* If this is a primary subheap, initialize main heap */
627 subheap
->headerSize
= ROUND_SIZE( sizeof(HEAP
) );
628 subheap
->next
= NULL
;
630 heap
->magic
= HEAP_MAGIC
;
632 heap
->commitRoutine
= Parameters
->CommitRoutine
;
634 heap
->commitRoutine
= NULL
;
636 /* Build the free lists */
638 list_init( &heap
->freeList
[0].arena
.entry
);
639 for (i
= 0, pEntry
= heap
->freeList
; i
< HEAP_NB_FREE_LISTS
; i
++, pEntry
++)
641 pEntry
->arena
.size
= 0 | ARENA_FLAG_FREE
;
642 pEntry
->arena
.magic
= ARENA_FREE_MAGIC
;
643 if (i
) list_add_after( &pEntry
[-1].arena
.entry
, &pEntry
->arena
.entry
);
646 /* Initialize critical section */
648 if (RtlpGetMode() == UserMode
)
650 if (!processHeap
) /* do it by hand to avoid memory allocations */
652 heap
->critSection
.DebugInfo
= &process_heap_critsect_debug
;
653 heap
->critSection
.LockCount
= -1;
654 heap
->critSection
.RecursionCount
= 0;
655 heap
->critSection
.OwningThread
= 0;
656 heap
->critSection
.LockSemaphore
= 0;
657 heap
->critSection
.SpinCount
= 0;
658 process_heap_critsect_debug
.CriticalSection
= &heap
->critSection
;
660 else RtlInitializeHeapLock( &heap
->critSection
);
665 if (heap
->commitRoutine
)
667 if (subheap
!= (SUBHEAP
*)heap
)
669 Status
= heap
->commitRoutine(heap
, &address
, &commitSize
);
673 /* the caller is responsible for committing the first page! */
674 Status
= STATUS_SUCCESS
;
679 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
684 PAGE_EXECUTE_READWRITE
);
686 if (!NT_SUCCESS(Status
))
688 DPRINT("Could not commit %08lx bytes for sub-heap %p\n",
689 commitSize
, address
);
693 /* Create the first free block */
695 HEAP_CreateFreeBlock( subheap
, (LPBYTE
)subheap
+ subheap
->headerSize
,
696 subheap
->size
- subheap
->headerSize
);
701 /***********************************************************************
704 * Create a sub-heap of the given size.
705 * If heap == NULL, creates a main heap.
707 static SUBHEAP
*HEAP_CreateSubHeap( HEAP
*heap
, void *base
, DWORD flags
,
708 SIZE_T commitSize
, SIZE_T totalSize
,
709 IN PRTL_HEAP_PARAMETERS Parameters
)
711 LPVOID address
= base
;
713 /* round-up sizes on a 64K boundary */
714 totalSize
= (totalSize
+ 0xffff) & 0xffff0000;
715 commitSize
= (commitSize
+ 0xffff) & 0xffff0000;
716 if (!commitSize
) commitSize
= 0x10000;
717 if (totalSize
< commitSize
) totalSize
= commitSize
;
721 /* allocate the memory block */
722 if (ZwAllocateVirtualMemory( NtCurrentProcess(), &address
, 0, &totalSize
,
723 MEM_RESERVE
| MEM_COMMIT
, PAGE_READWRITE
))
725 WARN("Could not allocate %08lx bytes\n", totalSize
);
730 /* Initialize subheap */
732 if (!HEAP_InitSubHeap( heap
? heap
: (HEAP
*)address
,
733 address
, flags
, commitSize
, totalSize
, Parameters
))
736 if (!base
) ZwFreeVirtualMemory( NtCurrentProcess(), &address
, &size
, MEM_RELEASE
);
740 return (SUBHEAP
*)address
;
744 /***********************************************************************
747 * Find a free block at least as large as the requested size, and make sure
748 * the requested size is committed.
750 static ARENA_FREE
*HEAP_FindFreeBlock( HEAP
*heap
, SIZE_T size
,
751 SUBHEAP
**ppSubHeap
)
755 FREE_LIST_ENTRY
*pEntry
= heap
->freeList
+ get_freelist_index( size
+ sizeof(ARENA_INUSE
) );
757 /* Find a suitable free list, and in it find a block large enough */
759 ptr
= &pEntry
->arena
.entry
;
760 while ((ptr
= list_next( &heap
->freeList
[0].arena
.entry
, ptr
)))
762 ARENA_FREE
*pArena
= LIST_ENTRY( ptr
, ARENA_FREE
, entry
);
763 SIZE_T arena_size
= (pArena
->size
& ARENA_SIZE_MASK
) +
764 sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
765 if (arena_size
>= size
)
767 subheap
= HEAP_FindSubHeap( heap
, pArena
);
768 if (!HEAP_Commit( subheap
, (ARENA_INUSE
*)pArena
, size
)) return NULL
;
769 *ppSubHeap
= subheap
;
774 /* If no block was found, attempt to grow the heap */
776 if (!(heap
->flags
& HEAP_GROWABLE
))
778 WARN("Not enough space in heap %p for %08lx bytes\n", heap
, size
);
781 /* make sure that we have a big enough size *committed* to fit another
782 * last free arena in !
783 * So just one heap struct, one first free arena which will eventually
784 * get used, and a second free arena that might get assigned all remaining
785 * free space in HEAP_ShrinkBlock() */
786 size
+= ROUND_SIZE(sizeof(SUBHEAP
)) + sizeof(ARENA_INUSE
) + sizeof(ARENA_FREE
);
787 if (!(subheap
= HEAP_CreateSubHeap( heap
, NULL
, heap
->flags
, size
,
788 max( HEAP_DEF_SIZE
, size
), NULL
)))
791 TRACE("created new sub-heap %p of %08lx bytes for heap %p\n",
792 subheap
, size
, heap
);
794 *ppSubHeap
= subheap
;
795 return (ARENA_FREE
*)(subheap
+ 1);
798 /***********************************************************************
799 * HEAP_IsValidArenaPtr
801 * Check that the pointer is inside the range possible for arenas.
803 static BOOL
HEAP_IsValidArenaPtr( const HEAP
*heap
, const void *ptr
)
806 const SUBHEAP
*subheap
= HEAP_FindSubHeap( heap
, ptr
);
807 if (!subheap
) return FALSE
;
808 if ((const char *)ptr
>= (const char *)subheap
+ subheap
->headerSize
) return TRUE
;
809 if (subheap
!= &heap
->subheap
) return FALSE
;
810 for (i
= 0; i
< HEAP_NB_FREE_LISTS
; i
++)
811 if (ptr
== (const void *)&heap
->freeList
[i
].arena
) return TRUE
;
816 /***********************************************************************
817 * HEAP_ValidateFreeArena
819 static BOOL
HEAP_ValidateFreeArena( SUBHEAP
*subheap
, ARENA_FREE
*pArena
)
821 ARENA_FREE
*prev
, *next
;
822 char *heapEnd
= (char *)subheap
+ subheap
->size
;
824 /* Check for unaligned pointers */
825 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= 0 )
827 ERR("Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
831 /* Check magic number */
832 if (pArena
->magic
!= ARENA_FREE_MAGIC
)
834 ERR("Heap %p: invalid free arena magic for %p\n", subheap
->heap
, pArena
);
837 /* Check size flags */
838 if (!(pArena
->size
& ARENA_FLAG_FREE
) ||
839 (pArena
->size
& ARENA_FLAG_PREV_FREE
))
841 ERR("Heap %p: bad flags %08lx for free arena %p\n",
842 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
845 /* Check arena size */
846 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
848 ERR("Heap %p: bad size %08lx for free arena %p\n",
849 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
852 /* Check that next pointer is valid */
853 next
= LIST_ENTRY( pArena
->entry
.next
, ARENA_FREE
, entry
);
854 if (!HEAP_IsValidArenaPtr( subheap
->heap
, next
))
856 ERR("Heap %p: bad next ptr %p for arena %p\n",
857 subheap
->heap
, next
, pArena
);
860 /* Check that next arena is free */
861 if (!(next
->size
& ARENA_FLAG_FREE
) || (next
->magic
!= ARENA_FREE_MAGIC
))
863 ERR("Heap %p: next arena %p invalid for %p\n",
864 subheap
->heap
, next
, pArena
);
867 /* Check that prev pointer is valid */
868 prev
= LIST_ENTRY( pArena
->entry
.prev
, ARENA_FREE
, entry
);
869 if (!HEAP_IsValidArenaPtr( subheap
->heap
, prev
))
871 ERR("Heap %p: bad prev ptr %p for arena %p\n",
872 subheap
->heap
, prev
, pArena
);
875 /* Check that prev arena is free */
876 if (!(prev
->size
& ARENA_FLAG_FREE
) || (prev
->magic
!= ARENA_FREE_MAGIC
))
878 /* this often means that the prev arena got overwritten
879 * by a memory write before that prev arena */
880 ERR("Heap %p: prev arena %p invalid for %p\n",
881 subheap
->heap
, prev
, pArena
);
884 /* Check that next block has PREV_FREE flag */
885 if ((char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
)
887 if (!(*(DWORD
*)((char *)(pArena
+ 1) +
888 (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
890 ERR("Heap %p: free arena %p next block has no PREV_FREE flag\n",
891 subheap
->heap
, pArena
);
894 /* Check next block back pointer */
895 if (*((ARENA_FREE
**)((char *)(pArena
+ 1) +
896 (pArena
->size
& ARENA_SIZE_MASK
)) - 1) != pArena
)
898 ERR("Heap %p: arena %p has wrong back ptr %p\n",
899 subheap
->heap
, pArena
,
900 *((ARENA_FREE
**)((char *)(pArena
+1) + (pArena
->size
& ARENA_SIZE_MASK
)) - 1));
907 /***********************************************************************
908 * HEAP_ValidateInUseArena
910 static BOOL
HEAP_ValidateInUseArena( const SUBHEAP
*subheap
, const ARENA_INUSE
*pArena
, BOOL quiet
)
912 const char *heapEnd
= (const char *)subheap
+ subheap
->size
;
914 /* Check for unaligned pointers */
915 if ( (ULONG_PTR
)pArena
% ALIGNMENT
!= 0 )
917 if ( quiet
== NOISY
)
919 ERR( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
920 if ( TRACE_ON(heap
) )
921 HEAP_Dump( subheap
->heap
);
923 else if ( WARN_ON(heap
) )
925 WARN( "Heap %p: unaligned arena pointer %p\n", subheap
->heap
, pArena
);
926 if ( TRACE_ON(heap
) )
927 HEAP_Dump( subheap
->heap
);
932 /* Check magic number */
933 if (pArena
->magic
!= ARENA_INUSE_MAGIC
)
935 if (quiet
== NOISY
) {
936 ERR("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
938 HEAP_Dump( subheap
->heap
);
939 } else if (WARN_ON(heap
)) {
940 WARN("Heap %p: invalid in-use arena magic for %p\n", subheap
->heap
, pArena
);
942 HEAP_Dump( subheap
->heap
);
946 /* Check size flags */
947 if (pArena
->size
& ARENA_FLAG_FREE
)
949 ERR("Heap %p: bad flags %08lx for in-use arena %p\n",
950 subheap
->heap
, pArena
->size
& ~ARENA_SIZE_MASK
, pArena
);
953 /* Check arena size */
954 if ((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) > heapEnd
)
956 ERR("Heap %p: bad size %08lx for in-use arena %p\n",
957 subheap
->heap
, pArena
->size
& ARENA_SIZE_MASK
, pArena
);
960 /* Check next arena PREV_FREE flag */
961 if (((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
) < heapEnd
) &&
962 (*(const DWORD
*)((const char *)(pArena
+ 1) + (pArena
->size
& ARENA_SIZE_MASK
)) & ARENA_FLAG_PREV_FREE
))
964 ERR("Heap %p: in-use arena %p next block has PREV_FREE flag\n",
965 subheap
->heap
, pArena
);
968 /* Check prev free arena */
969 if (pArena
->size
& ARENA_FLAG_PREV_FREE
)
971 const ARENA_FREE
*pPrev
= *((const ARENA_FREE
* const*)pArena
- 1);
972 /* Check prev pointer */
973 if (!HEAP_IsValidArenaPtr( subheap
->heap
, pPrev
))
975 ERR("Heap %p: bad back ptr %p for arena %p\n",
976 subheap
->heap
, pPrev
, pArena
);
979 /* Check that prev arena is free */
980 if (!(pPrev
->size
& ARENA_FLAG_FREE
) ||
981 (pPrev
->magic
!= ARENA_FREE_MAGIC
))
983 ERR("Heap %p: prev arena %p invalid for in-use %p\n",
984 subheap
->heap
, pPrev
, pArena
);
987 /* Check that prev arena is really the previous block */
988 if ((const char *)(pPrev
+ 1) + (pPrev
->size
& ARENA_SIZE_MASK
) != (const char *)pArena
)
990 ERR("Heap %p: prev arena %p is not prev for in-use %p\n",
991 subheap
->heap
, pPrev
, pArena
);
998 /***********************************************************************
999 * HEAP_IsRealArena [Internal]
1000 * Validates a block is a valid arena.
1006 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, /* [in] ptr to the heap */
1007 DWORD flags
, /* [in] Bit flags that control access during operation */
1008 LPCVOID block
, /* [in] Optional pointer to memory block to validate */
1009 BOOL quiet
) /* [in] Flag - if true, HEAP_ValidateInUseArena
1010 * does not complain */
1015 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
1017 ERR("Invalid heap %p!\n", heapPtr
);
1021 flags
&= HEAP_NO_SERIALIZE
;
1022 flags
|= heapPtr
->flags
;
1023 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1024 if (!(flags
& HEAP_NO_SERIALIZE
))
1025 RtlEnterHeapLock( &heapPtr
->critSection
);
1029 /* Only check this single memory block */
1031 if (!(subheap
= HEAP_FindSubHeap( heapPtr
, block
)) ||
1032 ((const char *)block
< (char *)subheap
+ subheap
->headerSize
1033 + sizeof(ARENA_INUSE
)))
1036 ERR("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1037 else if (WARN_ON(heap
))
1038 WARN("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1041 ret
= HEAP_ValidateInUseArena( subheap
, (const ARENA_INUSE
*)block
- 1, quiet
);
1043 if (!(flags
& HEAP_NO_SERIALIZE
))
1044 RtlLeaveHeapLock( &heapPtr
->critSection
);
1048 subheap
= &heapPtr
->subheap
;
1049 while (subheap
&& ret
)
1051 char *ptr
= (char *)subheap
+ subheap
->headerSize
;
1052 while (ptr
< (char *)subheap
+ subheap
->size
)
1054 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
1056 if (!HEAP_ValidateFreeArena( subheap
, (ARENA_FREE
*)ptr
)) {
1060 ptr
+= sizeof(ARENA_FREE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1064 if (!HEAP_ValidateInUseArena( subheap
, (ARENA_INUSE
*)ptr
, NOISY
)) {
1068 ptr
+= sizeof(ARENA_INUSE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1071 subheap
= subheap
->next
;
1074 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1079 /***********************************************************************
1080 * HeapCreate (KERNEL32.336)
1082 * Handle of heap: Success
1088 RtlCreateHeap(ULONG flags
,
1093 PRTL_HEAP_PARAMETERS Parameters
)
1097 /* Allocate the heap block */
1101 totalSize
= HEAP_DEF_SIZE
;
1102 flags
|= HEAP_GROWABLE
;
1104 if (!(subheap
= HEAP_CreateSubHeap( NULL
, addr
, flags
, commitSize
, totalSize
, Parameters
))) return 0;
1106 if (RtlpGetMode() == UserMode
)
1108 /* link it into the per-process heap list */
1111 HEAP
*heapPtr
= subheap
->heap
;
1112 RtlEnterHeapLock( &processHeap
->critSection
);
1113 list_add_head( &processHeap
->entry
, &heapPtr
->entry
);
1114 RtlLeaveHeapLock( &processHeap
->critSection
);
1118 processHeap
= subheap
->heap
; /* assume the first heap we create is the process main heap */
1119 list_init( &processHeap
->entry
);
1123 return (HANDLE
)subheap
;
1126 /***********************************************************************
1127 * HeapDestroy (KERNEL32.337)
1135 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1136 * Failure: The Heap handle, if heap is the process heap.
1139 RtlDestroyHeap(HANDLE heap
) /* [in] Handle of heap */
1141 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1144 DPRINT("%p\n", heap
);
1148 if (RtlpGetMode() == UserMode
)
1150 if (heap
== NtCurrentPeb()->ProcessHeap
)
1151 return heap
; /* cannot delete the main process heap */
1153 /* remove it from the per-process list */
1154 RtlEnterHeapLock( &processHeap
->critSection
);
1155 list_remove( &heapPtr
->entry
);
1156 RtlLeaveHeapLock( &processHeap
->critSection
);
1159 RtlDeleteHeapLock( &heapPtr
->critSection
);
1160 subheap
= &heapPtr
->subheap
;
1163 SUBHEAP
*next
= subheap
->next
;
1165 void *addr
= subheap
;
1166 ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &size
, MEM_RELEASE
);
1169 return (HANDLE
)NULL
;
1173 /***********************************************************************
1174 * HeapAlloc (KERNEL32.334)
1176 * Pointer to allocated memory block
1178 * 0x7d030f60--invalid flags in RtlHeapAllocate
1182 RtlAllocateHeap(HANDLE heap
, /* [in] Handle of private heap block */
1183 ULONG flags
, /* [in] Heap allocation control flags */
1184 ULONG size
) /* [in] Number of bytes to allocate */
1187 ARENA_INUSE
*pInUse
;
1189 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1190 SIZE_T rounded_size
;
1192 /* Validate the parameters */
1196 if (flags
& HEAP_GENERATE_EXCEPTIONS
)
1197 RtlRaiseStatus( STATUS_NO_MEMORY
);
1200 //flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1201 flags
|= heapPtr
->flags
;
1202 rounded_size
= ROUND_SIZE(size
);
1203 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1205 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1206 /* Locate a suitable free block */
1208 /* Locate a suitable free block */
1210 if (!(pArena
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &subheap
)))
1212 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1213 heap
, flags
, size
);
1214 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1215 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1219 /* Remove the arena from the free list */
1221 list_remove( &pArena
->entry
);
1223 /* Build the in-use arena */
1225 pInUse
= (ARENA_INUSE
*)pArena
;
1227 /* in-use arena is smaller than free arena,
1228 * so we have to add the difference to the size */
1229 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
) + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1230 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1232 /* Save user flags */
1233 subheap
->UserFlags
= flags
& HEAP_SETTABLE_USER_FLAGS
;
1235 /* Shrink the block */
1237 HEAP_ShrinkBlock( subheap
, pInUse
, rounded_size
);
1238 pInUse
->unused_bytes
= (pInUse
->size
& ARENA_SIZE_MASK
) - size
;
1240 if (flags
& HEAP_ZERO_MEMORY
)
1241 clear_block( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1243 mark_block_uninitialized( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1245 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1247 TRACE("(%p,%08lx,%08lx): returning %p\n", heap
, flags
, size
, pInUse
+ 1 );
1248 return (LPVOID
)(pInUse
+ 1);
1252 /***********************************************************************
1253 * HeapFree (KERNEL32.338)
1260 BOOLEAN NTAPI
RtlFreeHeap(
1261 HANDLE heap
, /* [in] Handle of heap */
1262 ULONG flags
, /* [in] Heap freeing flags */
1263 PVOID ptr
/* [in] Address of memory to free */
1266 ARENA_INUSE
*pInUse
;
1270 /* Validate the parameters */
1272 if (!ptr
) return TRUE
; /* freeing a NULL ptr isn't an error in Win2k */
1274 heapPtr
= HEAP_GetPtr( heap
);
1277 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1281 flags
&= HEAP_NO_SERIALIZE
;
1282 flags
|= heapPtr
->flags
;
1283 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1284 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1286 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1287 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1288 TRACE("(%p,%08lx,%p): returning FALSE\n", heap
, flags
, ptr
);
1292 /* Turn the block into a free block */
1294 pInUse
= (ARENA_INUSE
*)ptr
- 1;
1295 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1296 HEAP_MakeInUseBlockFree( subheap
, pInUse
);
1298 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1300 TRACE("(%p,%08lx,%p): returning TRUE\n", heap
, flags
, ptr
);
1305 /***********************************************************************
1308 * Heap [in] Handle of heap block
1309 * Flags [in] Heap reallocation flags
1310 * Ptr, [in] Address of memory to reallocate
1311 * Size [in] Number of bytes to reallocate
1314 * Pointer to reallocated memory block
1316 * 0x7d030f60--invalid flags in RtlHeapAllocate
1319 PVOID NTAPI
RtlReAllocateHeap(
1326 ARENA_INUSE
*pArena
;
1329 SIZE_T oldSize
, rounded_size
;
1331 if (!ptr
) return NULL
;
1332 if (!(heapPtr
= HEAP_GetPtr( heap
)))
1334 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1338 /* Validate the parameters */
1340 //Flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1341 // HEAP_REALLOC_IN_PLACE_ONLY;
1342 flags
|= heapPtr
->flags
;
1343 rounded_size
= ROUND_SIZE(size
);
1344 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1346 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1347 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1349 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1350 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1351 TRACE("(%p,%08lx,%p,%08lx): returning NULL\n", heap
, flags
, ptr
, size
);
1355 pArena
= (ARENA_INUSE
*)ptr
- 1;
1356 subheap
= HEAP_FindSubHeap( heapPtr
, pArena
);
1357 oldSize
= (pArena
->size
& ARENA_SIZE_MASK
);
1358 if (rounded_size
> oldSize
)
1360 char *pNext
= (char *)(pArena
+ 1) + oldSize
;
1361 if ((pNext
< (char *)subheap
+ subheap
->size
) &&
1362 (*(DWORD
*)pNext
& ARENA_FLAG_FREE
) &&
1363 (oldSize
+ (*(DWORD
*)pNext
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
) >= rounded_size
))
1365 /* The next block is free and large enough */
1366 ARENA_FREE
*pFree
= (ARENA_FREE
*)pNext
;
1367 list_remove( &pFree
->entry
);
1368 pArena
->size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(*pFree
);
1369 if (!HEAP_Commit( subheap
, pArena
, rounded_size
))
1371 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1372 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1373 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1376 HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
);
1378 else /* Do it the hard way */
1381 ARENA_INUSE
*pInUse
;
1382 SUBHEAP
*newsubheap
;
1384 if ((flags
& HEAP_REALLOC_IN_PLACE_ONLY
) ||
1385 !(pNew
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &newsubheap
)))
1387 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1388 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1389 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1393 /* Build the in-use arena */
1395 list_remove( &pNew
->entry
);
1396 pInUse
= (ARENA_INUSE
*)pNew
;
1397 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
)
1398 + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1399 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1400 HEAP_ShrinkBlock( newsubheap
, pInUse
, rounded_size
);
1401 mark_block_initialized( pInUse
+ 1, oldSize
);
1402 memcpy( pInUse
+ 1, pArena
+ 1, oldSize
);
1404 /* Free the previous block */
1406 HEAP_MakeInUseBlockFree( subheap
, pArena
);
1407 subheap
= newsubheap
;
1411 else HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
); /* Shrink the block */
1413 pArena
->unused_bytes
= (pArena
->size
& ARENA_SIZE_MASK
) - size
;
1415 /* Clear the extra bytes if needed */
1417 if (rounded_size
> oldSize
)
1419 if (flags
& HEAP_ZERO_MEMORY
)
1420 clear_block( (char *)(pArena
+ 1) + oldSize
,
1421 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1423 mark_block_uninitialized( (char *)(pArena
+ 1) + oldSize
,
1424 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1427 /* Return the new arena */
1429 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1431 TRACE("(%p,%08lx,%p,%08lx): returning %p\n", heap
, flags
, ptr
, size
, pArena
+ 1 );
1432 return (LPVOID
)(pArena
+ 1);
1436 /***********************************************************************
1442 RtlCompactHeap(HANDLE Heap
,
1450 /***********************************************************************
1452 * Attempts to acquire the critical section object for a specified heap.
1455 * Heap [in] Handle of heap to lock for exclusive access
1464 RtlLockHeap(IN HANDLE Heap
)
1466 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1469 RtlEnterHeapLock( &heapPtr
->critSection
);
1474 /***********************************************************************
1476 * Releases ownership of the critical section object.
1479 * Heap [in] Handle to the heap to unlock
1488 RtlUnlockHeap(HANDLE Heap
)
1490 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1493 RtlLeaveHeapLock( &heapPtr
->critSection
);
1498 /***********************************************************************
1501 * Heap [in] Handle of heap
1502 * Flags [in] Heap size control flags
1503 * Ptr [in] Address of memory to return size for
1506 * Size in bytes of allocated memory
1507 * 0xffffffff: Failure
1519 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1523 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1526 flags
&= HEAP_NO_SERIALIZE
;
1527 flags
|= heapPtr
->flags
;
1528 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1529 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1531 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1536 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
- 1;
1537 ret
= (pArena
->size
& ARENA_SIZE_MASK
) - pArena
->unused_bytes
;
1539 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1541 TRACE("(%p,%08lx,%p): returning %08lx\n", heap
, flags
, ptr
, ret
);
1546 /***********************************************************************
1548 * Validates a specified heap.
1551 * Heap [in] Handle to the heap
1552 * Flags [in] Bit flags that control access during operation
1553 * Block [in] Optional pointer to memory block to validate
1564 BOOLEAN NTAPI
RtlValidateHeap(
1570 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1573 return HEAP_IsRealArena( heapPtr
, Flags
, Block
, QUIET
);
1577 RtlInitializeHeapManager(VOID
)
1581 Peb
= NtCurrentPeb();
1583 Peb
->NumberOfHeaps
= 0;
1584 Peb
->MaximumNumberOfHeaps
= -1; /* no limit */
1585 Peb
->ProcessHeaps
= NULL
;
1587 //RtlInitializeHeapLock(&RtlpProcessHeapsListLock);
1595 RtlEnumProcessHeaps(PHEAP_ENUMERATION_ROUTINE HeapEnumerationRoutine
,
1598 DPRINT1("UNIMPLEMENTED\n");
1599 DPRINT1("UNIMPLEMENTED\n");
1600 DPRINT1("UNIMPLEMENTED\n");
1601 DPRINT1("UNIMPLEMENTED\n");
1603 return STATUS_SUCCESS
;
1605 NTSTATUS Status
= STATUS_SUCCESS
;
1608 RtlEnterHeapLock(&RtlpProcessHeapsListLock
);
1610 for (pptr
= (HEAP
**)&NtCurrentPeb()->ProcessHeaps
; *pptr
; pptr
= &(*pptr
)->next
)
1612 Status
= HeapEnumerationRoutine(*pptr
,lParam
);
1613 if (!NT_SUCCESS(Status
))
1617 RtlLeaveHeapLock(&RtlpProcessHeapsListLock
);
1628 RtlGetProcessHeaps(ULONG count
,
1631 ULONG total
= 1; /* main heap */
1634 RtlEnterHeapLock( &processHeap
->critSection
);
1635 LIST_FOR_EACH( ptr
, &processHeap
->entry
) total
++;
1638 *heaps
++ = processHeap
;
1639 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1640 *heaps
++ = LIST_ENTRY( ptr
, HEAP
, entry
);
1642 RtlLeaveHeapLock( &processHeap
->critSection
);
1651 RtlValidateProcessHeaps(VOID
)
1653 DPRINT1("UNIMPLEMENTED\n");
1654 DPRINT1("UNIMPLEMENTED\n");
1655 DPRINT1("UNIMPLEMENTED\n");
1656 DPRINT1("UNIMPLEMENTED\n");
1658 return STATUS_SUCCESS
;
1660 BOOLEAN Result
= TRUE
;
1663 RtlEnterHeapLock(&RtlpProcessHeapsListLock
);
1665 for (pptr
= (HEAP
**)&NtCurrentPeb()->ProcessHeaps
; *pptr
; pptr
= &(*pptr
)->next
)
1667 if (!RtlValidateHeap(*pptr
, 0, NULL
))
1674 RtlLeaveHeapLock (&RtlpProcessHeapsListLock
);
1686 IN PVOID HeapHandle
,
1699 RtlSetUserValueHeap(IN PVOID HeapHandle
,
1701 IN PVOID BaseAddress
,
1704 HEAP
*heapPtr
= HEAP_GetPtr(HeapHandle
);
1705 ARENA_INUSE
*pInUse
;
1708 /* Get the subheap */
1709 pInUse
= (ARENA_INUSE
*)BaseAddress
- 1;
1710 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1713 subheap
->UserValue
= UserValue
;
1722 RtlGetUserInfoHeap(IN PVOID HeapHandle
,
1724 IN PVOID BaseAddress
,
1725 OUT PVOID
*UserValue
,
1726 OUT PULONG UserFlags
)
1728 HEAP
*heapPtr
= HEAP_GetPtr(HeapHandle
);
1729 ARENA_INUSE
*pInUse
;
1732 /* Get the subheap */
1733 pInUse
= (ARENA_INUSE
*)BaseAddress
- 1;
1734 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1737 DPRINT1("V/F: %lx %p\n", subheap
->UserValue
, subheap
->UserFlags
);
1738 if (UserValue
) *UserValue
= subheap
->UserValue
;
1739 if (UserFlags
) *UserFlags
= subheap
->UserFlags
;
1748 RtlUsageHeap(IN HANDLE Heap
,
1750 OUT PRTL_HEAP_USAGE Usage
)
1754 return STATUS_NOT_IMPLEMENTED
;
1759 RtlQueryTagHeap(IN PVOID HeapHandle
,
1762 IN BOOLEAN ResetCounters
,
1763 OUT PRTL_HEAP_TAG_INFO HeapTagInfo
)
1772 RtlExtendHeap(IN HANDLE Heap
,
1784 RtlCreateTagHeap(IN HANDLE HeapHandle
,
1787 IN PWSTR TagSubName
)