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
},
207 0, 0, { (DWORD_PTR
)(__FILE__
": main process heap section") }
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 /***********************************************************************
1000 * Checks whether the pointer points to a block inside a given heap.
1003 * Should this return BOOL32?
1009 int HEAP_IsInsideHeap(
1010 HANDLE heap
, /* [in] Heap */
1011 ULONG flags
, /* [in] Flags */
1012 PVOID ptr
/* [in] Pointer */
1015 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1019 /* Validate the parameters */
1023 flags
|= heapPtr
->flags
;
1024 if (!(flags
& HEAP_NO_SERIALIZE
))
1025 RtlEnterHeapLock( &heapPtr
->critSection
);
1026 ret
= (((subheap
= HEAP_FindSubHeap( heapPtr
, ptr
)) != NULL
) &&
1027 (((char *)ptr
>= (char *)subheap
+ subheap
->headerSize
1028 + sizeof(ARENA_INUSE
))));
1029 if (!(flags
& HEAP_NO_SERIALIZE
))
1030 RtlLeaveHeapLock( &heapPtr
->critSection
);
1035 void DumpStackFrames ( PULONG Frame
, ULONG FrameCount
)
1040 DbgPrint("Frames: ");
1043 #if defined __GNUC__
1044 __asm__("mov %%ebp, %0" : "=r" (Frame
) : );
1045 #elif defined(_MSC_VER)
1046 __asm mov
[Frame
], ebp
1048 Frame
= (PULONG
)Frame
[0]; // step out of DumpStackFrames
1050 while ( Frame
!= 0 && (ULONG
)Frame
!= 0xDEADBEEF && (ULONG
)Frame
!= 0xcdcdcdcd && (ULONG
)Frame
!= 0xcccccccc && i
++ < FrameCount
)
1052 DbgPrint("<%p>", (PVOID
)Frame
[1]);
1053 if (Frame
[1] == 0xdeadbeef)
1055 Frame
= (PULONG
)Frame
[0];
1062 /***********************************************************************
1063 * HEAP_IsRealArena [Internal]
1064 * Validates a block is a valid arena.
1070 static BOOL
HEAP_IsRealArena( HEAP
*heapPtr
, /* [in] ptr to the heap */
1071 DWORD flags
, /* [in] Bit flags that control access during operation */
1072 LPCVOID block
, /* [in] Optional pointer to memory block to validate */
1073 BOOL quiet
) /* [in] Flag - if true, HEAP_ValidateInUseArena
1074 * does not complain */
1079 if (!heapPtr
|| (heapPtr
->magic
!= HEAP_MAGIC
))
1081 ERR("Invalid heap %p!\n", heapPtr
);
1085 flags
&= HEAP_NO_SERIALIZE
;
1086 flags
|= heapPtr
->flags
;
1087 /* calling HeapLock may result in infinite recursion, so do the critsect directly */
1088 if (!(flags
& HEAP_NO_SERIALIZE
))
1089 RtlEnterHeapLock( &heapPtr
->critSection
);
1093 /* Only check this single memory block */
1095 if (!(subheap
= HEAP_FindSubHeap( heapPtr
, block
)) ||
1096 ((const char *)block
< (char *)subheap
+ subheap
->headerSize
1097 + sizeof(ARENA_INUSE
)))
1100 ERR("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1101 else if (WARN_ON(heap
))
1102 WARN("Heap %p: block %p is not inside heap\n", heapPtr
, block
);
1105 ret
= HEAP_ValidateInUseArena( subheap
, (const ARENA_INUSE
*)block
- 1, quiet
);
1107 if (!(flags
& HEAP_NO_SERIALIZE
))
1108 RtlLeaveHeapLock( &heapPtr
->critSection
);
1112 subheap
= &heapPtr
->subheap
;
1113 while (subheap
&& ret
)
1115 char *ptr
= (char *)subheap
+ subheap
->headerSize
;
1116 while (ptr
< (char *)subheap
+ subheap
->size
)
1118 if (*(DWORD
*)ptr
& ARENA_FLAG_FREE
)
1120 if (!HEAP_ValidateFreeArena( subheap
, (ARENA_FREE
*)ptr
)) {
1124 ptr
+= sizeof(ARENA_FREE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1128 if (!HEAP_ValidateInUseArena( subheap
, (ARENA_INUSE
*)ptr
, NOISY
)) {
1132 ptr
+= sizeof(ARENA_INUSE
) + (*(DWORD
*)ptr
& ARENA_SIZE_MASK
);
1135 subheap
= subheap
->next
;
1138 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1143 /***********************************************************************
1144 * HeapCreate (KERNEL32.336)
1146 * Handle of heap: Success
1152 RtlCreateHeap(ULONG flags
,
1157 PRTL_HEAP_PARAMETERS Parameters
)
1161 /* Allocate the heap block */
1165 totalSize
= HEAP_DEF_SIZE
;
1166 flags
|= HEAP_GROWABLE
;
1168 if (!(subheap
= HEAP_CreateSubHeap( NULL
, addr
, flags
, commitSize
, totalSize
, Parameters
))) return 0;
1170 if (RtlpGetMode() == UserMode
)
1172 /* link it into the per-process heap list */
1175 HEAP
*heapPtr
= subheap
->heap
;
1176 RtlEnterHeapLock( &processHeap
->critSection
);
1177 list_add_head( &processHeap
->entry
, &heapPtr
->entry
);
1178 RtlLeaveHeapLock( &processHeap
->critSection
);
1182 processHeap
= subheap
->heap
; /* assume the first heap we create is the process main heap */
1183 list_init( &processHeap
->entry
);
1187 return (HANDLE
)subheap
;
1190 /***********************************************************************
1191 * HeapDestroy (KERNEL32.337)
1199 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1200 * Failure: The Heap handle, if heap is the process heap.
1203 RtlDestroyHeap(HANDLE heap
) /* [in] Handle of heap */
1205 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1208 DPRINT("%p\n", heap
);
1212 if (RtlpGetMode() == UserMode
)
1214 if (heap
== NtCurrentPeb()->ProcessHeap
)
1215 return heap
; /* cannot delete the main process heap */
1217 /* remove it from the per-process list */
1218 RtlEnterHeapLock( &processHeap
->critSection
);
1219 list_remove( &heapPtr
->entry
);
1220 RtlLeaveHeapLock( &processHeap
->critSection
);
1223 RtlDeleteHeapLock( &heapPtr
->critSection
);
1224 subheap
= &heapPtr
->subheap
;
1227 SUBHEAP
*next
= subheap
->next
;
1229 void *addr
= subheap
;
1230 ZwFreeVirtualMemory( NtCurrentProcess(), &addr
, &size
, MEM_RELEASE
);
1233 return (HANDLE
)NULL
;
1237 /***********************************************************************
1238 * HeapAlloc (KERNEL32.334)
1240 * Pointer to allocated memory block
1242 * 0x7d030f60--invalid flags in RtlHeapAllocate
1246 RtlAllocateHeap(HANDLE heap
, /* [in] Handle of private heap block */
1247 ULONG flags
, /* [in] Heap allocation control flags */
1248 ULONG size
) /* [in] Number of bytes to allocate */
1251 ARENA_INUSE
*pInUse
;
1253 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1254 SIZE_T rounded_size
;
1256 /* Validate the parameters */
1260 if (flags
& HEAP_GENERATE_EXCEPTIONS
)
1261 RtlRaiseStatus( STATUS_NO_MEMORY
);
1264 //flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY;
1265 flags
|= heapPtr
->flags
;
1266 rounded_size
= ROUND_SIZE(size
);
1267 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1269 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1270 /* Locate a suitable free block */
1272 /* Locate a suitable free block */
1274 if (!(pArena
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &subheap
)))
1276 TRACE("(%p,%08lx,%08lx): returning NULL\n",
1277 heap
, flags
, size
);
1278 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1279 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1283 /* Remove the arena from the free list */
1285 list_remove( &pArena
->entry
);
1287 /* Build the in-use arena */
1289 pInUse
= (ARENA_INUSE
*)pArena
;
1291 /* in-use arena is smaller than free arena,
1292 * so we have to add the difference to the size */
1293 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
) + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1294 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1296 /* Save user flags */
1297 subheap
->UserFlags
= flags
& HEAP_SETTABLE_USER_FLAGS
;
1299 /* Shrink the block */
1301 HEAP_ShrinkBlock( subheap
, pInUse
, rounded_size
);
1302 pInUse
->unused_bytes
= (pInUse
->size
& ARENA_SIZE_MASK
) - size
;
1304 if (flags
& HEAP_ZERO_MEMORY
)
1305 clear_block( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1307 mark_block_uninitialized( pInUse
+ 1, pInUse
->size
& ARENA_SIZE_MASK
);
1309 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1311 TRACE("(%p,%08lx,%08lx): returning %p\n", heap
, flags
, size
, pInUse
+ 1 );
1312 return (LPVOID
)(pInUse
+ 1);
1316 /***********************************************************************
1317 * HeapFree (KERNEL32.338)
1324 BOOLEAN NTAPI
RtlFreeHeap(
1325 HANDLE heap
, /* [in] Handle of heap */
1326 ULONG flags
, /* [in] Heap freeing flags */
1327 PVOID ptr
/* [in] Address of memory to free */
1330 ARENA_INUSE
*pInUse
;
1334 /* Validate the parameters */
1336 if (!ptr
) return TRUE
; /* freeing a NULL ptr isn't an error in Win2k */
1338 heapPtr
= HEAP_GetPtr( heap
);
1341 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1345 flags
&= HEAP_NO_SERIALIZE
;
1346 flags
|= heapPtr
->flags
;
1347 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1348 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1350 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1351 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1352 TRACE("(%p,%08lx,%p): returning FALSE\n", heap
, flags
, ptr
);
1356 /* Turn the block into a free block */
1358 pInUse
= (ARENA_INUSE
*)ptr
- 1;
1359 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1360 HEAP_MakeInUseBlockFree( subheap
, pInUse
);
1362 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1364 TRACE("(%p,%08lx,%p): returning TRUE\n", heap
, flags
, ptr
);
1369 /***********************************************************************
1372 * Heap [in] Handle of heap block
1373 * Flags [in] Heap reallocation flags
1374 * Ptr, [in] Address of memory to reallocate
1375 * Size [in] Number of bytes to reallocate
1378 * Pointer to reallocated memory block
1380 * 0x7d030f60--invalid flags in RtlHeapAllocate
1383 PVOID NTAPI
RtlReAllocateHeap(
1390 ARENA_INUSE
*pArena
;
1393 SIZE_T oldSize
, rounded_size
;
1395 if (!ptr
) return NULL
;
1396 if (!(heapPtr
= HEAP_GetPtr( heap
)))
1398 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1402 /* Validate the parameters */
1404 //Flags &= HEAP_GENERATE_EXCEPTIONS | HEAP_NO_SERIALIZE | HEAP_ZERO_MEMORY |
1405 // HEAP_REALLOC_IN_PLACE_ONLY;
1406 flags
|= heapPtr
->flags
;
1407 rounded_size
= ROUND_SIZE(size
);
1408 if (rounded_size
< HEAP_MIN_DATA_SIZE
) rounded_size
= HEAP_MIN_DATA_SIZE
;
1410 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1411 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1413 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1414 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1415 TRACE("(%p,%08lx,%p,%08lx): returning NULL\n", heap
, flags
, ptr
, size
);
1419 pArena
= (ARENA_INUSE
*)ptr
- 1;
1420 subheap
= HEAP_FindSubHeap( heapPtr
, pArena
);
1421 oldSize
= (pArena
->size
& ARENA_SIZE_MASK
);
1422 if (rounded_size
> oldSize
)
1424 char *pNext
= (char *)(pArena
+ 1) + oldSize
;
1425 if ((pNext
< (char *)subheap
+ subheap
->size
) &&
1426 (*(DWORD
*)pNext
& ARENA_FLAG_FREE
) &&
1427 (oldSize
+ (*(DWORD
*)pNext
& ARENA_SIZE_MASK
) + sizeof(ARENA_FREE
) >= rounded_size
))
1429 /* The next block is free and large enough */
1430 ARENA_FREE
*pFree
= (ARENA_FREE
*)pNext
;
1431 list_remove( &pFree
->entry
);
1432 pArena
->size
+= (pFree
->size
& ARENA_SIZE_MASK
) + sizeof(*pFree
);
1433 if (!HEAP_Commit( subheap
, pArena
, rounded_size
))
1435 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1436 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1437 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1440 HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
);
1442 else /* Do it the hard way */
1445 ARENA_INUSE
*pInUse
;
1446 SUBHEAP
*newsubheap
;
1448 if ((flags
& HEAP_REALLOC_IN_PLACE_ONLY
) ||
1449 !(pNew
= HEAP_FindFreeBlock( heapPtr
, rounded_size
, &newsubheap
)))
1451 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1452 if (flags
& HEAP_GENERATE_EXCEPTIONS
) RtlRaiseStatus( STATUS_NO_MEMORY
);
1453 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_NO_MEMORY
);
1457 /* Build the in-use arena */
1459 list_remove( &pNew
->entry
);
1460 pInUse
= (ARENA_INUSE
*)pNew
;
1461 pInUse
->size
= (pInUse
->size
& ~ARENA_FLAG_FREE
)
1462 + sizeof(ARENA_FREE
) - sizeof(ARENA_INUSE
);
1463 pInUse
->magic
= ARENA_INUSE_MAGIC
;
1464 HEAP_ShrinkBlock( newsubheap
, pInUse
, rounded_size
);
1465 mark_block_initialized( pInUse
+ 1, oldSize
);
1466 memcpy( pInUse
+ 1, pArena
+ 1, oldSize
);
1468 /* Free the previous block */
1470 HEAP_MakeInUseBlockFree( subheap
, pArena
);
1471 subheap
= newsubheap
;
1475 else HEAP_ShrinkBlock( subheap
, pArena
, rounded_size
); /* Shrink the block */
1477 pArena
->unused_bytes
= (pArena
->size
& ARENA_SIZE_MASK
) - size
;
1479 /* Clear the extra bytes if needed */
1481 if (rounded_size
> oldSize
)
1483 if (flags
& HEAP_ZERO_MEMORY
)
1484 clear_block( (char *)(pArena
+ 1) + oldSize
,
1485 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1487 mark_block_uninitialized( (char *)(pArena
+ 1) + oldSize
,
1488 (pArena
->size
& ARENA_SIZE_MASK
) - oldSize
);
1491 /* Return the new arena */
1493 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1495 TRACE("(%p,%08lx,%p,%08lx): returning %p\n", heap
, flags
, ptr
, size
, pArena
+ 1 );
1496 return (LPVOID
)(pArena
+ 1);
1500 /***********************************************************************
1506 RtlCompactHeap(HANDLE Heap
,
1514 /***********************************************************************
1516 * Attempts to acquire the critical section object for a specified heap.
1519 * Heap [in] Handle of heap to lock for exclusive access
1528 RtlLockHeap(IN HANDLE Heap
)
1530 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1533 RtlEnterHeapLock( &heapPtr
->critSection
);
1538 /***********************************************************************
1540 * Releases ownership of the critical section object.
1543 * Heap [in] Handle to the heap to unlock
1552 RtlUnlockHeap(HANDLE Heap
)
1554 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1557 RtlLeaveHeapLock( &heapPtr
->critSection
);
1562 /***********************************************************************
1565 * Heap [in] Handle of heap
1566 * Flags [in] Heap size control flags
1567 * Ptr [in] Address of memory to return size for
1570 * Size in bytes of allocated memory
1571 * 0xffffffff: Failure
1583 HEAP
*heapPtr
= HEAP_GetPtr( heap
);
1587 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_HANDLE
);
1590 flags
&= HEAP_NO_SERIALIZE
;
1591 flags
|= heapPtr
->flags
;
1592 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlEnterHeapLock( &heapPtr
->critSection
);
1593 if (!HEAP_IsRealArena( heapPtr
, HEAP_NO_SERIALIZE
, ptr
, QUIET
))
1595 RtlSetLastWin32ErrorAndNtStatusFromNtStatus( STATUS_INVALID_PARAMETER
);
1600 ARENA_INUSE
*pArena
= (ARENA_INUSE
*)ptr
- 1;
1601 ret
= (pArena
->size
& ARENA_SIZE_MASK
) - pArena
->unused_bytes
;
1603 if (!(flags
& HEAP_NO_SERIALIZE
)) RtlLeaveHeapLock( &heapPtr
->critSection
);
1605 TRACE("(%p,%08lx,%p): returning %08lx\n", heap
, flags
, ptr
, ret
);
1610 /***********************************************************************
1612 * Validates a specified heap.
1615 * Heap [in] Handle to the heap
1616 * Flags [in] Bit flags that control access during operation
1617 * Block [in] Optional pointer to memory block to validate
1628 BOOLEAN NTAPI
RtlValidateHeap(
1634 HEAP
*heapPtr
= HEAP_GetPtr( Heap
);
1637 return HEAP_IsRealArena( heapPtr
, Flags
, Block
, QUIET
);
1641 RtlInitializeHeapManager(VOID
)
1645 Peb
= NtCurrentPeb();
1647 Peb
->NumberOfHeaps
= 0;
1648 Peb
->MaximumNumberOfHeaps
= -1; /* no limit */
1649 Peb
->ProcessHeaps
= NULL
;
1651 //RtlInitializeHeapLock(&RtlpProcessHeapsListLock);
1659 RtlEnumProcessHeaps(PHEAP_ENUMERATION_ROUTINE HeapEnumerationRoutine
,
1662 DPRINT1("UNIMPLEMENTED\n");
1663 DPRINT1("UNIMPLEMENTED\n");
1664 DPRINT1("UNIMPLEMENTED\n");
1665 DPRINT1("UNIMPLEMENTED\n");
1667 return STATUS_SUCCESS
;
1669 NTSTATUS Status
= STATUS_SUCCESS
;
1672 RtlEnterHeapLock(&RtlpProcessHeapsListLock
);
1674 for (pptr
= (HEAP
**)&NtCurrentPeb()->ProcessHeaps
; *pptr
; pptr
= &(*pptr
)->next
)
1676 Status
= HeapEnumerationRoutine(*pptr
,lParam
);
1677 if (!NT_SUCCESS(Status
))
1681 RtlLeaveHeapLock(&RtlpProcessHeapsListLock
);
1692 RtlGetProcessHeaps(ULONG count
,
1695 ULONG total
= 1; /* main heap */
1698 RtlEnterHeapLock( &processHeap
->critSection
);
1699 LIST_FOR_EACH( ptr
, &processHeap
->entry
) total
++;
1702 *heaps
++ = processHeap
;
1703 LIST_FOR_EACH( ptr
, &processHeap
->entry
)
1704 *heaps
++ = LIST_ENTRY( ptr
, HEAP
, entry
);
1706 RtlLeaveHeapLock( &processHeap
->critSection
);
1715 RtlValidateProcessHeaps(VOID
)
1717 DPRINT1("UNIMPLEMENTED\n");
1718 DPRINT1("UNIMPLEMENTED\n");
1719 DPRINT1("UNIMPLEMENTED\n");
1720 DPRINT1("UNIMPLEMENTED\n");
1722 return STATUS_SUCCESS
;
1724 BOOLEAN Result
= TRUE
;
1727 RtlEnterHeapLock(&RtlpProcessHeapsListLock
);
1729 for (pptr
= (HEAP
**)&NtCurrentPeb()->ProcessHeaps
; *pptr
; pptr
= &(*pptr
)->next
)
1731 if (!RtlValidateHeap(*pptr
, 0, NULL
))
1738 RtlLeaveHeapLock (&RtlpProcessHeapsListLock
);
1750 IN PVOID HeapHandle
,
1763 RtlSetUserValueHeap(IN PVOID HeapHandle
,
1765 IN PVOID BaseAddress
,
1768 HEAP
*heapPtr
= HEAP_GetPtr(HeapHandle
);
1769 ARENA_INUSE
*pInUse
;
1772 /* Get the subheap */
1773 pInUse
= (ARENA_INUSE
*)BaseAddress
- 1;
1774 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1777 subheap
->UserValue
= UserValue
;
1786 RtlGetUserInfoHeap(IN PVOID HeapHandle
,
1788 IN PVOID BaseAddress
,
1789 OUT PVOID
*UserValue
,
1790 OUT PULONG UserFlags
)
1792 HEAP
*heapPtr
= HEAP_GetPtr(HeapHandle
);
1793 ARENA_INUSE
*pInUse
;
1796 /* Get the subheap */
1797 pInUse
= (ARENA_INUSE
*)BaseAddress
- 1;
1798 subheap
= HEAP_FindSubHeap( heapPtr
, pInUse
);
1801 DPRINT1("V/F: %lx %p\n", subheap
->UserValue
, subheap
->UserFlags
);
1802 if (UserValue
) *UserValue
= subheap
->UserValue
;
1803 if (UserFlags
) *UserFlags
= subheap
->UserFlags
;
1812 RtlUsageHeap(IN HANDLE Heap
,
1814 OUT PRTL_HEAP_USAGE Usage
)
1818 return STATUS_NOT_IMPLEMENTED
;
1823 RtlQueryTagHeap(IN PVOID HeapHandle
,
1826 IN BOOLEAN ResetCounters
,
1827 OUT PRTL_HEAP_TAG_INFO HeapTagInfo
)
1836 RtlExtendHeap(IN HANDLE Heap
,
1848 RtlCreateTagHeap(IN HANDLE HeapHandle
,
1851 IN PWSTR TagSubName
)