1 /* COPYRIGHT: See COPYING in the top level directory
2 * PROJECT: ReactOS system libraries
4 * PURPOSE: RTL Heap backend allocator
5 * PROGRAMMERS: Copyright 2010 Aleksey Bragin
9 http://msdn.microsoft.com/en-us/library/ms810466.aspx
10 http://msdn.microsoft.com/en-us/library/ms810603.aspx
11 http://www.securitylab.ru/analytics/216376.php
12 http://binglongx.spaces.live.com/blog/cns!142CBF6D49079DE8!596.entry
13 http://www.phreedom.org/research/exploits/asn1-bitstring/
14 http://illmatics.com/Understanding_the_LFH.pdf
15 http://www.alex-ionescu.com/?p=18
18 /* INCLUDES *****************************************************************/
26 HEAP_LOCK RtlpProcessHeapsListLock
;
30 /* How many least significant bits are clear */
31 UCHAR RtlpBitsClearLow
[] =
33 8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
34 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
35 5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
36 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
37 6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
38 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
39 5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
40 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
41 7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
42 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
43 5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
44 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
45 6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
46 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
47 5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
48 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0
52 RtlpFindLeastSetBit(ULONG Bits
)
57 return RtlpBitsClearLow
[Bits
& 0xFF]; /* Lowest byte */
59 return RtlpBitsClearLow
[(Bits
>> 8) & 0xFF] + 8; /* 2nd byte */
63 if ((Bits
>> 16) & 0xFF)
64 return RtlpBitsClearLow
[(Bits
>> 16) & 0xFF] + 16; /* 3rd byte */
66 return RtlpBitsClearLow
[(Bits
>> 24) & 0xFF] + 24; /* Highest byte */
70 /* Maximum size of a tail-filling pattern used for compare operation */
71 UCHAR FillPattern
[HEAP_ENTRY_SIZE
] =
85 RtlCompareMemoryUlong(PVOID Source
, ULONG Length
, ULONG Value
);
87 /* FUNCTIONS *****************************************************************/
90 RtlpInitializeHeap(PHEAP Heap
,
96 PVOID NextHeapBase
= Heap
+ 1;
97 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
103 *HeaderSize
+= NumUCRs
* sizeof(*UcrDescriptor
);
105 /* Prepare a list of UCRs */
106 InitializeListHead(&Heap
->UCRList
);
107 InitializeListHead(&Heap
->UCRSegments
);
108 UcrDescriptor
= NextHeapBase
;
110 for (i
=0; i
<NumUCRs
; i
++, UcrDescriptor
++)
112 InsertTailList(&Heap
->UCRList
, &UcrDescriptor
->ListEntry
);
115 NextHeapBase
= UcrDescriptor
;
118 /* Round up header size again */
119 *HeaderSize
= ROUND_UP(*HeaderSize
, HEAP_ENTRY_SIZE
);
121 ASSERT(*HeaderSize
<= PAGE_SIZE
);
123 /* Initialize heap's header */
124 Heap
->Entry
.Size
= (*HeaderSize
) >> HEAP_ENTRY_SHIFT
;
125 Heap
->Entry
.Flags
= HEAP_ENTRY_BUSY
;
127 Heap
->Signature
= HEAP_SIGNATURE
;
129 Heap
->ForceFlags
= (Flags
& (HEAP_NO_SERIALIZE
|
130 HEAP_GENERATE_EXCEPTIONS
|
132 HEAP_REALLOC_IN_PLACE_ONLY
|
133 HEAP_VALIDATE_PARAMETERS_ENABLED
|
134 HEAP_VALIDATE_ALL_ENABLED
|
135 HEAP_TAIL_CHECKING_ENABLED
|
136 HEAP_CREATE_ALIGN_16
|
137 HEAP_FREE_CHECKING_ENABLED
));
138 Heap
->HeaderValidateCopy
= NULL
;
139 Heap
->HeaderValidateLength
= ((PCHAR
)NextHeapBase
- (PCHAR
)Heap
);
141 /* Initialize free lists */
142 for (i
=0; i
<HEAP_FREELISTS
; i
++)
144 InitializeListHead(&Heap
->FreeLists
[i
]);
147 /* Initialize "big" allocations list */
148 InitializeListHead(&Heap
->VirtualAllocdBlocks
);
150 /* Initialize lock */
154 Status
= RtlInitializeHeapLock((PHEAP_LOCK
)Lock
);
155 if (!NT_SUCCESS(Status
))
157 DPRINT1("Initializing the lock failed!\n");
158 return /*NULL*/; // FIXME!
162 /* Set the lock variable */
163 Heap
->LockVariable
= Lock
;
167 RtlpSetFreeListsBit(PHEAP Heap
,
168 PHEAP_FREE_ENTRY FreeEntry
)
172 ASSERT(FreeEntry
->Size
< HEAP_FREELISTS
);
174 /* Calculate offset in the free list bitmap */
175 Index
= FreeEntry
->Size
>> 3; /* = FreeEntry->Size / (sizeof(UCHAR) * 8)*/
176 Bit
= 1 << (FreeEntry
->Size
& 7);
178 /* Assure it's not already set */
179 ASSERT((Heap
->u
.FreeListsInUseBytes
[Index
] & Bit
) == 0);
182 Heap
->u
.FreeListsInUseBytes
[Index
] |= Bit
;
186 RtlpClearFreeListsBit(PHEAP Heap
,
187 PHEAP_FREE_ENTRY FreeEntry
)
191 ASSERT(FreeEntry
->Size
< HEAP_FREELISTS
);
193 /* Calculate offset in the free list bitmap */
194 Index
= FreeEntry
->Size
>> 3; /* = FreeEntry->Size / (sizeof(UCHAR) * 8)*/
195 Bit
= 1 << (FreeEntry
->Size
& 7);
197 /* Assure it was set and the corresponding free list is empty */
198 ASSERT(Heap
->u
.FreeListsInUseBytes
[Index
] & Bit
);
199 ASSERT(IsListEmpty(&Heap
->FreeLists
[FreeEntry
->Size
]));
202 Heap
->u
.FreeListsInUseBytes
[Index
] ^= Bit
;
206 RtlpInsertFreeBlockHelper(PHEAP Heap
,
207 PHEAP_FREE_ENTRY FreeEntry
,
211 PLIST_ENTRY FreeListHead
, Current
;
212 PHEAP_FREE_ENTRY CurrentEntry
;
214 ASSERT(FreeEntry
->Size
== BlockSize
);
216 /* Fill if it's not denied */
219 FreeEntry
->Flags
&= ~(HEAP_ENTRY_FILL_PATTERN
|
220 HEAP_ENTRY_EXTRA_PRESENT
|
223 if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
225 RtlFillMemoryUlong((PCHAR
)(FreeEntry
+ 1),
226 (BlockSize
<< HEAP_ENTRY_SHIFT
) - sizeof(*FreeEntry
),
229 FreeEntry
->Flags
|= HEAP_ENTRY_FILL_PATTERN
;
234 /* Clear out all flags except the last entry one */
235 FreeEntry
->Flags
&= HEAP_ENTRY_LAST_ENTRY
;
238 /* Insert it either into dedicated or non-dedicated list */
239 if (BlockSize
< HEAP_FREELISTS
)
242 FreeListHead
= &Heap
->FreeLists
[BlockSize
];
244 if (IsListEmpty(FreeListHead
))
246 RtlpSetFreeListsBit(Heap
, FreeEntry
);
251 /* Non-dedicated one */
252 FreeListHead
= &Heap
->FreeLists
[0];
253 Current
= FreeListHead
->Flink
;
255 /* Find a position where to insert it to (the list must be sorted) */
256 while (FreeListHead
!= Current
)
258 CurrentEntry
= CONTAINING_RECORD(Current
, HEAP_FREE_ENTRY
, FreeList
);
260 if (BlockSize
<= CurrentEntry
->Size
)
263 Current
= Current
->Flink
;
266 FreeListHead
= Current
;
269 /* Actually insert it into the list */
270 InsertTailList(FreeListHead
, &FreeEntry
->FreeList
);
274 RtlpInsertFreeBlock(PHEAP Heap
,
275 PHEAP_FREE_ENTRY FreeEntry
,
278 USHORT Size
, PreviousSize
;
279 UCHAR SegmentOffset
, Flags
;
280 PHEAP_SEGMENT Segment
;
282 DPRINT("RtlpInsertFreeBlock(%p %p %x)\n", Heap
, FreeEntry
, BlockSize
);
284 /* Increase the free size counter */
285 Heap
->TotalFreeSize
+= BlockSize
;
287 /* Remember certain values */
288 Flags
= FreeEntry
->Flags
;
289 PreviousSize
= FreeEntry
->PreviousSize
;
290 SegmentOffset
= FreeEntry
->SegmentOffset
;
291 Segment
= Heap
->Segments
[SegmentOffset
];
296 /* Check for the max size */
297 if (BlockSize
> HEAP_MAX_BLOCK_SIZE
)
299 Size
= HEAP_MAX_BLOCK_SIZE
;
301 /* Special compensation if it goes above limit just by 1 */
302 if (BlockSize
== (HEAP_MAX_BLOCK_SIZE
+ 1))
305 FreeEntry
->Flags
= 0;
310 FreeEntry
->Flags
= Flags
;
313 /* Change its size and insert it into a free list */
314 FreeEntry
->Size
= Size
;
315 FreeEntry
->PreviousSize
= PreviousSize
;
316 FreeEntry
->SegmentOffset
= SegmentOffset
;
318 /* Call a helper to actually insert the block */
319 RtlpInsertFreeBlockHelper(Heap
, FreeEntry
, Size
, FALSE
);
325 /* Go to the next entry */
326 FreeEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)FreeEntry
+ Size
);
328 /* Check if that's all */
329 if ((PHEAP_ENTRY
)FreeEntry
>= Segment
->LastValidEntry
) return;
332 /* Update previous size if needed */
333 if (!(Flags
& HEAP_ENTRY_LAST_ENTRY
))
334 FreeEntry
->PreviousSize
= PreviousSize
;
338 RtlpRemoveFreeBlock(PHEAP Heap
,
339 PHEAP_FREE_ENTRY FreeEntry
,
343 SIZE_T Result
, RealSize
;
344 PLIST_ENTRY OldBlink
, OldFlink
;
346 // FIXME: Maybe use RemoveEntryList?
348 /* Remove the free block */
349 OldFlink
= FreeEntry
->FreeList
.Flink
;
350 OldBlink
= FreeEntry
->FreeList
.Blink
;
351 OldBlink
->Flink
= OldFlink
;
352 OldFlink
->Blink
= OldBlink
;
354 /* Update the freelists bitmap */
355 if ((OldFlink
== OldBlink
) &&
356 (Dedicated
|| (!Dedicated
&& FreeEntry
->Size
< HEAP_FREELISTS
)))
358 RtlpClearFreeListsBit(Heap
, FreeEntry
);
361 /* Fill with pattern if necessary */
363 (FreeEntry
->Flags
& HEAP_ENTRY_FILL_PATTERN
))
365 RealSize
= (FreeEntry
->Size
<< HEAP_ENTRY_SHIFT
) - sizeof(*FreeEntry
);
367 /* Deduct extra stuff from block's real size */
368 if (FreeEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
&&
369 RealSize
> sizeof(HEAP_FREE_ENTRY_EXTRA
))
371 RealSize
-= sizeof(HEAP_FREE_ENTRY_EXTRA
);
374 /* Check if the free filler is intact */
375 Result
= RtlCompareMemoryUlong((PCHAR
)(FreeEntry
+ 1),
379 if (Result
!= RealSize
)
381 DPRINT1("Free heap block %p modified at %p after it was freed\n",
383 (PCHAR
)(FreeEntry
+ 1) + Result
);
389 RtlpGetSizeOfBigBlock(PHEAP_ENTRY HeapEntry
)
391 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry
;
393 /* Get pointer to the containing record */
394 VirtualEntry
= CONTAINING_RECORD(HeapEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
396 /* Restore the real size */
397 return VirtualEntry
->CommitSize
- HeapEntry
->Size
;
400 PHEAP_UCR_DESCRIPTOR NTAPI
401 RtlpCreateUnCommittedRange(PHEAP_SEGMENT Segment
)
404 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
405 PHEAP_UCR_SEGMENT UcrSegment
;
406 PHEAP Heap
= Segment
->Heap
;
407 SIZE_T ReserveSize
= 16 * PAGE_SIZE
;
408 SIZE_T CommitSize
= 1 * PAGE_SIZE
;
411 DPRINT("RtlpCreateUnCommittedRange(%p)\n", Segment
);
413 /* Check if we have unused UCRs */
414 if (IsListEmpty(&Heap
->UCRList
))
416 /* Get a pointer to the first UCR segment */
417 UcrSegment
= CONTAINING_RECORD(&Heap
->UCRSegments
.Flink
, HEAP_UCR_SEGMENT
, ListEntry
);
419 /* Check the list of UCR segments */
420 if (IsListEmpty(&Heap
->UCRSegments
) ||
421 UcrSegment
->ReservedSize
== UcrSegment
->CommittedSize
)
423 /* We need to create a new one. Reserve 16 pages for it */
425 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
426 (PVOID
*)&UcrSegment
,
432 if (!NT_SUCCESS(Status
)) return NULL
;
434 /* Commit one page */
435 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
436 (PVOID
*)&UcrSegment
,
442 if (!NT_SUCCESS(Status
))
444 /* Release reserved memory */
445 ZwFreeVirtualMemory(NtCurrentProcess(),
446 (PVOID
*)&UcrDescriptor
,
453 UcrSegment
->ReservedSize
= ReserveSize
;
454 UcrSegment
->CommittedSize
= CommitSize
;
456 /* Add it to the head of the list */
457 InsertHeadList(&Heap
->UCRSegments
, &UcrSegment
->ListEntry
);
459 /* Get a pointer to the first available UCR descriptor */
460 UcrDescriptor
= (PHEAP_UCR_DESCRIPTOR
)(UcrSegment
+ 1);
464 /* It's possible to use existing UCR segment. Commit one more page */
465 UcrDescriptor
= (PHEAP_UCR_DESCRIPTOR
)((PCHAR
)UcrSegment
+ UcrSegment
->CommittedSize
);
466 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
467 (PVOID
*)&UcrDescriptor
,
473 if (!NT_SUCCESS(Status
)) return NULL
;
476 UcrSegment
->CommittedSize
+= CommitSize
;
479 /* There is a whole bunch of new UCR descriptors. Put them into the unused list */
480 while ((PCHAR
)UcrDescriptor
< ((PCHAR
)UcrSegment
+ UcrSegment
->CommittedSize
))
482 InsertTailList(&Heap
->UCRList
, &UcrDescriptor
->ListEntry
);
487 /* There are unused UCRs, just get the first one */
488 Entry
= RemoveHeadList(&Heap
->UCRList
);
489 UcrDescriptor
= CONTAINING_RECORD(Entry
, HEAP_UCR_DESCRIPTOR
, ListEntry
);
490 return UcrDescriptor
;
494 RtlpDestroyUnCommittedRange(PHEAP_SEGMENT Segment
,
495 PHEAP_UCR_DESCRIPTOR UcrDescriptor
)
498 UcrDescriptor
->Address
= NULL
;
499 UcrDescriptor
->Size
= 0;
501 /* Put it into the heap's list of unused UCRs */
502 InsertHeadList(&Segment
->Heap
->UCRList
, &UcrDescriptor
->ListEntry
);
506 RtlpInsertUnCommittedPages(PHEAP_SEGMENT Segment
,
511 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
513 DPRINT("RtlpInsertUnCommittedPages(%p %p %x)\n", Segment
, Address
, Size
);
515 /* Go through the list of UCR descriptors, they are sorted from lowest address
517 Current
= Segment
->UCRSegmentList
.Flink
;
518 while(Current
!= &Segment
->UCRSegmentList
)
520 UcrDescriptor
= CONTAINING_RECORD(Current
, HEAP_UCR_DESCRIPTOR
, SegmentEntry
);
522 if ((ULONG_PTR
)UcrDescriptor
->Address
> Address
)
524 /* Check for a really lucky case */
525 if ((Address
+ Size
) == (ULONG_PTR
)UcrDescriptor
->Address
)
528 UcrDescriptor
->Address
= (PVOID
)Address
;
529 UcrDescriptor
->Size
+= Size
;
533 /* We found the block after which the new one should go */
536 else if (((ULONG_PTR
)UcrDescriptor
->Address
+ UcrDescriptor
->Size
) == Address
)
538 /* Modify this entry */
539 Address
= (ULONG_PTR
)UcrDescriptor
->Address
;
540 Size
+= UcrDescriptor
->Size
;
542 /* Remove it from the list and destroy it */
543 RemoveEntryList(Current
);
544 RtlpDestroyUnCommittedRange(Segment
, UcrDescriptor
);
546 Segment
->NumberOfUnCommittedRanges
--;
550 /* Advance to the next descriptor */
551 Current
= Current
->Flink
;
555 /* Create a new UCR descriptor */
556 UcrDescriptor
= RtlpCreateUnCommittedRange(Segment
);
557 if (!UcrDescriptor
) return;
559 UcrDescriptor
->Address
= (PVOID
)Address
;
560 UcrDescriptor
->Size
= Size
;
562 /* "Current" is the descriptor after which our one should go */
563 InsertTailList(Current
, &UcrDescriptor
->SegmentEntry
);
565 DPRINT("Added segment UCR with base %p, size 0x%x\n", Address
, Size
);
567 /* Increase counters */
568 Segment
->NumberOfUnCommittedRanges
++;
571 PHEAP_FREE_ENTRY NTAPI
572 RtlpFindAndCommitPages(PHEAP Heap
,
573 PHEAP_SEGMENT Segment
,
575 PVOID AddressRequested
)
578 ULONG_PTR Address
= 0;
579 PHEAP_UCR_DESCRIPTOR UcrDescriptor
, PreviousUcr
= NULL
;
580 PHEAP_ENTRY FirstEntry
, LastEntry
, PreviousLastEntry
;
583 DPRINT("RtlpFindAndCommitPages(%p %p %x %p)\n", Heap
, Segment
, *Size
, Address
);
585 /* Go through UCRs in a segment */
586 Current
= Segment
->UCRSegmentList
.Flink
;
587 while(Current
!= &Segment
->UCRSegmentList
)
589 UcrDescriptor
= CONTAINING_RECORD(Current
, HEAP_UCR_DESCRIPTOR
, SegmentEntry
);
591 /* Check if we can use that one right away */
592 if (UcrDescriptor
->Size
>= *Size
&&
593 (UcrDescriptor
->Address
== AddressRequested
|| !AddressRequested
))
595 /* Get the address */
596 Address
= (ULONG_PTR
)UcrDescriptor
->Address
;
599 if (Heap
->CommitRoutine
)
601 Status
= Heap
->CommitRoutine(Heap
, (PVOID
*)&Address
, Size
);
605 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
613 DPRINT("Committed %d bytes at base %p, UCR size is %d\n", *Size
, Address
, UcrDescriptor
->Size
);
615 /* Fail in unsuccessful case */
616 if (!NT_SUCCESS(Status
))
618 DPRINT1("Committing page failed with status 0x%08X\n", Status
);
622 /* Update tracking numbers */
623 Segment
->NumberOfUnCommittedPages
-= *Size
/ PAGE_SIZE
;
625 /* Calculate first and last entries */
626 FirstEntry
= (PHEAP_ENTRY
)Address
;
628 if ((Segment
->LastEntryInSegment
->Flags
& HEAP_ENTRY_LAST_ENTRY
) &&
629 (ULONG_PTR
)(Segment
->LastEntryInSegment
+ Segment
->LastEntryInSegment
->Size
) == (ULONG_PTR
)UcrDescriptor
->Address
)
631 LastEntry
= Segment
->LastEntryInSegment
;
635 /* Go through the entries to find the last one */
638 LastEntry
= (PHEAP_ENTRY
)((ULONG_PTR
)PreviousUcr
->Address
+ PreviousUcr
->Size
);
640 LastEntry
= Segment
->FirstEntry
;
642 while (!(LastEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
644 PreviousLastEntry
= LastEntry
;
645 LastEntry
+= LastEntry
->Size
;
647 if ((ULONG_PTR
)LastEntry
>= (ULONG_PTR
)Segment
->LastValidEntry
||
648 LastEntry
->Size
== 0)
650 if (LastEntry
== (PHEAP_ENTRY
)Address
)
653 LastEntry
= PreviousLastEntry
;
657 DPRINT1("Last entry not found in a committed range near to %p\n", PreviousLastEntry
);
663 /* Unmark it as a last entry */
664 LastEntry
->Flags
&= ~HEAP_ENTRY_LAST_ENTRY
;
666 /* Update UCR descriptor */
667 UcrDescriptor
->Address
= (PVOID
)((ULONG_PTR
)UcrDescriptor
->Address
+ *Size
);
668 UcrDescriptor
->Size
-= *Size
;
670 DPRINT("Updating UcrDescriptor %p, new Address %p, size %d\n",
671 UcrDescriptor
, UcrDescriptor
->Address
, UcrDescriptor
->Size
);
673 /* Check if anything left in this UCR */
674 if (UcrDescriptor
->Size
== 0)
676 /* It's fully exhausted */
677 if (UcrDescriptor
->Address
== Segment
->LastValidEntry
)
679 FirstEntry
->Flags
= HEAP_ENTRY_LAST_ENTRY
;
680 Segment
->LastEntryInSegment
= FirstEntry
;
684 FirstEntry
->Flags
= 0;
685 Segment
->LastEntryInSegment
= Segment
->FirstEntry
;
688 /* This UCR needs to be removed because it became useless */
689 RemoveEntryList(&UcrDescriptor
->SegmentEntry
);
691 RtlpDestroyUnCommittedRange(Segment
, UcrDescriptor
);
692 Segment
->NumberOfUnCommittedRanges
--;
696 FirstEntry
->Flags
= HEAP_ENTRY_LAST_ENTRY
;
697 Segment
->LastEntryInSegment
= FirstEntry
;
700 /* Set various first entry fields*/
701 FirstEntry
->SegmentOffset
= LastEntry
->SegmentOffset
;
702 FirstEntry
->Size
= *Size
>> HEAP_ENTRY_SHIFT
;
703 FirstEntry
->PreviousSize
= LastEntry
->Size
;
705 /* Update previous size */
706 if (!(FirstEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
707 (FirstEntry
+ FirstEntry
->Size
)->PreviousSize
= FirstEntry
->Size
;
710 return (PHEAP_FREE_ENTRY
)FirstEntry
;
713 /* Advance to the next descriptor */
714 PreviousUcr
= UcrDescriptor
;
715 Current
= Current
->Flink
;
722 RtlpDeCommitFreeBlock(PHEAP Heap
,
723 PHEAP_FREE_ENTRY FreeEntry
,
726 PHEAP_SEGMENT Segment
;
727 PHEAP_ENTRY PrecedingInUseEntry
= NULL
, NextInUseEntry
= NULL
;
728 PHEAP_FREE_ENTRY NextFreeEntry
;
729 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
730 ULONG PrecedingSize
, NextSize
, DecommitSize
;
731 ULONG_PTR DecommitBase
;
734 DPRINT("Decommitting %p %p %x\n", Heap
, FreeEntry
, Size
);
736 /* We can't decommit if there is a commit routine! */
737 if (Heap
->CommitRoutine
)
739 /* Just add it back the usual way */
740 RtlpInsertFreeBlock(Heap
, FreeEntry
, Size
);
744 /* Get the segment */
745 Segment
= Heap
->Segments
[FreeEntry
->SegmentOffset
];
747 /* Get the preceding entry */
748 DecommitBase
= ROUND_UP(FreeEntry
, PAGE_SIZE
);
749 PrecedingSize
= (PHEAP_ENTRY
)DecommitBase
- (PHEAP_ENTRY
)FreeEntry
;
751 if (PrecedingSize
== 1)
753 /* Just 1 heap entry, increase the base/size */
754 DecommitBase
+= PAGE_SIZE
;
755 PrecedingSize
+= PAGE_SIZE
>> HEAP_ENTRY_SHIFT
;
757 else if (FreeEntry
->PreviousSize
&&
758 (DecommitBase
== (ULONG_PTR
)FreeEntry
))
760 PrecedingInUseEntry
= (PHEAP_ENTRY
)FreeEntry
- FreeEntry
->PreviousSize
;
763 /* Get the next entry */
764 NextFreeEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)FreeEntry
+ Size
);
765 DecommitSize
= ROUND_DOWN(NextFreeEntry
, PAGE_SIZE
);
766 NextSize
= (PHEAP_ENTRY
)NextFreeEntry
- (PHEAP_ENTRY
)DecommitSize
;
770 /* Just 1 heap entry, increase the size */
771 DecommitSize
-= PAGE_SIZE
;
772 NextSize
+= PAGE_SIZE
>> HEAP_ENTRY_SHIFT
;
774 else if (NextSize
== 0 &&
775 !(FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
777 NextInUseEntry
= (PHEAP_ENTRY
)NextFreeEntry
;
780 NextFreeEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)NextFreeEntry
- NextSize
);
782 /* Calculate real decommit size */
783 if (DecommitSize
> DecommitBase
)
785 DecommitSize
-= DecommitBase
;
789 /* Nothing to decommit */
790 RtlpInsertFreeBlock(Heap
, FreeEntry
, Size
);
794 /* A decommit is necessary. Create a UCR descriptor */
795 UcrDescriptor
= RtlpCreateUnCommittedRange(Segment
);
798 DPRINT1("HEAP: Failed to create UCR descriptor\n");
799 RtlpInsertFreeBlock(Heap
, FreeEntry
, PrecedingSize
);
803 /* Decommit the memory */
804 Status
= ZwFreeVirtualMemory(NtCurrentProcess(),
805 (PVOID
*)&DecommitBase
,
809 /* Delete that UCR. This is needed to assure there is an unused UCR entry in the list */
810 RtlpDestroyUnCommittedRange(Segment
, UcrDescriptor
);
812 if (!NT_SUCCESS(Status
))
814 RtlpInsertFreeBlock(Heap
, FreeEntry
, Size
);
818 /* Insert uncommitted pages */
819 RtlpInsertUnCommittedPages(Segment
, DecommitBase
, DecommitSize
);
820 Segment
->NumberOfUnCommittedPages
+= (DecommitSize
/ PAGE_SIZE
);
824 /* Adjust size of this free entry and insert it */
825 FreeEntry
->Flags
= HEAP_ENTRY_LAST_ENTRY
;
826 FreeEntry
->Size
= PrecedingSize
;
827 Heap
->TotalFreeSize
+= PrecedingSize
;
829 /* Set last entry in the segment to this entry */
830 Segment
->LastEntryInSegment
= (PHEAP_ENTRY
)FreeEntry
;
832 /* Insert it into the free list */
833 RtlpInsertFreeBlockHelper(Heap
, FreeEntry
, PrecedingSize
, FALSE
);
835 else if (PrecedingInUseEntry
)
837 /* Adjust preceding in use entry */
838 PrecedingInUseEntry
->Flags
|= HEAP_ENTRY_LAST_ENTRY
;
839 Segment
->LastEntryInSegment
= PrecedingInUseEntry
;
840 } else if ((ULONG_PTR
)Segment
->LastEntryInSegment
>= DecommitBase
&&
841 ((PCHAR
)Segment
->LastEntryInSegment
< ((PCHAR
)DecommitBase
+ DecommitSize
)))
843 /* Update this segment's last entry */
844 Segment
->LastEntryInSegment
= Segment
->FirstEntry
;
847 /* Now the next one */
850 /* Adjust size of this free entry and insert it */
851 NextFreeEntry
->Flags
= 0;
852 NextFreeEntry
->PreviousSize
= 0;
853 NextFreeEntry
->SegmentOffset
= Segment
->Entry
.SegmentOffset
;
854 NextFreeEntry
->Size
= NextSize
;
856 ((PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)NextFreeEntry
+ NextSize
))->PreviousSize
= NextSize
;
858 Heap
->TotalFreeSize
+= NextSize
;
859 RtlpInsertFreeBlockHelper(Heap
, NextFreeEntry
, NextSize
, FALSE
);
861 else if (NextInUseEntry
)
863 NextInUseEntry
->PreviousSize
= 0;
868 RtlpInitializeHeapSegment(PHEAP Heap
,
869 PHEAP_SEGMENT Segment
,
873 PVOID UncommittedBase
,
876 ULONG Pages
, CommitSize
;
877 PHEAP_ENTRY HeapEntry
;
878 USHORT PreviousSize
= 0, NewSize
;
881 Pages
= ((PCHAR
)LimitAddress
- (PCHAR
)BaseAddress
) / PAGE_SIZE
;
883 HeapEntry
= (PHEAP_ENTRY
)ROUND_UP(Segment
+ 1, HEAP_ENTRY_SIZE
);
885 DPRINT("RtlpInitializeHeapSegment(%p %p %x %x %p %p %p)\n", Heap
, Segment
, SegmentIndex
, Flags
, BaseAddress
, UncommittedBase
, LimitAddress
);
886 DPRINT("Pages %x, HeapEntry %p, sizeof(HEAP_SEGMENT) %x\n", Pages
, HeapEntry
, sizeof(HEAP_SEGMENT
));
888 /* Check if it's the first segment and remember its size */
889 if (Heap
== BaseAddress
)
890 PreviousSize
= Heap
->Entry
.Size
;
892 NewSize
= ((PCHAR
)HeapEntry
- (PCHAR
)Segment
) >> HEAP_ENTRY_SHIFT
;
894 if ((PVOID
)(HeapEntry
+ 1) >= UncommittedBase
)
896 /* Check if it goes beyond the limit */
897 if ((PVOID
)(HeapEntry
+ 1) >= LimitAddress
)
900 /* Need to commit memory */
901 CommitSize
= (PCHAR
)(HeapEntry
+ 1) - (PCHAR
)UncommittedBase
;
902 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
903 (PVOID
)&UncommittedBase
,
908 if (!NT_SUCCESS(Status
))
910 DPRINT1("Committing page failed with status 0x%08X\n", Status
);
914 DPRINT("Committed %d bytes at base %p\n", CommitSize
, UncommittedBase
);
916 /* Calcule the new uncommitted base */
917 UncommittedBase
= (PVOID
)((PCHAR
)UncommittedBase
+ CommitSize
);
920 /* Initialize the segment entry */
921 Segment
->Entry
.PreviousSize
= PreviousSize
;
922 Segment
->Entry
.Size
= NewSize
;
923 Segment
->Entry
.Flags
= HEAP_ENTRY_BUSY
;
924 Segment
->Entry
.SegmentOffset
= SegmentIndex
;
926 /* Initialize the segment itself */
927 Segment
->SegmentSignature
= HEAP_SEGMENT_SIGNATURE
;
928 Segment
->Heap
= Heap
;
929 Segment
->BaseAddress
= BaseAddress
;
930 Segment
->FirstEntry
= HeapEntry
;
931 Segment
->LastValidEntry
= (PHEAP_ENTRY
)((PCHAR
)BaseAddress
+ Pages
* PAGE_SIZE
);
932 Segment
->NumberOfPages
= Pages
;
933 Segment
->NumberOfUnCommittedPages
= ((PCHAR
)LimitAddress
- (PCHAR
)UncommittedBase
) / PAGE_SIZE
;
934 InitializeListHead(&Segment
->UCRSegmentList
);
936 /* Insert uncommitted pages into UCR (uncommitted ranges) list */
937 if (Segment
->NumberOfUnCommittedPages
)
939 RtlpInsertUnCommittedPages(Segment
, (ULONG_PTR
)UncommittedBase
, Segment
->NumberOfUnCommittedPages
* PAGE_SIZE
);
942 /* Set the segment index pointer */
943 Heap
->Segments
[SegmentIndex
] = Segment
;
945 /* Prepare a free heap entry */
946 HeapEntry
->Flags
= HEAP_ENTRY_LAST_ENTRY
;
947 HeapEntry
->PreviousSize
= Segment
->Entry
.Size
;
948 HeapEntry
->SegmentOffset
= SegmentIndex
;
950 /* Set last entry in segment */
951 Segment
->LastEntryInSegment
= HeapEntry
;
954 RtlpInsertFreeBlock(Heap
, (PHEAP_FREE_ENTRY
)HeapEntry
, (PHEAP_ENTRY
)UncommittedBase
- HeapEntry
);
960 RtlpDestroyHeapSegment(PHEAP_SEGMENT Segment
)
966 /* Make sure it's not user allocated */
967 if (Segment
->SegmentFlags
& HEAP_USER_ALLOCATED
) return;
969 BaseAddress
= Segment
->BaseAddress
;
970 DPRINT("Destroying segment %p, BA %p\n", Segment
, BaseAddress
);
972 /* Release virtual memory */
973 Status
= ZwFreeVirtualMemory(NtCurrentProcess(),
978 if (!NT_SUCCESS(Status
))
980 DPRINT1("HEAP: Failed to release segment's memory with status 0x%08X\n", Status
);
986 RtlpAddHeapToProcessList(PHEAP Heap
)
991 Peb
= RtlGetCurrentPeb();
993 /* Acquire the lock */
994 RtlEnterHeapLock(&RtlpProcessHeapsListLock
);
997 /* Check if max number of heaps reached */
998 if (Peb
->NumberOfHeaps
== Peb
->MaximumNumberOfHeaps
)
1000 // TODO: Handle this case
1004 /* Add the heap to the process heaps */
1005 Peb
->ProcessHeaps
[Peb
->NumberOfHeaps
] = Heap
;
1006 Peb
->NumberOfHeaps
++;
1007 Heap
->ProcessHeapsListIndex
= Peb
->NumberOfHeaps
;
1008 // } _SEH2_FINALLY {
1010 /* Release the lock */
1011 RtlLeaveHeapLock(&RtlpProcessHeapsListLock
);
1016 /* Usermode only! */
1018 RtlpRemoveHeapFromProcessList(PHEAP Heap
)
1021 PHEAP
*Current
, *Next
;
1025 Peb
= RtlGetCurrentPeb();
1027 /* Acquire the lock */
1028 RtlEnterHeapLock(&RtlpProcessHeapsListLock
);
1030 /* Check if we don't need anything to do */
1031 if ((Heap
->ProcessHeapsListIndex
== 0) ||
1032 (Heap
->ProcessHeapsListIndex
> Peb
->NumberOfHeaps
) ||
1033 (Peb
->NumberOfHeaps
== 0))
1035 /* Release the lock */
1036 RtlLeaveHeapLock(&RtlpProcessHeapsListLock
);
1041 /* The process actually has more than one heap.
1042 Use classic, lernt from university times algorithm for removing an entry
1043 from a static array */
1045 Current
= (PHEAP
*)&Peb
->ProcessHeaps
[Heap
->ProcessHeapsListIndex
- 1];
1048 /* How many items we need to shift to the left */
1049 Count
= Peb
->NumberOfHeaps
- (Heap
->ProcessHeapsListIndex
- 1);
1051 /* Move them all in a loop */
1054 /* Copy it and advance next pointer */
1057 /* Update its index */
1058 (*Current
)->ProcessHeapsListIndex
-= 1;
1060 /* Advance pointers */
1065 /* Decrease total number of heaps */
1066 Peb
->NumberOfHeaps
--;
1068 /* Zero last unused item */
1069 Peb
->ProcessHeaps
[Peb
->NumberOfHeaps
] = NULL
;
1070 Heap
->ProcessHeapsListIndex
= 0;
1072 /* Release the lock */
1073 RtlLeaveHeapLock(&RtlpProcessHeapsListLock
);
1076 PHEAP_FREE_ENTRY NTAPI
1077 RtlpCoalesceHeap(PHEAP Heap
)
1083 PHEAP_FREE_ENTRY NTAPI
1084 RtlpCoalesceFreeBlocks (PHEAP Heap
,
1085 PHEAP_FREE_ENTRY FreeEntry
,
1089 PHEAP_FREE_ENTRY CurrentEntry
, NextEntry
;
1091 /* Get the previous entry */
1092 CurrentEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)FreeEntry
- FreeEntry
->PreviousSize
);
1095 if (CurrentEntry
!= FreeEntry
&&
1096 !(CurrentEntry
->Flags
& HEAP_ENTRY_BUSY
) &&
1097 (*FreeSize
+ CurrentEntry
->Size
) <= HEAP_MAX_BLOCK_SIZE
)
1099 ASSERT(FreeEntry
->PreviousSize
== CurrentEntry
->Size
);
1101 /* Remove it if asked for */
1104 RtlpRemoveFreeBlock(Heap
, FreeEntry
, FALSE
, FALSE
);
1105 Heap
->TotalFreeSize
-= FreeEntry
->Size
;
1107 /* Remove it only once! */
1111 /* Remove previous entry too */
1112 RtlpRemoveFreeBlock(Heap
, CurrentEntry
, FALSE
, FALSE
);
1115 CurrentEntry
->Flags
= FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
;
1117 /* Update last entry in the segment */
1118 if (CurrentEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
)
1119 Heap
->Segments
[CurrentEntry
->SegmentOffset
]->LastEntryInSegment
= (PHEAP_ENTRY
)CurrentEntry
;
1121 /* Advance FreeEntry and update sizes */
1122 FreeEntry
= CurrentEntry
;
1123 *FreeSize
= *FreeSize
+ CurrentEntry
->Size
;
1124 Heap
->TotalFreeSize
-= CurrentEntry
->Size
;
1125 FreeEntry
->Size
= *FreeSize
;
1127 /* Also update previous size if needed */
1128 if (!(FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
1130 ((PHEAP_ENTRY
)FreeEntry
+ *FreeSize
)->PreviousSize
= *FreeSize
;
1134 /* Check the next block if it exists */
1135 if (!(FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
1137 NextEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)FreeEntry
+ *FreeSize
);
1139 if (!(NextEntry
->Flags
& HEAP_ENTRY_BUSY
) &&
1140 NextEntry
->Size
+ *FreeSize
<= HEAP_MAX_BLOCK_SIZE
)
1142 ASSERT(*FreeSize
== NextEntry
->PreviousSize
);
1144 /* Remove it if asked for */
1147 RtlpRemoveFreeBlock(Heap
, FreeEntry
, FALSE
, FALSE
);
1148 Heap
->TotalFreeSize
-= FreeEntry
->Size
;
1152 FreeEntry
->Flags
= NextEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
;
1154 /* Update last entry in the segment */
1155 if (FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
)
1156 Heap
->Segments
[FreeEntry
->SegmentOffset
]->LastEntryInSegment
= (PHEAP_ENTRY
)FreeEntry
;
1158 /* Remove next entry now */
1159 RtlpRemoveFreeBlock(Heap
, NextEntry
, FALSE
, FALSE
);
1162 *FreeSize
= *FreeSize
+ NextEntry
->Size
;
1163 Heap
->TotalFreeSize
-= NextEntry
->Size
;
1164 FreeEntry
->Size
= *FreeSize
;
1166 /* Also update previous size if needed */
1167 if (!(FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
1169 ((PHEAP_ENTRY
)FreeEntry
+ *FreeSize
)->PreviousSize
= *FreeSize
;
1176 PHEAP_FREE_ENTRY NTAPI
1177 RtlpExtendHeap(PHEAP Heap
,
1181 UCHAR Index
, EmptyIndex
;
1182 SIZE_T FreeSize
, CommitSize
, ReserveSize
;
1183 PHEAP_SEGMENT Segment
;
1184 PHEAP_FREE_ENTRY FreeEntry
;
1187 DPRINT("RtlpExtendHeap(%p %x)\n", Heap
, Size
);
1189 /* Calculate amount in pages */
1190 Pages
= (Size
+ PAGE_SIZE
- 1) / PAGE_SIZE
;
1191 FreeSize
= Pages
* PAGE_SIZE
;
1192 DPRINT("Pages %x, FreeSize %x. Going through segments...\n", Pages
, FreeSize
);
1194 /* Find an empty segment */
1195 EmptyIndex
= HEAP_SEGMENTS
;
1196 for (Index
= 0; Index
< HEAP_SEGMENTS
; Index
++)
1198 Segment
= Heap
->Segments
[Index
];
1200 if (Segment
) DPRINT("Segment[%d] %p with NOUCP %x\n", Index
, Segment
, Segment
->NumberOfUnCommittedPages
);
1202 /* Check if its size suits us */
1204 Pages
<= Segment
->NumberOfUnCommittedPages
)
1206 DPRINT("This segment is suitable\n");
1208 /* Commit needed amount */
1209 FreeEntry
= RtlpFindAndCommitPages(Heap
, Segment
, &FreeSize
, NULL
);
1211 /* Coalesce it with adjacent entries */
1214 FreeSize
= FreeSize
>> HEAP_ENTRY_SHIFT
;
1215 FreeEntry
= RtlpCoalesceFreeBlocks(Heap
, FreeEntry
, &FreeSize
, FALSE
);
1216 RtlpInsertFreeBlock(Heap
, FreeEntry
, FreeSize
);
1220 else if (!Segment
&&
1221 EmptyIndex
== HEAP_SEGMENTS
)
1223 /* Remember the first unused segment index */
1228 /* No luck, need to grow the heap */
1229 if ((Heap
->Flags
& HEAP_GROWABLE
) &&
1230 (EmptyIndex
!= HEAP_SEGMENTS
))
1234 /* Reserve the memory */
1235 if ((Size
+ PAGE_SIZE
) <= Heap
->SegmentReserve
)
1236 ReserveSize
= Heap
->SegmentReserve
;
1238 ReserveSize
= Size
+ PAGE_SIZE
;
1240 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1247 /* If it failed, retry again with a half division algorithm */
1248 while (!NT_SUCCESS(Status
) &&
1249 ReserveSize
!= Size
+ PAGE_SIZE
)
1253 if (ReserveSize
< (Size
+ PAGE_SIZE
))
1254 ReserveSize
= Size
+ PAGE_SIZE
;
1256 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1264 /* Proceed only if it's success */
1265 if (NT_SUCCESS(Status
))
1267 Heap
->SegmentReserve
+= ReserveSize
;
1269 /* Now commit the memory */
1270 if ((Size
+ PAGE_SIZE
) <= Heap
->SegmentCommit
)
1271 CommitSize
= Heap
->SegmentCommit
;
1273 CommitSize
= Size
+ PAGE_SIZE
;
1275 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1282 DPRINT("Committed %d bytes at base %p\n", CommitSize
, Segment
);
1284 /* Initialize heap segment if commit was successful */
1285 if (NT_SUCCESS(Status
))
1287 if (!RtlpInitializeHeapSegment(Heap
, Segment
, EmptyIndex
, 0, Segment
,
1288 (PCHAR
)Segment
+ CommitSize
, (PCHAR
)Segment
+ ReserveSize
))
1290 Status
= STATUS_NO_MEMORY
;
1294 /* If everything worked - cool */
1295 if (NT_SUCCESS(Status
)) return (PHEAP_FREE_ENTRY
)Segment
->FirstEntry
;
1297 DPRINT1("Committing failed with status 0x%08X\n", Status
);
1299 /* Nope, we failed. Free memory */
1300 ZwFreeVirtualMemory(NtCurrentProcess(),
1307 DPRINT1("Reserving failed with status 0x%08X\n", Status
);
1311 if (RtlpGetMode() == UserMode
)
1313 /* If coalescing on free is disabled in usermode, then do it here */
1314 if (Heap
->Flags
& HEAP_DISABLE_COALESCE_ON_FREE
)
1316 FreeEntry
= RtlpCoalesceHeap(Heap
);
1318 /* If it's a suitable one - return it */
1320 FreeEntry
->Size
>= Size
)
1330 /***********************************************************************
1333 * Handle of heap: Success
1339 RtlCreateHeap(ULONG Flags
,
1344 PRTL_HEAP_PARAMETERS Parameters
)
1346 PVOID CommittedAddress
= NULL
, UncommittedAddress
= NULL
;
1348 RTL_HEAP_PARAMETERS SafeParams
= {0};
1350 ULONG_PTR MaximumUserModeAddress
;
1351 SYSTEM_BASIC_INFORMATION SystemInformation
;
1352 MEMORY_BASIC_INFORMATION MemoryInfo
;
1353 ULONG NtGlobalFlags
= RtlGetNtGlobalFlags();
1354 ULONG HeapSegmentFlags
= 0;
1356 ULONG MaxBlockSize
, HeaderSize
;
1357 BOOLEAN AllocateLock
= FALSE
;
1359 /* Check for a special heap */
1360 if (RtlpPageHeapEnabled
&& !Addr
&& !Lock
)
1362 Heap
= RtlpPageHeapCreate(Flags
, Addr
, TotalSize
, CommitSize
, Lock
, Parameters
);
1363 if (Heap
) return Heap
;
1365 /* Reset a special Parameters == -1 hack */
1366 if ((ULONG_PTR
)Parameters
== (ULONG_PTR
)-1)
1369 DPRINT1("Enabling page heap failed\n");
1372 /* Check validation flags */
1373 if (!(Flags
& HEAP_SKIP_VALIDATION_CHECKS
) && (Flags
& ~HEAP_CREATE_VALID_MASK
))
1375 DPRINT1("Invalid flags 0x%08x, fixing...\n", Flags
);
1376 Flags
&= HEAP_CREATE_VALID_MASK
;
1379 /* TODO: Capture parameters, once we decide to use SEH */
1380 if (!Parameters
) Parameters
= &SafeParams
;
1382 /* Check global flags */
1383 if (NtGlobalFlags
& FLG_HEAP_DISABLE_COALESCING
)
1384 Flags
|= HEAP_DISABLE_COALESCE_ON_FREE
;
1386 if (NtGlobalFlags
& FLG_HEAP_ENABLE_FREE_CHECK
)
1387 Flags
|= HEAP_FREE_CHECKING_ENABLED
;
1389 if (NtGlobalFlags
& FLG_HEAP_ENABLE_TAIL_CHECK
)
1390 Flags
|= HEAP_TAIL_CHECKING_ENABLED
;
1392 if (RtlpGetMode() == UserMode
)
1394 /* Also check these flags if in usermode */
1395 if (NtGlobalFlags
& FLG_HEAP_VALIDATE_ALL
)
1396 Flags
|= HEAP_VALIDATE_ALL_ENABLED
;
1398 if (NtGlobalFlags
& FLG_HEAP_VALIDATE_PARAMETERS
)
1399 Flags
|= HEAP_VALIDATE_PARAMETERS_ENABLED
;
1401 if (NtGlobalFlags
& FLG_USER_STACK_TRACE_DB
)
1402 Flags
|= HEAP_CAPTURE_STACK_BACKTRACES
;
1405 Peb
= RtlGetCurrentPeb();
1407 /* Apply defaults for non-set parameters */
1408 if (!Parameters
->SegmentCommit
) Parameters
->SegmentCommit
= Peb
->HeapSegmentCommit
;
1409 if (!Parameters
->SegmentReserve
) Parameters
->SegmentReserve
= Peb
->HeapSegmentReserve
;
1410 if (!Parameters
->DeCommitFreeBlockThreshold
) Parameters
->DeCommitFreeBlockThreshold
= Peb
->HeapDeCommitFreeBlockThreshold
;
1411 if (!Parameters
->DeCommitTotalFreeThreshold
) Parameters
->DeCommitTotalFreeThreshold
= Peb
->HeapDeCommitTotalFreeThreshold
;
1415 /* Apply defaults for non-set parameters */
1417 if (!Parameters
->SegmentCommit
) Parameters
->SegmentCommit
= MmHeapSegmentCommit
;
1418 if (!Parameters
->SegmentReserve
) Parameters
->SegmentReserve
= MmHeapSegmentReserve
;
1419 if (!Parameters
->DeCommitFreeBlockThreshold
) Parameters
->DeCommitFreeBlockThreshold
= MmHeapDeCommitFreeBlockThreshold
;
1420 if (!Parameters
->DeCommitTotalFreeThreshold
) Parameters
->DeCommitTotalFreeThreshold
= MmHeapDeCommitTotalFreeThreshold
;
1424 // FIXME: Move to memory manager
1425 if (!Parameters
->SegmentCommit
) Parameters
->SegmentCommit
= PAGE_SIZE
* 2;
1426 if (!Parameters
->SegmentReserve
) Parameters
->SegmentReserve
= 1048576;
1427 if (!Parameters
->DeCommitFreeBlockThreshold
) Parameters
->DeCommitFreeBlockThreshold
= PAGE_SIZE
;
1428 if (!Parameters
->DeCommitTotalFreeThreshold
) Parameters
->DeCommitTotalFreeThreshold
= 65536;
1430 /* Get the max um address */
1431 Status
= ZwQuerySystemInformation(SystemBasicInformation
,
1433 sizeof(SystemInformation
),
1436 if (!NT_SUCCESS(Status
))
1438 DPRINT1("Getting max usermode address failed with status 0x%08x\n", Status
);
1442 MaximumUserModeAddress
= SystemInformation
.MaximumUserModeAddress
;
1444 /* Calculate max alloc size */
1445 if (!Parameters
->MaximumAllocationSize
)
1446 Parameters
->MaximumAllocationSize
= MaximumUserModeAddress
- (ULONG_PTR
)0x10000 - PAGE_SIZE
;
1448 MaxBlockSize
= 0x80000 - PAGE_SIZE
;
1450 if (!Parameters
->VirtualMemoryThreshold
||
1451 Parameters
->VirtualMemoryThreshold
> MaxBlockSize
)
1453 Parameters
->VirtualMemoryThreshold
= MaxBlockSize
;
1456 /* Check reserve/commit sizes and set default values */
1459 CommitSize
= PAGE_SIZE
;
1461 TotalSize
= ROUND_UP(TotalSize
, PAGE_SIZE
);
1463 TotalSize
= 64 * PAGE_SIZE
;
1467 /* Round up the commit size to be at least the page size */
1468 CommitSize
= ROUND_UP(CommitSize
, PAGE_SIZE
);
1471 TotalSize
= ROUND_UP(TotalSize
, PAGE_SIZE
);
1473 TotalSize
= ROUND_UP(CommitSize
, 16 * PAGE_SIZE
);
1476 /* Call special heap */
1477 if (RtlpHeapIsSpecial(Flags
))
1478 return RtlDebugCreateHeap(Flags
, Addr
, TotalSize
, CommitSize
, Lock
, Parameters
);
1480 /* Calculate header size */
1481 HeaderSize
= sizeof(HEAP
);
1482 if (!(Flags
& HEAP_NO_SERIALIZE
))
1486 Flags
|= HEAP_LOCK_USER_ALLOCATED
;
1490 HeaderSize
+= sizeof(HEAP_LOCK
);
1491 AllocateLock
= TRUE
;
1496 /* Invalid parameters */
1500 /* See if we are already provided with an address for the heap */
1503 if (Parameters
->CommitRoutine
)
1505 /* There is a commit routine, so no problem here, check params */
1506 if ((Flags
& HEAP_GROWABLE
) ||
1507 !Parameters
->InitialCommit
||
1508 !Parameters
->InitialReserve
||
1509 (Parameters
->InitialCommit
> Parameters
->InitialReserve
))
1515 /* Calculate committed and uncommitted addresses */
1516 CommittedAddress
= Addr
;
1517 UncommittedAddress
= (PCHAR
)Addr
+ Parameters
->InitialCommit
;
1518 TotalSize
= Parameters
->InitialReserve
;
1520 /* Zero the initial page ourselves */
1521 RtlZeroMemory(CommittedAddress
, PAGE_SIZE
);
1525 /* Commit routine is absent, so query how much memory caller reserved */
1526 Status
= ZwQueryVirtualMemory(NtCurrentProcess(),
1528 MemoryBasicInformation
,
1533 if (!NT_SUCCESS(Status
))
1535 DPRINT1("Querying amount of user supplied memory failed with status 0x%08X\n", Status
);
1540 if (MemoryInfo
.BaseAddress
!= Addr
||
1541 MemoryInfo
.State
== MEM_FREE
)
1546 /* Validation checks passed, set committed/uncommitted addresses */
1547 CommittedAddress
= Addr
;
1549 /* Check if it's committed or not */
1550 if (MemoryInfo
.State
== MEM_COMMIT
)
1552 /* Zero it out because it's already committed */
1553 RtlZeroMemory(CommittedAddress
, PAGE_SIZE
);
1555 /* Calculate uncommitted address value */
1556 CommitSize
= MemoryInfo
.RegionSize
;
1557 TotalSize
= CommitSize
;
1558 UncommittedAddress
= (PCHAR
)Addr
+ CommitSize
;
1560 /* Check if uncommitted address is reserved */
1561 Status
= ZwQueryVirtualMemory(NtCurrentProcess(),
1563 MemoryBasicInformation
,
1568 if (NT_SUCCESS(Status
) &&
1569 MemoryInfo
.State
== MEM_RESERVE
)
1571 /* It is, so add it up to the reserve size */
1572 TotalSize
+= MemoryInfo
.RegionSize
;
1577 /* It's not committed, inform following code that a commit is necessary */
1578 CommitSize
= PAGE_SIZE
;
1579 UncommittedAddress
= Addr
;
1583 /* Mark this as a user-committed mem */
1584 HeapSegmentFlags
= HEAP_USER_ALLOCATED
;
1589 /* Check commit routine */
1590 if (Parameters
->CommitRoutine
) return NULL
;
1592 /* Reserve memory */
1593 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1600 if (!NT_SUCCESS(Status
))
1602 DPRINT1("Failed to reserve memory with status 0x%08x\n", Status
);
1606 /* Set base addresses */
1607 CommittedAddress
= Heap
;
1608 UncommittedAddress
= Heap
;
1611 /* Check if we need to commit something */
1612 if (CommittedAddress
== UncommittedAddress
)
1614 /* Commit the required size */
1615 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1622 DPRINT("Committed %d bytes at base %p\n", CommitSize
, CommittedAddress
);
1624 if (!NT_SUCCESS(Status
))
1626 DPRINT1("Failure, Status 0x%08X\n", Status
);
1628 /* Release memory if it was reserved */
1629 if (!Addr
) ZwFreeVirtualMemory(NtCurrentProcess(),
1637 /* Calculate new uncommitted address */
1638 UncommittedAddress
= (PCHAR
)UncommittedAddress
+ CommitSize
;
1641 DPRINT("Created heap %p, CommitSize %x, ReserveSize %x\n", Heap
, CommitSize
, TotalSize
);
1643 /* Initialize the heap */
1644 RtlpInitializeHeap(Heap
, &HeaderSize
, Flags
, AllocateLock
, Lock
);
1646 /* Initialize heap's first segment */
1647 if (!RtlpInitializeHeapSegment(Heap
,
1648 (PHEAP_SEGMENT
)((PCHAR
)Heap
+ HeaderSize
),
1653 (PCHAR
)CommittedAddress
+ TotalSize
))
1655 DPRINT1("Failed to initialize heap segment\n");
1659 /* Set other data */
1660 Heap
->ProcessHeapsListIndex
= 0;
1661 Heap
->SegmentCommit
= Parameters
->SegmentCommit
;
1662 Heap
->SegmentReserve
= Parameters
->SegmentReserve
;
1663 Heap
->DeCommitFreeBlockThreshold
= Parameters
->DeCommitFreeBlockThreshold
>> HEAP_ENTRY_SHIFT
;
1664 Heap
->DeCommitTotalFreeThreshold
= Parameters
->DeCommitTotalFreeThreshold
>> HEAP_ENTRY_SHIFT
;
1665 Heap
->MaximumAllocationSize
= Parameters
->MaximumAllocationSize
;
1666 Heap
->VirtualMemoryThreshold
= ROUND_UP(Parameters
->VirtualMemoryThreshold
, HEAP_ENTRY_SIZE
) >> HEAP_ENTRY_SHIFT
;
1667 Heap
->CommitRoutine
= Parameters
->CommitRoutine
;
1670 if (Flags
& HEAP_CREATE_ALIGN_16
)
1672 Heap
->AlignMask
= (ULONG
)~15;
1673 Heap
->AlignRound
= 15 + sizeof(HEAP_ENTRY
);
1677 Heap
->AlignMask
= (ULONG
)~(HEAP_ENTRY_SIZE
- 1);
1678 Heap
->AlignRound
= HEAP_ENTRY_SIZE
- 1 + sizeof(HEAP_ENTRY
);
1681 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
1682 Heap
->AlignRound
+= HEAP_ENTRY_SIZE
;
1684 /* Add heap to process list in case of usermode heap */
1685 if (RtlpGetMode() == UserMode
)
1687 RtlpAddHeapToProcessList(Heap
);
1689 // FIXME: What about lookasides?
1692 DPRINT("Heap %p, flags 0x%08x\n", Heap
, Heap
->Flags
);
1696 /***********************************************************************
1705 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1706 * Failure: The Heap handle, if heap is the process heap.
1709 RtlDestroyHeap(HANDLE HeapPtr
) /* [in] Handle of heap */
1711 PHEAP Heap
= (PHEAP
)HeapPtr
;
1712 PLIST_ENTRY Current
;
1713 PHEAP_UCR_SEGMENT UcrSegment
;
1714 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry
;
1718 PHEAP_SEGMENT Segment
;
1720 if (!HeapPtr
) return NULL
;
1722 /* Call page heap routine if required */
1723 if (Heap
->ForceFlags
& HEAP_FLAG_PAGE_ALLOCS
) return RtlpPageHeapDestroy(HeapPtr
);
1725 /* Call special heap */
1726 if (RtlpHeapIsSpecial(Heap
->Flags
))
1728 if (!RtlDebugDestroyHeap(Heap
)) return HeapPtr
;
1731 /* Check for a process heap */
1732 if (RtlpGetMode() == UserMode
&&
1733 HeapPtr
== NtCurrentPeb()->ProcessHeap
) return HeapPtr
;
1735 /* Free up all big allocations */
1736 Current
= Heap
->VirtualAllocdBlocks
.Flink
;
1737 while (Current
!= &Heap
->VirtualAllocdBlocks
)
1739 VirtualEntry
= CONTAINING_RECORD(Current
, HEAP_VIRTUAL_ALLOC_ENTRY
, Entry
);
1740 BaseAddress
= (PVOID
)VirtualEntry
;
1741 Current
= Current
->Flink
;
1743 ZwFreeVirtualMemory(NtCurrentProcess(),
1749 /* Delete tags and remove heap from the process heaps list in user mode */
1750 if (RtlpGetMode() == UserMode
)
1752 // FIXME DestroyTags
1753 RtlpRemoveHeapFromProcessList(Heap
);
1756 /* Delete the heap lock */
1757 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
1759 /* Delete it if it wasn't user allocated */
1760 if (!(Heap
->Flags
& HEAP_LOCK_USER_ALLOCATED
))
1761 RtlDeleteHeapLock(Heap
->LockVariable
);
1763 /* Clear out the lock variable */
1764 Heap
->LockVariable
= NULL
;
1767 /* Free UCR segments if any were created */
1768 Current
= Heap
->UCRSegments
.Flink
;
1769 while(Current
!= &Heap
->UCRSegments
)
1771 UcrSegment
= CONTAINING_RECORD(Current
, HEAP_UCR_SEGMENT
, ListEntry
);
1773 /* Advance to the next descriptor */
1774 Current
= Current
->Flink
;
1776 BaseAddress
= (PVOID
)UcrSegment
;
1779 /* Release that memory */
1780 ZwFreeVirtualMemory(NtCurrentProcess(),
1786 /* Go through segments and destroy them */
1787 for (i
= HEAP_SEGMENTS
- 1; i
>= 0; i
--)
1789 Segment
= Heap
->Segments
[i
];
1790 if (Segment
) RtlpDestroyHeapSegment(Segment
);
1797 RtlpSplitEntry(PHEAP Heap
,
1798 PHEAP_FREE_ENTRY FreeBlock
,
1799 SIZE_T AllocationSize
,
1803 PHEAP_FREE_ENTRY SplitBlock
, SplitBlock2
;
1805 PHEAP_ENTRY InUseEntry
;
1808 /* Save flags, update total free size */
1809 FreeFlags
= FreeBlock
->Flags
;
1810 Heap
->TotalFreeSize
-= FreeBlock
->Size
;
1812 /* Make this block an in-use one */
1813 InUseEntry
= (PHEAP_ENTRY
)FreeBlock
;
1814 InUseEntry
->Flags
= HEAP_ENTRY_BUSY
;
1815 InUseEntry
->SmallTagIndex
= 0;
1817 /* Calculate the extra amount */
1818 FreeSize
= InUseEntry
->Size
- Index
;
1820 /* Update it's size fields (we don't need their data anymore) */
1821 InUseEntry
->Size
= Index
;
1822 InUseEntry
->UnusedBytes
= AllocationSize
- Size
;
1824 /* If there is something to split - do the split */
1827 /* Don't split if resulting entry can't contain any payload data
1828 (i.e. being just HEAP_ENTRY_SIZE) */
1831 /* Increase sizes of the in-use entry */
1833 InUseEntry
->UnusedBytes
+= sizeof(HEAP_ENTRY
);
1837 /* Calculate a pointer to the new entry */
1838 SplitBlock
= (PHEAP_FREE_ENTRY
)(InUseEntry
+ Index
);
1841 SplitBlock
->Flags
= FreeFlags
;
1842 SplitBlock
->SegmentOffset
= InUseEntry
->SegmentOffset
;
1843 SplitBlock
->Size
= FreeSize
;
1844 SplitBlock
->PreviousSize
= Index
;
1846 /* Check if it's the last entry */
1847 if (FreeFlags
& HEAP_ENTRY_LAST_ENTRY
)
1849 /* Insert it to the free list if it's the last entry */
1850 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
1851 Heap
->TotalFreeSize
+= FreeSize
;
1855 /* Not so easy - need to update next's previous size too */
1856 SplitBlock2
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
);
1858 if (SplitBlock2
->Flags
& HEAP_ENTRY_BUSY
)
1860 SplitBlock2
->PreviousSize
= (USHORT
)FreeSize
;
1861 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
1862 Heap
->TotalFreeSize
+= FreeSize
;
1866 /* Even more complex - the next entry is free, so we can merge them into one! */
1867 SplitBlock
->Flags
= SplitBlock2
->Flags
;
1869 /* Remove that next entry */
1870 RtlpRemoveFreeBlock(Heap
, SplitBlock2
, FALSE
, FALSE
);
1873 FreeSize
+= SplitBlock2
->Size
;
1874 Heap
->TotalFreeSize
-= SplitBlock2
->Size
;
1876 if (FreeSize
<= HEAP_MAX_BLOCK_SIZE
)
1878 /* Insert it back */
1879 SplitBlock
->Size
= FreeSize
;
1881 /* Don't forget to update previous size of the next entry! */
1882 if (!(SplitBlock
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
1884 ((PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
))->PreviousSize
= FreeSize
;
1887 /* Actually insert it */
1888 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, (USHORT
)FreeSize
, FALSE
);
1890 /* Update total size */
1891 Heap
->TotalFreeSize
+= FreeSize
;
1895 /* Resulting block is quite big */
1896 RtlpInsertFreeBlock(Heap
, SplitBlock
, FreeSize
);
1901 /* Reset flags of the free entry */
1904 /* Update last entry in segment */
1905 if (SplitBlock
->Flags
& HEAP_ENTRY_LAST_ENTRY
)
1907 Heap
->Segments
[SplitBlock
->SegmentOffset
]->LastEntryInSegment
= (PHEAP_ENTRY
)SplitBlock
;
1912 /* Set last entry flag */
1913 if (FreeFlags
& HEAP_ENTRY_LAST_ENTRY
)
1914 InUseEntry
->Flags
|= HEAP_ENTRY_LAST_ENTRY
;
1920 RtlpAllocateNonDedicated(PHEAP Heap
,
1923 SIZE_T AllocationSize
,
1927 PLIST_ENTRY FreeListHead
, Next
;
1928 PHEAP_FREE_ENTRY FreeBlock
;
1929 PHEAP_ENTRY InUseEntry
;
1930 PHEAP_ENTRY_EXTRA Extra
;
1931 EXCEPTION_RECORD ExceptionRecord
;
1933 /* Go through the zero list to find a place where to insert the new entry */
1934 FreeListHead
= &Heap
->FreeLists
[0];
1936 /* Start from the largest block to reduce time */
1937 Next
= FreeListHead
->Blink
;
1938 if (FreeListHead
!= Next
)
1940 FreeBlock
= CONTAINING_RECORD(Next
, HEAP_FREE_ENTRY
, FreeList
);
1942 if (FreeBlock
->Size
>= Index
)
1944 /* Our request is smaller than the largest entry in the zero list */
1946 /* Go through the list to find insertion place */
1947 Next
= FreeListHead
->Flink
;
1948 while (FreeListHead
!= Next
)
1950 FreeBlock
= CONTAINING_RECORD(Next
, HEAP_FREE_ENTRY
, FreeList
);
1952 if (FreeBlock
->Size
>= Index
)
1954 /* Found minimally fitting entry. Proceed to either using it as it is
1955 or splitting it to two entries */
1956 RemoveEntryList(&FreeBlock
->FreeList
);
1959 InUseEntry
= RtlpSplitEntry(Heap
, FreeBlock
, AllocationSize
, Index
, Size
);
1961 /* Release the lock */
1962 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
1964 /* Zero memory if that was requested */
1965 if (Flags
& HEAP_ZERO_MEMORY
)
1966 RtlZeroMemory(InUseEntry
+ 1, Size
);
1967 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
1969 /* Fill this block with a special pattern */
1970 RtlFillMemoryUlong(InUseEntry
+ 1, Size
& ~0x3, ARENA_INUSE_FILLER
);
1973 /* Fill tail of the block with a special pattern too if requested */
1974 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
1976 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
, sizeof(HEAP_ENTRY
), HEAP_TAIL_FILL
);
1977 InUseEntry
->Flags
|= HEAP_ENTRY_FILL_PATTERN
;
1980 /* Prepare extra if it's present */
1981 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
1983 Extra
= RtlpGetExtraStuffPointer(InUseEntry
);
1984 RtlZeroMemory(Extra
, sizeof(HEAP_ENTRY_EXTRA
));
1989 /* Return pointer to the */
1990 return InUseEntry
+ 1;
1993 /* Advance to the next entry */
1999 /* Extend the heap, 0 list didn't have anything suitable */
2000 FreeBlock
= RtlpExtendHeap(Heap
, AllocationSize
);
2002 /* Use the new biggest entry we've got */
2005 RemoveEntryList(&FreeBlock
->FreeList
);
2008 InUseEntry
= RtlpSplitEntry(Heap
, FreeBlock
, AllocationSize
, Index
, Size
);
2010 /* Release the lock */
2011 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2013 /* Zero memory if that was requested */
2014 if (Flags
& HEAP_ZERO_MEMORY
)
2015 RtlZeroMemory(InUseEntry
+ 1, Size
);
2016 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
2018 /* Fill this block with a special pattern */
2019 RtlFillMemoryUlong(InUseEntry
+ 1, Size
& ~0x3, ARENA_INUSE_FILLER
);
2022 /* Fill tail of the block with a special pattern too if requested */
2023 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
2025 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
, sizeof(HEAP_ENTRY
), HEAP_TAIL_FILL
);
2026 InUseEntry
->Flags
|= HEAP_ENTRY_FILL_PATTERN
;
2029 /* Prepare extra if it's present */
2030 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
2032 Extra
= RtlpGetExtraStuffPointer(InUseEntry
);
2033 RtlZeroMemory(Extra
, sizeof(HEAP_ENTRY_EXTRA
));
2038 /* Return pointer to the */
2039 return InUseEntry
+ 1;
2042 /* Really unfortunate, out of memory condition */
2043 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_NO_MEMORY
);
2045 /* Generate an exception */
2046 if (Flags
& HEAP_GENERATE_EXCEPTIONS
)
2048 ExceptionRecord
.ExceptionCode
= STATUS_NO_MEMORY
;
2049 ExceptionRecord
.ExceptionRecord
= NULL
;
2050 ExceptionRecord
.NumberParameters
= 1;
2051 ExceptionRecord
.ExceptionFlags
= 0;
2052 ExceptionRecord
.ExceptionInformation
[0] = AllocationSize
;
2054 RtlRaiseException(&ExceptionRecord
);
2057 /* Release the lock */
2058 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2059 DPRINT1("HEAP: Allocation failed!\n");
2060 DPRINT1("Flags %x\n", Heap
->Flags
);
2064 /***********************************************************************
2065 * HeapAlloc (KERNEL32.334)
2067 * Pointer to allocated memory block
2069 * 0x7d030f60--invalid flags in RtlHeapAllocate
2073 RtlAllocateHeap(IN PVOID HeapPtr
,
2077 PHEAP Heap
= (PHEAP
)HeapPtr
;
2078 PULONG FreeListsInUse
;
2079 ULONG FreeListsInUseUlong
;
2080 SIZE_T AllocationSize
;
2082 PLIST_ENTRY FreeListHead
;
2083 PHEAP_ENTRY InUseEntry
;
2084 PHEAP_FREE_ENTRY FreeBlock
;
2085 ULONG InUseIndex
, i
;
2087 EXCEPTION_RECORD ExceptionRecord
;
2088 BOOLEAN HeapLocked
= FALSE
;
2089 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualBlock
= NULL
;
2090 PHEAP_ENTRY_EXTRA Extra
;
2094 Flags
|= Heap
->ForceFlags
;
2096 /* Call special heap */
2097 if (RtlpHeapIsSpecial(Flags
))
2098 return RtlDebugAllocateHeap(Heap
, Flags
, Size
);
2100 /* Check for the maximum size */
2101 if (Size
>= 0x80000000)
2103 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_NO_MEMORY
);
2104 DPRINT1("HEAP: Allocation failed!\n");
2108 if (Flags
& (HEAP_CREATE_ENABLE_TRACING
|
2109 HEAP_CREATE_ALIGN_16
))
2111 DPRINT1("HEAP: RtlAllocateHeap is called with unsupported flags %x, ignoring\n", Flags
);
2114 //DPRINT("RtlAllocateHeap(%p %x %x)\n", Heap, Flags, Size);
2116 /* Calculate allocation size and index */
2118 AllocationSize
= Size
;
2121 AllocationSize
= (AllocationSize
+ Heap
->AlignRound
) & Heap
->AlignMask
;
2122 Index
= AllocationSize
>> HEAP_ENTRY_SHIFT
;
2124 /* Acquire the lock if necessary */
2125 if (!(Flags
& HEAP_NO_SERIALIZE
))
2127 RtlEnterHeapLock(Heap
->LockVariable
);
2131 /* Depending on the size, the allocation is going to be done from dedicated,
2132 non-dedicated lists or a virtual block of memory */
2133 if (Index
< HEAP_FREELISTS
)
2135 FreeListHead
= &Heap
->FreeLists
[Index
];
2137 if (!IsListEmpty(FreeListHead
))
2139 /* There is a free entry in this list */
2140 FreeBlock
= CONTAINING_RECORD(FreeListHead
->Blink
,
2144 /* Save flags and remove the free entry */
2145 FreeFlags
= FreeBlock
->Flags
;
2146 RtlpRemoveFreeBlock(Heap
, FreeBlock
, TRUE
, FALSE
);
2148 /* Update the total free size of the heap */
2149 Heap
->TotalFreeSize
-= Index
;
2151 /* Initialize this block */
2152 InUseEntry
= (PHEAP_ENTRY
)FreeBlock
;
2153 InUseEntry
->Flags
= HEAP_ENTRY_BUSY
| (FreeFlags
& HEAP_ENTRY_LAST_ENTRY
);
2154 InUseEntry
->UnusedBytes
= AllocationSize
- Size
;
2155 InUseEntry
->SmallTagIndex
= 0;
2159 /* Find smallest free block which this request could fit in */
2160 InUseIndex
= Index
>> 5;
2161 FreeListsInUse
= &Heap
->u
.FreeListsInUseUlong
[InUseIndex
];
2163 /* This bit magic disables all sizes which are less than the requested allocation size */
2164 FreeListsInUseUlong
= *FreeListsInUse
++ & ~((1 << ((ULONG
)Index
& 0x1f)) - 1);
2166 /* If size is definitily more than our lists - go directly to the non-dedicated one */
2168 return RtlpAllocateNonDedicated(Heap
, Flags
, Size
, AllocationSize
, Index
, HeapLocked
);
2170 /* Go through the list */
2171 for (i
= InUseIndex
; i
< 4; i
++)
2173 if (FreeListsInUseUlong
)
2175 FreeListHead
= &Heap
->FreeLists
[i
* 32];
2179 if (i
< 3) FreeListsInUseUlong
= *FreeListsInUse
++;
2182 /* Nothing found, search in the non-dedicated list */
2184 return RtlpAllocateNonDedicated(Heap
, Flags
, Size
, AllocationSize
, Index
, HeapLocked
);
2186 /* That list is found, now calculate exact block */
2187 FreeListHead
+= RtlpFindLeastSetBit(FreeListsInUseUlong
);
2189 /* Take this entry and remove it from the list of free blocks */
2190 FreeBlock
= CONTAINING_RECORD(FreeListHead
->Blink
,
2193 RtlpRemoveFreeBlock(Heap
, FreeBlock
, TRUE
, FALSE
);
2196 InUseEntry
= RtlpSplitEntry(Heap
, FreeBlock
, AllocationSize
, Index
, Size
);
2199 /* Release the lock */
2200 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2202 /* Zero memory if that was requested */
2203 if (Flags
& HEAP_ZERO_MEMORY
)
2204 RtlZeroMemory(InUseEntry
+ 1, Size
);
2205 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
2207 /* Fill this block with a special pattern */
2208 RtlFillMemoryUlong(InUseEntry
+ 1, Size
& ~0x3, ARENA_INUSE_FILLER
);
2211 /* Fill tail of the block with a special pattern too if requested */
2212 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
2214 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
, sizeof(HEAP_ENTRY
), HEAP_TAIL_FILL
);
2215 InUseEntry
->Flags
|= HEAP_ENTRY_FILL_PATTERN
;
2218 /* Prepare extra if it's present */
2219 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
2221 Extra
= RtlpGetExtraStuffPointer(InUseEntry
);
2222 RtlZeroMemory(Extra
, sizeof(HEAP_ENTRY_EXTRA
));
2227 /* User data starts right after the entry's header */
2228 return InUseEntry
+ 1;
2230 else if (Index
<= Heap
->VirtualMemoryThreshold
)
2232 /* The block is too large for dedicated lists, but fine for a non-dedicated one */
2233 return RtlpAllocateNonDedicated(Heap
, Flags
, Size
, AllocationSize
, Index
, HeapLocked
);
2235 else if (Heap
->Flags
& HEAP_GROWABLE
)
2237 /* We've got a very big allocation request, satisfy it by directly allocating virtual memory */
2238 AllocationSize
+= sizeof(HEAP_VIRTUAL_ALLOC_ENTRY
) - sizeof(HEAP_ENTRY
);
2240 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
2241 (PVOID
*)&VirtualBlock
,
2247 if (!NT_SUCCESS(Status
))
2250 /* Release the lock */
2251 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2252 DPRINT1("HEAP: Allocation failed!\n");
2256 /* Initialize the newly allocated block */
2257 VirtualBlock
->BusyBlock
.Size
= (AllocationSize
- Size
);
2258 VirtualBlock
->BusyBlock
.Flags
= HEAP_ENTRY_VIRTUAL_ALLOC
| HEAP_ENTRY_EXTRA_PRESENT
| HEAP_ENTRY_BUSY
;
2259 VirtualBlock
->CommitSize
= AllocationSize
;
2260 VirtualBlock
->ReserveSize
= AllocationSize
;
2262 /* Insert it into the list of virtual allocations */
2263 InsertTailList(&Heap
->VirtualAllocdBlocks
, &VirtualBlock
->Entry
);
2265 /* Release the lock */
2266 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2268 /* Return pointer to user data */
2269 return VirtualBlock
+ 1;
2272 /* Generate an exception */
2273 if (Flags
& HEAP_GENERATE_EXCEPTIONS
)
2275 ExceptionRecord
.ExceptionCode
= STATUS_NO_MEMORY
;
2276 ExceptionRecord
.ExceptionRecord
= NULL
;
2277 ExceptionRecord
.NumberParameters
= 1;
2278 ExceptionRecord
.ExceptionFlags
= 0;
2279 ExceptionRecord
.ExceptionInformation
[0] = AllocationSize
;
2281 RtlRaiseException(&ExceptionRecord
);
2284 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_BUFFER_TOO_SMALL
);
2286 /* Release the lock */
2287 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2288 DPRINT1("HEAP: Allocation failed!\n");
2293 /***********************************************************************
2294 * HeapFree (KERNEL32.338)
2301 BOOLEAN NTAPI
RtlFreeHeap(
2302 HANDLE HeapPtr
, /* [in] Handle of heap */
2303 ULONG Flags
, /* [in] Heap freeing flags */
2304 PVOID Ptr
/* [in] Address of memory to free */
2308 PHEAP_ENTRY HeapEntry
;
2309 USHORT TagIndex
= 0;
2311 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry
;
2312 BOOLEAN Locked
= FALSE
;
2315 /* Freeing NULL pointer is a legal operation */
2316 if (!Ptr
) return TRUE
;
2318 /* Get pointer to the heap and force flags */
2319 Heap
= (PHEAP
)HeapPtr
;
2320 Flags
|= Heap
->ForceFlags
;
2322 /* Call special heap */
2323 if (RtlpHeapIsSpecial(Flags
))
2324 return RtlDebugFreeHeap(Heap
, Flags
, Ptr
);
2326 /* Lock if necessary */
2327 if (!(Flags
& HEAP_NO_SERIALIZE
))
2329 RtlEnterHeapLock(Heap
->LockVariable
);
2333 /* Get pointer to the heap entry */
2334 HeapEntry
= (PHEAP_ENTRY
)Ptr
- 1;
2336 /* Check this entry, fail if it's invalid */
2337 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
) ||
2338 (((ULONG_PTR
)Ptr
& 0x7) != 0) ||
2339 (HeapEntry
->SegmentOffset
>= HEAP_SEGMENTS
))
2341 /* This is an invalid block */
2342 DPRINT1("HEAP: Trying to free an invalid address %p!\n", Ptr
);
2343 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
2345 /* Release the heap lock */
2346 if (Locked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2350 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2352 /* Big allocation */
2353 VirtualEntry
= CONTAINING_RECORD(HeapEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
2355 /* Remove it from the list */
2356 RemoveEntryList(&VirtualEntry
->Entry
);
2361 Status
= ZwFreeVirtualMemory(NtCurrentProcess(),
2362 (PVOID
*)&VirtualEntry
,
2366 if (!NT_SUCCESS(Status
))
2368 DPRINT1("HEAP: Failed releasing memory with Status 0x%08X. Heap %p, ptr %p, base address %p\n",
2369 Status
, Heap
, Ptr
, VirtualEntry
);
2370 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(Status
);
2375 /* Normal allocation */
2376 BlockSize
= HeapEntry
->Size
;
2380 /* Coalesce in kernel mode, and in usermode if it's not disabled */
2381 if (RtlpGetMode() == KernelMode
||
2382 (RtlpGetMode() == UserMode
&& !(Heap
->Flags
& HEAP_DISABLE_COALESCE_ON_FREE
)))
2384 HeapEntry
= (PHEAP_ENTRY
)RtlpCoalesceFreeBlocks(Heap
,
2385 (PHEAP_FREE_ENTRY
)HeapEntry
,
2390 /* If there is no need to decommit the block - put it into a free list */
2391 if (BlockSize
< Heap
->DeCommitFreeBlockThreshold
||
2392 (Heap
->TotalFreeSize
+ BlockSize
< Heap
->DeCommitTotalFreeThreshold
))
2394 /* Check if it needs to go to a 0 list */
2395 if (BlockSize
> HEAP_MAX_BLOCK_SIZE
)
2397 /* General-purpose 0 list */
2398 RtlpInsertFreeBlock(Heap
, (PHEAP_FREE_ENTRY
)HeapEntry
, BlockSize
);
2402 /* Usual free list */
2403 RtlpInsertFreeBlockHelper(Heap
, (PHEAP_FREE_ENTRY
)HeapEntry
, BlockSize
, FALSE
);
2405 /* Assert sizes are consistent */
2406 if (!(HeapEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
2408 ASSERT((HeapEntry
+ BlockSize
)->PreviousSize
== BlockSize
);
2411 /* Increase the free size */
2412 Heap
->TotalFreeSize
+= BlockSize
;
2416 if (RtlpGetMode() == UserMode
&&
2425 /* Decommit this block */
2426 RtlpDeCommitFreeBlock(Heap
, (PHEAP_FREE_ENTRY
)HeapEntry
, BlockSize
);
2430 /* Release the heap lock */
2431 if (Locked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2437 RtlpGrowBlockInPlace (IN PHEAP Heap
,
2439 IN PHEAP_ENTRY InUseEntry
,
2443 UCHAR EntryFlags
, RememberFlags
;
2444 PHEAP_FREE_ENTRY FreeEntry
, UnusedEntry
, FollowingEntry
;
2445 SIZE_T FreeSize
, PrevSize
, TailPart
, AddedSize
= 0;
2446 PHEAP_ENTRY_EXTRA OldExtra
, NewExtra
;
2448 /* We can't grow beyond specified threshold */
2449 if (Index
> Heap
->VirtualMemoryThreshold
)
2452 /* Get entry flags */
2453 EntryFlags
= InUseEntry
->Flags
;
2455 /* Get the next free entry */
2456 FreeEntry
= (PHEAP_FREE_ENTRY
)(InUseEntry
+ InUseEntry
->Size
);
2458 if (EntryFlags
& HEAP_ENTRY_LAST_ENTRY
)
2460 /* There is no next block, just uncommitted space. Calculate how much is needed */
2461 FreeSize
= (Index
- InUseEntry
->Size
) << HEAP_ENTRY_SHIFT
;
2462 FreeSize
= ROUND_UP(FreeSize
, PAGE_SIZE
);
2464 /* Find and commit those pages */
2465 FreeEntry
= RtlpFindAndCommitPages(Heap
,
2466 Heap
->Segments
[InUseEntry
->SegmentOffset
],
2470 /* Fail if it failed... */
2471 if (!FreeEntry
) return FALSE
;
2473 /* It was successful, perform coalescing */
2474 FreeSize
= FreeSize
>> HEAP_ENTRY_SHIFT
;
2475 FreeEntry
= RtlpCoalesceFreeBlocks(Heap
, FreeEntry
, &FreeSize
, FALSE
);
2477 /* Check if it's enough */
2478 if (FreeSize
+ InUseEntry
->Size
< Index
)
2480 /* Still not enough */
2481 RtlpInsertFreeBlock(Heap
, FreeEntry
, FreeSize
);
2482 Heap
->TotalFreeSize
+= FreeSize
;
2486 /* Remember flags of this free entry */
2487 RememberFlags
= FreeEntry
->Flags
;
2490 FreeSize
+= InUseEntry
->Size
;
2494 /* The next block indeed exists. Check if it's free or in use */
2495 if (FreeEntry
->Flags
& HEAP_ENTRY_BUSY
) return FALSE
;
2497 /* Next entry is free, check if it can fit the block we need */
2498 FreeSize
= InUseEntry
->Size
+ FreeEntry
->Size
;
2499 if (FreeSize
< Index
) return FALSE
;
2501 /* Remember flags of this free entry */
2502 RememberFlags
= FreeEntry
->Flags
;
2504 /* Remove this block from the free list */
2505 RtlpRemoveFreeBlock(Heap
, FreeEntry
, FALSE
, FALSE
);
2506 Heap
->TotalFreeSize
-= FreeEntry
->Size
;
2509 PrevSize
= (InUseEntry
->Size
<< HEAP_ENTRY_SHIFT
) - InUseEntry
->UnusedBytes
;
2512 /* Don't produce too small blocks */
2519 /* Process extra stuff */
2520 if (RememberFlags
& HEAP_ENTRY_EXTRA_PRESENT
)
2522 /* Calculate pointers */
2523 OldExtra
= (PHEAP_ENTRY_EXTRA
)(InUseEntry
+ InUseEntry
->Size
- 1);
2524 NewExtra
= (PHEAP_ENTRY_EXTRA
)(InUseEntry
+ Index
- 1);
2527 *NewExtra
= *OldExtra
;
2533 InUseEntry
->Size
= Index
;
2534 InUseEntry
->UnusedBytes
= ((Index
<< HEAP_ENTRY_SHIFT
) - Size
);
2536 /* Check if there is a free space remaining after merging those blocks */
2539 /* Update flags and sizes */
2540 InUseEntry
->Flags
|= RememberFlags
& HEAP_ENTRY_LAST_ENTRY
;
2542 /* Either update previous size of the next entry or mark it as a last
2543 entry in the segment*/
2544 if (RememberFlags
& HEAP_ENTRY_LAST_ENTRY
)
2545 Heap
->Segments
[InUseEntry
->SegmentOffset
]->LastEntryInSegment
= InUseEntry
;
2547 (InUseEntry
+ InUseEntry
->Size
)->PreviousSize
= InUseEntry
->Size
;
2551 /* Complex case, we need to split the block to give unused free space
2553 UnusedEntry
= (PHEAP_FREE_ENTRY
)(InUseEntry
+ Index
);
2554 UnusedEntry
->PreviousSize
= Index
;
2555 UnusedEntry
->SegmentOffset
= InUseEntry
->SegmentOffset
;
2557 /* Update the following block or set the last entry in the segment */
2558 if (RememberFlags
& HEAP_ENTRY_LAST_ENTRY
)
2560 /* Set last entry and set flags and size */
2561 Heap
->Segments
[InUseEntry
->SegmentOffset
]->LastEntryInSegment
= InUseEntry
;
2562 UnusedEntry
->Flags
= RememberFlags
;
2563 UnusedEntry
->Size
= FreeSize
;
2565 /* Insert it to the heap and update total size */
2566 RtlpInsertFreeBlockHelper(Heap
, UnusedEntry
, FreeSize
, FALSE
);
2567 Heap
->TotalFreeSize
+= FreeSize
;
2571 /* There is a block after this one */
2572 FollowingEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)UnusedEntry
+ FreeSize
);
2574 if (FollowingEntry
->Flags
& HEAP_ENTRY_BUSY
)
2576 /* Update flags and set size of the unused space entry */
2577 UnusedEntry
->Flags
= RememberFlags
& (~HEAP_ENTRY_LAST_ENTRY
);
2578 UnusedEntry
->Size
= FreeSize
;
2580 /* Update previous size of the following entry */
2581 FollowingEntry
->PreviousSize
= FreeSize
;
2583 /* Insert it to the heap and update total free size */
2584 RtlpInsertFreeBlockHelper(Heap
, UnusedEntry
, FreeSize
, FALSE
);
2585 Heap
->TotalFreeSize
+= FreeSize
;
2589 /* That following entry is also free, what a fortune! */
2590 RememberFlags
= FollowingEntry
->Flags
;
2593 RtlpRemoveFreeBlock(Heap
, FollowingEntry
, FALSE
, FALSE
);
2594 Heap
->TotalFreeSize
-= FollowingEntry
->Size
;
2596 /* And make up a new combined block */
2597 FreeSize
+= FollowingEntry
->Size
;
2598 UnusedEntry
->Flags
= RememberFlags
;
2600 /* Check where to put it */
2601 if (FreeSize
<= HEAP_MAX_BLOCK_SIZE
)
2603 /* Fine for a dedicated list */
2604 UnusedEntry
->Size
= FreeSize
;
2606 if (RememberFlags
& HEAP_ENTRY_LAST_ENTRY
)
2607 Heap
->Segments
[UnusedEntry
->SegmentOffset
]->LastEntryInSegment
= (PHEAP_ENTRY
)UnusedEntry
;
2609 ((PHEAP_ENTRY
)UnusedEntry
+ FreeSize
)->PreviousSize
= FreeSize
;
2611 /* Insert it back and update total size */
2612 RtlpInsertFreeBlockHelper(Heap
, UnusedEntry
, FreeSize
, FALSE
);
2613 Heap
->TotalFreeSize
+= FreeSize
;
2617 /* The block is very large, leave all the hassle to the insertion routine */
2618 RtlpInsertFreeBlock(Heap
, UnusedEntry
, FreeSize
);
2624 /* Copy user settable flags */
2625 InUseEntry
->Flags
&= ~HEAP_ENTRY_SETTABLE_FLAGS
;
2626 InUseEntry
->Flags
|= ((Flags
& HEAP_SETTABLE_USER_FLAGS
) >> 4);
2628 /* Properly "zero out" (and fill!) the space */
2629 if (Flags
& HEAP_ZERO_MEMORY
)
2631 RtlZeroMemory((PCHAR
)(InUseEntry
+ 1) + PrevSize
, Size
- PrevSize
);
2633 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
2635 /* Calculate tail part which we need to fill */
2636 TailPart
= PrevSize
& (sizeof(ULONG
) - 1);
2638 /* "Invert" it as usual */
2639 if (TailPart
) TailPart
= 4 - TailPart
;
2641 if (Size
> (PrevSize
+ TailPart
))
2642 AddedSize
= (Size
- (PrevSize
+ TailPart
)) & ~(sizeof(ULONG
) - 1);
2646 RtlFillMemoryUlong((PCHAR
)(InUseEntry
+ 1) + PrevSize
+ TailPart
,
2648 ARENA_INUSE_FILLER
);
2652 /* Fill the new tail */
2653 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
2655 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
,
2660 /* Return success */
2664 PHEAP_ENTRY_EXTRA NTAPI
2665 RtlpGetExtraStuffPointer(PHEAP_ENTRY HeapEntry
)
2667 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry
;
2669 /* Check if it's a big block */
2670 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2672 VirtualEntry
= CONTAINING_RECORD(HeapEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
2674 /* Return a pointer to the extra stuff*/
2675 return &VirtualEntry
->ExtraStuff
;
2679 /* This is a usual entry, which means extra stuff follows this block */
2680 return (PHEAP_ENTRY_EXTRA
)(HeapEntry
+ HeapEntry
->Size
- 1);
2685 /***********************************************************************
2688 * Heap [in] Handle of heap block
2689 * Flags [in] Heap reallocation flags
2690 * Ptr, [in] Address of memory to reallocate
2691 * Size [in] Number of bytes to reallocate
2694 * Pointer to reallocated memory block
2696 * 0x7d030f60--invalid flags in RtlHeapAllocate
2700 RtlReAllocateHeap(HANDLE HeapPtr
,
2705 PHEAP Heap
= (PHEAP
)HeapPtr
;
2706 PHEAP_ENTRY InUseEntry
, NewInUseEntry
;
2707 PHEAP_ENTRY_EXTRA OldExtra
, NewExtra
;
2708 SIZE_T AllocationSize
, FreeSize
, DecommitSize
;
2709 BOOLEAN HeapLocked
= FALSE
;
2710 PVOID NewBaseAddress
;
2711 PHEAP_FREE_ENTRY SplitBlock
, SplitBlock2
;
2712 SIZE_T OldSize
, Index
, OldIndex
;
2716 SIZE_T RemainderBytes
, ExtraSize
;
2717 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualAllocBlock
;
2718 EXCEPTION_RECORD ExceptionRecord
;
2720 /* Return success in case of a null pointer */
2723 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_SUCCESS
);
2727 /* Force heap flags */
2728 Flags
|= Heap
->ForceFlags
;
2730 /* Call special heap */
2731 if (RtlpHeapIsSpecial(Flags
))
2732 return RtlDebugReAllocateHeap(Heap
, Flags
, Ptr
, Size
);
2734 /* Make sure size is valid */
2735 if (Size
>= 0x80000000)
2737 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_NO_MEMORY
);
2741 /* Calculate allocation size and index */
2743 AllocationSize
= Size
;
2746 AllocationSize
= (AllocationSize
+ Heap
->AlignRound
) & Heap
->AlignMask
;
2748 /* Add up extra stuff, if it is present anywhere */
2749 if (((((PHEAP_ENTRY
)Ptr
)-1)->Flags
& HEAP_ENTRY_EXTRA_PRESENT
) ||
2750 (Flags
& HEAP_EXTRA_FLAGS_MASK
) ||
2751 Heap
->PseudoTagEntries
)
2753 AllocationSize
+= sizeof(HEAP_ENTRY_EXTRA
);
2756 /* Acquire the lock if necessary */
2757 if (!(Flags
& HEAP_NO_SERIALIZE
))
2759 RtlEnterHeapLock(Heap
->LockVariable
);
2761 Flags
^= HEAP_NO_SERIALIZE
;
2764 /* Get the pointer to the in-use entry */
2765 InUseEntry
= (PHEAP_ENTRY
)Ptr
- 1;
2767 /* If that entry is not really in-use, we have a problem */
2768 if (!(InUseEntry
->Flags
& HEAP_ENTRY_BUSY
))
2770 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
2772 /* Release the lock and return */
2774 RtlLeaveHeapLock(Heap
->LockVariable
);
2778 if (InUseEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2780 /* This is a virtually allocated block. Get its size */
2781 OldSize
= RtlpGetSizeOfBigBlock(InUseEntry
);
2783 /* Convert it to an index */
2784 OldIndex
= (OldSize
+ InUseEntry
->Size
) >> HEAP_ENTRY_SHIFT
;
2786 /* Calculate new allocation size and round it to the page size */
2787 AllocationSize
+= FIELD_OFFSET(HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
2788 AllocationSize
= ROUND_UP(AllocationSize
, PAGE_SIZE
);
2793 OldIndex
= InUseEntry
->Size
;
2795 OldSize
= (OldIndex
<< HEAP_ENTRY_SHIFT
) - InUseEntry
->UnusedBytes
;
2798 /* Calculate new index */
2799 Index
= AllocationSize
>> HEAP_ENTRY_SHIFT
;
2801 /* Check for 4 different scenarios (old size, new size, old index, new index) */
2802 if (Index
<= OldIndex
)
2804 /* Difference must be greater than 1, adjust if it's not so */
2805 if (Index
+ 1 == OldIndex
)
2808 AllocationSize
+= sizeof(HEAP_ENTRY
);
2811 /* Calculate new size */
2812 if (InUseEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2814 /* Simple in case of a virtual alloc - just an unused size */
2815 InUseEntry
->Size
= AllocationSize
- Size
;
2817 else if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
2819 /* There is extra stuff, take it into account */
2820 OldExtra
= (PHEAP_ENTRY_EXTRA
)(InUseEntry
+ InUseEntry
->Size
- 1);
2821 NewExtra
= (PHEAP_ENTRY_EXTRA
)(InUseEntry
+ Index
- 1);
2822 *NewExtra
= *OldExtra
;
2824 // FIXME Tagging, TagIndex
2826 /* Update unused bytes count */
2827 InUseEntry
->UnusedBytes
= AllocationSize
- Size
;
2831 // FIXME Tagging, SmallTagIndex
2832 InUseEntry
->UnusedBytes
= AllocationSize
- Size
;
2835 /* If new size is bigger than the old size */
2838 /* Zero out that additional space if required */
2839 if (Flags
& HEAP_ZERO_MEMORY
)
2841 RtlZeroMemory((PCHAR
)Ptr
+ OldSize
, Size
- OldSize
);
2843 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
2845 /* Fill it on free if required */
2846 RemainderBytes
= OldSize
& (sizeof(ULONG
) - 1);
2849 RemainderBytes
= 4 - RemainderBytes
;
2851 if (Size
> (OldSize
+ RemainderBytes
))
2853 /* Calculate actual amount of extra bytes to fill */
2854 ExtraSize
= (Size
- (OldSize
+ RemainderBytes
)) & ~(sizeof(ULONG
) - 1);
2856 /* Fill them if there are any */
2859 RtlFillMemoryUlong((PCHAR
)(InUseEntry
+ 1) + OldSize
+ RemainderBytes
,
2861 ARENA_INUSE_FILLER
);
2867 /* Fill tail of the heap entry if required */
2868 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
2870 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
,
2875 /* Check if the difference is significant or not */
2876 if (Index
!= OldIndex
)
2879 FreeFlags
= InUseEntry
->Flags
& ~HEAP_ENTRY_BUSY
;
2881 if (FreeFlags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2883 /* This is a virtual block allocation */
2884 VirtualAllocBlock
= CONTAINING_RECORD(InUseEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
2888 DecommitBase
= (PCHAR
)VirtualAllocBlock
+ AllocationSize
;
2889 DecommitSize
= (OldIndex
<< HEAP_ENTRY_SHIFT
) - AllocationSize
;
2891 /* Release the memory */
2892 Status
= ZwFreeVirtualMemory(NtCurrentProcess(),
2893 (PVOID
*)&DecommitBase
,
2897 if (!NT_SUCCESS(Status
))
2899 DPRINT1("HEAP: Unable to release memory (pointer %p, size 0x%x), Status %08x\n", DecommitBase
, DecommitSize
, Status
);
2903 /* Otherwise reduce the commit size */
2904 VirtualAllocBlock
->CommitSize
-= DecommitSize
;
2909 /* Reduce size of the block and possibly split it */
2910 SplitBlock
= (PHEAP_FREE_ENTRY
)(InUseEntry
+ Index
);
2912 /* Initialize this entry */
2913 SplitBlock
->Flags
= FreeFlags
;
2914 SplitBlock
->PreviousSize
= Index
;
2915 SplitBlock
->SegmentOffset
= InUseEntry
->SegmentOffset
;
2917 /* Remember free size */
2918 FreeSize
= InUseEntry
->Size
- Index
;
2921 InUseEntry
->Size
= Index
;
2922 InUseEntry
->Flags
&= ~HEAP_ENTRY_LAST_ENTRY
;
2924 /* Is that the last entry */
2925 if (FreeFlags
& HEAP_ENTRY_LAST_ENTRY
)
2927 /* Update segment's last entry */
2928 Heap
->Segments
[SplitBlock
->SegmentOffset
]->LastEntryInSegment
= (PHEAP_ENTRY
)SplitBlock
;
2930 /* Set its size and insert it to the list */
2931 SplitBlock
->Size
= (USHORT
)FreeSize
;
2932 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
2934 /* Update total free size */
2935 Heap
->TotalFreeSize
+= FreeSize
;
2939 /* Get the block after that one */
2940 SplitBlock2
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
);
2942 if (SplitBlock2
->Flags
& HEAP_ENTRY_BUSY
)
2944 /* It's in use, add it here*/
2945 SplitBlock
->Size
= (USHORT
)FreeSize
;
2947 /* Update previous size of the next entry */
2948 ((PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
))->PreviousSize
= (USHORT
)FreeSize
;
2950 /* Insert it to the list */
2951 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
2953 /* Update total size */
2954 Heap
->TotalFreeSize
+= FreeSize
;
2958 /* Next entry is free, so merge with it */
2959 SplitBlock
->Flags
= SplitBlock2
->Flags
;
2961 /* Remove it, update total size */
2962 RtlpRemoveFreeBlock(Heap
, SplitBlock2
, FALSE
, FALSE
);
2963 Heap
->TotalFreeSize
-= SplitBlock2
->Size
;
2965 /* Calculate total free size */
2966 FreeSize
+= SplitBlock2
->Size
;
2968 if (FreeSize
<= HEAP_MAX_BLOCK_SIZE
)
2970 SplitBlock
->Size
= FreeSize
;
2972 if (!(SplitBlock
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
2974 /* Update previous size of the next entry */
2975 ((PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
))->PreviousSize
= FreeSize
;
2979 Heap
->Segments
[SplitBlock
->SegmentOffset
]->LastEntryInSegment
= (PHEAP_ENTRY
)SplitBlock
;
2982 /* Insert the new one back and update total size */
2983 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
2984 Heap
->TotalFreeSize
+= FreeSize
;
2989 RtlpInsertFreeBlock(Heap
, SplitBlock
, FreeSize
);
2998 /* We're growing the block */
2999 if ((InUseEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
) ||
3000 !RtlpGrowBlockInPlace(Heap
, Flags
, InUseEntry
, Size
, Index
))
3002 /* Growing in place failed, so growing out of place */
3003 if (Flags
& HEAP_REALLOC_IN_PLACE_ONLY
)
3005 DPRINT1("Realloc in place failed, but it was the only option\n");
3010 /* Clear tag bits */
3011 Flags
&= ~HEAP_TAG_MASK
;
3013 /* Process extra stuff */
3014 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
3016 /* Preserve user settable flags */
3017 Flags
&= ~HEAP_SETTABLE_USER_FLAGS
;
3019 Flags
|= HEAP_SETTABLE_USER_VALUE
| ((InUseEntry
->Flags
& HEAP_ENTRY_SETTABLE_FLAGS
) << 4);
3021 /* Get pointer to the old extra data */
3022 OldExtra
= RtlpGetExtraStuffPointer(InUseEntry
);
3024 /* Save tag index if it was set */
3025 if (OldExtra
->TagIndex
&&
3026 !(OldExtra
->TagIndex
& HEAP_PSEUDO_TAG_FLAG
))
3028 Flags
|= OldExtra
->TagIndex
<< HEAP_TAG_SHIFT
;
3031 else if (InUseEntry
->SmallTagIndex
)
3033 /* Take small tag index into account */
3034 Flags
|= InUseEntry
->SmallTagIndex
<< HEAP_TAG_SHIFT
;
3037 /* Allocate new block from the heap */
3038 NewBaseAddress
= RtlAllocateHeap(HeapPtr
,
3039 Flags
& ~HEAP_ZERO_MEMORY
,
3042 /* Proceed if it didn't fail */
3045 /* Get new entry pointer */
3046 NewInUseEntry
= (PHEAP_ENTRY
)NewBaseAddress
- 1;
3048 /* Process extra stuff if it exists */
3049 if (NewInUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
3051 NewExtra
= RtlpGetExtraStuffPointer(NewInUseEntry
);
3053 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
3055 OldExtra
= RtlpGetExtraStuffPointer(InUseEntry
);
3056 NewExtra
->Settable
= OldExtra
->Settable
;
3060 RtlZeroMemory(NewExtra
, sizeof(*NewExtra
));
3064 /* Copy actual user bits */
3066 RtlMoveMemory(NewBaseAddress
, Ptr
, Size
);
3068 RtlMoveMemory(NewBaseAddress
, Ptr
, OldSize
);
3070 /* Zero remaining part if required */
3071 if (Size
> OldSize
&&
3072 (Flags
& HEAP_ZERO_MEMORY
))
3074 RtlZeroMemory((PCHAR
)NewBaseAddress
+ OldSize
, Size
- OldSize
);
3077 /* Free the old block */
3078 RtlFreeHeap(HeapPtr
, Flags
, Ptr
);
3081 Ptr
= NewBaseAddress
;
3086 /* Did resizing fail? */
3087 if (!Ptr
&& (Flags
& HEAP_GENERATE_EXCEPTIONS
))
3089 /* Generate an exception if required */
3090 ExceptionRecord
.ExceptionCode
= STATUS_NO_MEMORY
;
3091 ExceptionRecord
.ExceptionRecord
= NULL
;
3092 ExceptionRecord
.NumberParameters
= 1;
3093 ExceptionRecord
.ExceptionFlags
= 0;
3094 ExceptionRecord
.ExceptionInformation
[0] = AllocationSize
;
3096 RtlRaiseException(&ExceptionRecord
);
3099 /* Release the heap lock if it was acquired */
3101 RtlLeaveHeapLock(Heap
->LockVariable
);
3107 /***********************************************************************
3113 RtlCompactHeap(HANDLE Heap
,
3121 /***********************************************************************
3123 * Attempts to acquire the critical section object for a specified heap.
3126 * Heap [in] Handle of heap to lock for exclusive access
3135 RtlLockHeap(IN HANDLE HeapPtr
)
3137 PHEAP Heap
= (PHEAP
)HeapPtr
;
3139 // FIXME Check for special heap
3141 /* Check if it's really a heap */
3142 if (Heap
->Signature
!= HEAP_SIGNATURE
) return FALSE
;
3144 /* Lock if it's lockable */
3145 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
3147 RtlEnterHeapLock(Heap
->LockVariable
);
3154 /***********************************************************************
3156 * Releases ownership of the critical section object.
3159 * Heap [in] Handle to the heap to unlock
3168 RtlUnlockHeap(HANDLE HeapPtr
)
3170 PHEAP Heap
= (PHEAP
)HeapPtr
;
3172 // FIXME Check for special heap
3174 /* Check if it's really a heap */
3175 if (Heap
->Signature
!= HEAP_SIGNATURE
) return FALSE
;
3177 /* Unlock if it's lockable */
3178 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
3180 RtlLeaveHeapLock(Heap
->LockVariable
);
3187 /***********************************************************************
3190 * Heap [in] Handle of heap
3191 * Flags [in] Heap size control flags
3192 * Ptr [in] Address of memory to return size for
3195 * Size in bytes of allocated memory
3196 * 0xffffffff: Failure
3207 PHEAP Heap
= (PHEAP
)HeapPtr
;
3208 PHEAP_ENTRY HeapEntry
;
3211 // FIXME This is a hack around missing SEH support!
3214 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_HANDLE
);
3219 Flags
|= Heap
->ForceFlags
;
3221 /* Call special heap */
3222 if (RtlpHeapIsSpecial(Flags
))
3223 return RtlDebugSizeHeap(Heap
, Flags
, Ptr
);
3225 /* Get the heap entry pointer */
3226 HeapEntry
= (PHEAP_ENTRY
)Ptr
- 1;
3228 /* Return -1 if that entry is free */
3229 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
))
3231 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
3235 /* Get size of this block depending if it's a usual or a big one */
3236 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
3238 EntrySize
= RtlpGetSizeOfBigBlock(HeapEntry
);
3243 EntrySize
= (HeapEntry
->Size
<< HEAP_ENTRY_SHIFT
) - HeapEntry
->UnusedBytes
;
3246 /* Return calculated size */
3251 RtlpCheckInUsePattern(PHEAP_ENTRY HeapEntry
)
3253 SIZE_T Size
, Result
;
3256 /* Calculate size */
3257 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
3258 Size
= RtlpGetSizeOfBigBlock(HeapEntry
);
3260 Size
= (HeapEntry
->Size
<< HEAP_ENTRY_SHIFT
) - HeapEntry
->UnusedBytes
;
3262 /* Calculate pointer to the tail part of the block */
3263 TailPart
= (PCHAR
)(HeapEntry
+ 1) + Size
;
3265 /* Compare tail pattern */
3266 Result
= RtlCompareMemory(TailPart
,
3270 if (Result
!= HEAP_ENTRY_SIZE
)
3272 DPRINT1("HEAP: Heap entry (size %x) %p tail is modified at %p\n", Size
, HeapEntry
, TailPart
+ Result
);
3281 RtlpValidateHeapHeaders(
3283 BOOLEAN Recalculate
)
3285 // We skip header validation for now
3290 RtlpValidateHeapEntry(
3292 PHEAP_ENTRY HeapEntry
)
3294 BOOLEAN BigAllocation
, EntryFound
= FALSE
;
3295 PHEAP_SEGMENT Segment
;
3296 ULONG SegmentOffset
;
3298 /* Perform various consistency checks of this entry */
3299 if (!HeapEntry
) goto invalid_entry
;
3300 if ((ULONG_PTR
)HeapEntry
& (HEAP_ENTRY_SIZE
- 1)) goto invalid_entry
;
3301 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
)) goto invalid_entry
;
3303 BigAllocation
= HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
;
3304 Segment
= Heap
->Segments
[HeapEntry
->SegmentOffset
];
3306 if (BigAllocation
&&
3307 (((ULONG_PTR
)HeapEntry
& (PAGE_SIZE
- 1)) != FIELD_OFFSET(HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
)))
3310 if (!BigAllocation
&& (HeapEntry
->SegmentOffset
>= HEAP_SEGMENTS
||
3312 HeapEntry
< Segment
->FirstEntry
||
3313 HeapEntry
>= Segment
->LastValidEntry
))
3316 if ((HeapEntry
->Flags
& HEAP_ENTRY_FILL_PATTERN
) &&
3317 !RtlpCheckInUsePattern(HeapEntry
))
3320 /* Checks are done, if this is a virtual entry, that's all */
3321 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
) return TRUE
;
3323 /* Go through segments and check if this entry fits into any of them */
3324 for (SegmentOffset
= 0; SegmentOffset
< HEAP_SEGMENTS
; SegmentOffset
++)
3326 Segment
= Heap
->Segments
[SegmentOffset
];
3327 if (!Segment
) continue;
3329 if ((HeapEntry
>= Segment
->FirstEntry
) &&
3330 (HeapEntry
< Segment
->LastValidEntry
))
3338 /* Return our result of finding entry in the segments */
3342 DPRINT1("HEAP: Invalid heap entry %p in heap %p\n", HeapEntry
, Heap
);
3347 RtlpValidateHeapSegment(
3349 PHEAP_SEGMENT Segment
,
3350 UCHAR SegmentOffset
,
3351 PULONG FreeEntriesCount
,
3352 PSIZE_T TotalFreeSize
,
3354 PSIZE_T PseudoTagEntries
)
3356 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
3357 PLIST_ENTRY UcrEntry
;
3358 SIZE_T ByteSize
, Size
, Result
;
3359 PHEAP_ENTRY CurrentEntry
;
3360 ULONG UnCommittedPages
;
3361 ULONG UnCommittedRanges
;
3364 UnCommittedPages
= 0;
3365 UnCommittedRanges
= 0;
3367 if (IsListEmpty(&Segment
->UCRSegmentList
))
3370 UcrDescriptor
= NULL
;
3374 UcrEntry
= Segment
->UCRSegmentList
.Flink
;
3375 UcrDescriptor
= CONTAINING_RECORD(UcrEntry
, HEAP_UCR_DESCRIPTOR
, SegmentEntry
);
3378 if (Segment
->BaseAddress
== Heap
)
3379 CurrentEntry
= &Heap
->Entry
;
3381 CurrentEntry
= &Segment
->Entry
;
3383 while (CurrentEntry
< Segment
->LastValidEntry
)
3385 if (UcrDescriptor
&&
3386 ((PVOID
)CurrentEntry
>= UcrDescriptor
->Address
))
3388 DPRINT1("HEAP: Entry %p is not inside uncommited range [%p .. %p)\n",
3389 CurrentEntry
, UcrDescriptor
->Address
,
3390 (PCHAR
)UcrDescriptor
->Address
+ UcrDescriptor
->Size
);
3397 while (CurrentEntry
< Segment
->LastValidEntry
)
3399 if (PreviousSize
!= CurrentEntry
->PreviousSize
)
3401 DPRINT1("HEAP: Entry %p has incorrect PreviousSize %x instead of %x\n",
3402 CurrentEntry
, CurrentEntry
->PreviousSize
, PreviousSize
);
3407 PreviousSize
= CurrentEntry
->Size
;
3408 Size
= CurrentEntry
->Size
<< HEAP_ENTRY_SHIFT
;
3410 if (CurrentEntry
->Flags
& HEAP_ENTRY_BUSY
)
3417 /* Check fill pattern */
3418 if (CurrentEntry
->Flags
& HEAP_ENTRY_FILL_PATTERN
)
3420 if (!RtlpCheckInUsePattern(CurrentEntry
))
3426 /* The entry is free, increase free entries count and total free size */
3427 *FreeEntriesCount
= *FreeEntriesCount
+ 1;
3428 *TotalFreeSize
+= CurrentEntry
->Size
;
3430 if ((Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
) &&
3431 (CurrentEntry
->Flags
& HEAP_ENTRY_FILL_PATTERN
))
3433 ByteSize
= Size
- sizeof(HEAP_FREE_ENTRY
);
3435 if ((CurrentEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
) &&
3436 (ByteSize
> sizeof(HEAP_FREE_ENTRY_EXTRA
)))
3438 ByteSize
-= sizeof(HEAP_FREE_ENTRY_EXTRA
);
3441 Result
= RtlCompareMemoryUlong((PCHAR
)((PHEAP_FREE_ENTRY
)CurrentEntry
+ 1),
3445 if (Result
!= ByteSize
)
3447 DPRINT1("HEAP: Free heap block %p modified at %p after it was freed\n",
3449 (PCHAR
)(CurrentEntry
+ 1) + Result
);
3456 if (CurrentEntry
->SegmentOffset
!= SegmentOffset
)
3458 DPRINT1("HEAP: Heap entry %p SegmentOffset is incorrect %x (should be %x)\n", CurrentEntry
, SegmentOffset
, CurrentEntry
->SegmentOffset
);
3462 /* Check if it's the last entry */
3463 if (CurrentEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
)
3465 CurrentEntry
= (PHEAP_ENTRY
)((PCHAR
)CurrentEntry
+ Size
);
3469 /* Check if it's not really the last one */
3470 if (CurrentEntry
!= Segment
->LastValidEntry
)
3472 DPRINT1("HEAP: Heap entry %p is not last block in segment (%x)\n", CurrentEntry
, Segment
->LastValidEntry
);
3476 else if (CurrentEntry
!= UcrDescriptor
->Address
)
3478 DPRINT1("HEAP: Heap entry %p does not match next uncommitted address (%p)\n",
3479 CurrentEntry
, UcrDescriptor
->Address
);
3485 UnCommittedPages
+= (UcrDescriptor
->Size
/ PAGE_SIZE
);
3486 UnCommittedRanges
++;
3488 CurrentEntry
= (PHEAP_ENTRY
)((PCHAR
)UcrDescriptor
->Address
+ UcrDescriptor
->Size
);
3490 /* Go to the next UCR descriptor */
3491 UcrEntry
= UcrEntry
->Flink
;
3492 if (UcrEntry
== &Segment
->UCRSegmentList
)
3495 UcrDescriptor
= NULL
;
3499 UcrDescriptor
= CONTAINING_RECORD(UcrEntry
, HEAP_UCR_DESCRIPTOR
, SegmentEntry
);
3506 /* Advance to the next entry */
3507 CurrentEntry
= (PHEAP_ENTRY
)((PCHAR
)CurrentEntry
+ Size
);
3511 /* Check total numbers of UCP and UCR */
3512 if (Segment
->NumberOfUnCommittedPages
!= UnCommittedPages
)
3514 DPRINT1("HEAP: Segment %p NumberOfUnCommittedPages is invalid (%x != %x)\n",
3515 Segment
, Segment
->NumberOfUnCommittedPages
, UnCommittedPages
);
3520 if (Segment
->NumberOfUnCommittedRanges
!= UnCommittedRanges
)
3522 DPRINT1("HEAP: Segment %p NumberOfUnCommittedRanges is invalid (%x != %x)\n",
3523 Segment
, Segment
->NumberOfUnCommittedRanges
, UnCommittedRanges
);
3532 RtlpValidateHeap(PHEAP Heap
,
3533 BOOLEAN ForceValidation
)
3535 PHEAP_SEGMENT Segment
;
3537 UCHAR SegmentOffset
;
3538 SIZE_T Size
, TotalFreeSize
;
3540 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualAllocBlock
;
3541 PLIST_ENTRY ListHead
, NextEntry
;
3542 PHEAP_FREE_ENTRY FreeEntry
;
3543 ULONG FreeBlocksCount
, FreeListEntriesCount
;
3546 if (!RtlpValidateHeapHeaders(Heap
, FALSE
))
3549 /* Skip validation if it's not needed */
3550 if (!ForceValidation
&& !(Heap
->Flags
& HEAP_VALIDATE_ALL_ENABLED
))
3553 /* Check free lists bitmaps */
3554 FreeListEntriesCount
= 0;
3555 ListHead
= &Heap
->FreeLists
[0];
3557 for (Size
= 0; Size
< HEAP_FREELISTS
; Size
++)
3561 /* This is a dedicated list. Check if it's empty */
3562 EmptyList
= IsListEmpty(ListHead
);
3564 if (Heap
->u
.FreeListsInUseBytes
[Size
>> 3] & (1 << (Size
& 7)))
3568 DPRINT1("HEAP: Empty %x-free list marked as non-empty\n", Size
);
3576 DPRINT1("HEAP: Non-empty %x-free list marked as empty\n", Size
);
3582 /* Now check this list entries */
3583 NextEntry
= ListHead
->Flink
;
3586 while (ListHead
!= NextEntry
)
3588 FreeEntry
= CONTAINING_RECORD(NextEntry
, HEAP_FREE_ENTRY
, FreeList
);
3589 NextEntry
= NextEntry
->Flink
;
3591 /* If there is an in-use entry in a free list - that's quite a big problem */
3592 if (FreeEntry
->Flags
& HEAP_ENTRY_BUSY
)
3594 DPRINT1("HEAP: %x-dedicated list free element %x is marked in-use\n", Size
, FreeEntry
);
3598 /* Check sizes according to that specific list's size */
3599 if ((Size
== 0) && (FreeEntry
->Size
< HEAP_FREELISTS
))
3601 DPRINT1("HEAP: Non dedicated list free element %x has size %x which would fit a dedicated list\n", FreeEntry
, FreeEntry
->Size
);
3604 else if (Size
&& (FreeEntry
->Size
!= Size
))
3606 DPRINT1("HEAP: %x-dedicated list free element %x has incorrect size %x\n", Size
, FreeEntry
, FreeEntry
->Size
);
3609 else if ((Size
== 0) && (FreeEntry
->Size
< PreviousSize
))
3611 DPRINT1("HEAP: Non dedicated list free element %x is not put in order\n", FreeEntry
);
3615 /* Remember previous size*/
3616 PreviousSize
= FreeEntry
->Size
;
3618 /* Add up to the total amount of free entries */
3619 FreeListEntriesCount
++;
3622 /* Go to the head of the next free list */
3626 /* Check big allocations */
3627 ListHead
= &Heap
->VirtualAllocdBlocks
;
3628 NextEntry
= ListHead
->Flink
;
3630 while (ListHead
!= NextEntry
)
3632 VirtualAllocBlock
= CONTAINING_RECORD(NextEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, Entry
);
3634 /* We can only check the fill pattern */
3635 if (VirtualAllocBlock
->BusyBlock
.Flags
& HEAP_ENTRY_FILL_PATTERN
)
3637 if (!RtlpCheckInUsePattern(&VirtualAllocBlock
->BusyBlock
))
3641 NextEntry
= NextEntry
->Flink
;
3644 /* Check all segments */
3645 FreeBlocksCount
= 0;
3648 for (SegmentOffset
= 0; SegmentOffset
< HEAP_SEGMENTS
; SegmentOffset
++)
3650 Segment
= Heap
->Segments
[SegmentOffset
];
3652 /* Go to the next one if there is no segment */
3653 if (!Segment
) continue;
3655 if (!RtlpValidateHeapSegment(Heap
,
3667 if (FreeListEntriesCount
!= FreeBlocksCount
)
3669 DPRINT1("HEAP: Free blocks count in arena (%d) does not match free blocks number in the free lists (%d)\n", FreeBlocksCount
, FreeListEntriesCount
);
3673 if (Heap
->TotalFreeSize
!= TotalFreeSize
)
3675 DPRINT1("HEAP: Total size of free blocks in arena (%d) does not equal to the one in heap header (%d)\n", TotalFreeSize
, Heap
->TotalFreeSize
);
3682 /***********************************************************************
3684 * Validates a specified heap.
3687 * Heap [in] Handle to the heap
3688 * Flags [in] Bit flags that control access during operation
3689 * Block [in] Optional pointer to memory block to validate
3700 BOOLEAN NTAPI
RtlValidateHeap(
3706 PHEAP Heap
= (PHEAP
)HeapPtr
;
3707 BOOLEAN HeapLocked
= FALSE
;
3710 /* Check for page heap */
3711 if (Heap
->ForceFlags
& HEAP_FLAG_PAGE_ALLOCS
)
3712 return RtlpDebugPageHeapValidate(HeapPtr
, Flags
, Block
);
3714 /* Check signature */
3715 if (Heap
->Signature
!= HEAP_SIGNATURE
)
3717 DPRINT1("HEAP: Signature %x is invalid for heap %p\n", Heap
->Signature
, Heap
);
3722 Flags
= Heap
->ForceFlags
;
3724 /* Acquire the lock if necessary */
3725 if (!(Flags
& HEAP_NO_SERIALIZE
))
3727 RtlEnterHeapLock(Heap
->LockVariable
);
3731 /* Either validate whole heap or just one entry */
3733 HeapValid
= RtlpValidateHeap(Heap
, TRUE
);
3735 HeapValid
= RtlpValidateHeapEntry(Heap
, (PHEAP_ENTRY
)Block
- 1);
3737 /* Unlock if it's lockable */
3740 RtlLeaveHeapLock(Heap
->LockVariable
);
3747 RtlInitializeHeapManager(VOID
)
3752 Peb
= RtlGetCurrentPeb();
3754 /* Initialize heap-related fields of PEB */
3755 Peb
->NumberOfHeaps
= 0;
3757 /* Initialize the process heaps list protecting lock */
3758 RtlInitializeHeapLock(&RtlpProcessHeapsListLock
);
3766 RtlEnumProcessHeaps(PHEAP_ENUMERATION_ROUTINE HeapEnumerationRoutine
,
3770 return STATUS_NOT_IMPLEMENTED
;
3778 RtlGetProcessHeaps(ULONG count
,
3790 RtlValidateProcessHeaps(VOID
)
3802 IN PVOID HeapHandle
,
3815 RtlSetUserValueHeap(IN PVOID HeapHandle
,
3817 IN PVOID BaseAddress
,
3820 PHEAP Heap
= (PHEAP
)HeapHandle
;
3821 PHEAP_ENTRY HeapEntry
;
3822 PHEAP_ENTRY_EXTRA Extra
;
3823 BOOLEAN HeapLocked
= FALSE
;
3826 Flags
|= Heap
->Flags
;
3828 /* Call special heap */
3829 if (RtlpHeapIsSpecial(Flags
))
3830 return RtlDebugSetUserValueHeap(Heap
, Flags
, BaseAddress
, UserValue
);
3832 /* Lock if it's lockable */
3833 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
3835 RtlEnterHeapLock(Heap
->LockVariable
);
3839 /* Get a pointer to the entry */
3840 HeapEntry
= (PHEAP_ENTRY
)BaseAddress
- 1;
3842 /* If it's a free entry - return error */
3843 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
))
3845 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
3847 /* Release the heap lock if it was acquired */
3849 RtlLeaveHeapLock(Heap
->LockVariable
);
3854 /* Check if this entry has an extra stuff associated with it */
3855 if (HeapEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
3857 /* Use extra to store the value */
3858 Extra
= RtlpGetExtraStuffPointer(HeapEntry
);
3859 Extra
->Settable
= (ULONG_PTR
)UserValue
;
3862 /* Release the heap lock if it was acquired */
3864 RtlLeaveHeapLock(Heap
->LockVariable
);
3874 RtlSetUserFlagsHeap(IN PVOID HeapHandle
,
3876 IN PVOID BaseAddress
,
3877 IN ULONG UserFlagsReset
,
3878 IN ULONG UserFlagsSet
)
3880 PHEAP Heap
= (PHEAP
)HeapHandle
;
3881 PHEAP_ENTRY HeapEntry
;
3882 BOOLEAN HeapLocked
= FALSE
;
3885 Flags
|= Heap
->Flags
;
3887 /* Call special heap */
3888 if (RtlpHeapIsSpecial(Flags
))
3889 return RtlDebugSetUserFlagsHeap(Heap
, Flags
, BaseAddress
, UserFlagsReset
, UserFlagsSet
);
3891 /* Lock if it's lockable */
3892 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
3894 RtlEnterHeapLock(Heap
->LockVariable
);
3898 /* Get a pointer to the entry */
3899 HeapEntry
= (PHEAP_ENTRY
)BaseAddress
- 1;
3901 /* If it's a free entry - return error */
3902 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
))
3904 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
3906 /* Release the heap lock if it was acquired */
3908 RtlLeaveHeapLock(Heap
->LockVariable
);
3913 /* Set / reset flags */
3914 HeapEntry
->Flags
&= ~(UserFlagsReset
>> 4);
3915 HeapEntry
->Flags
|= (UserFlagsSet
>> 4);
3917 /* Release the heap lock if it was acquired */
3919 RtlLeaveHeapLock(Heap
->LockVariable
);
3929 RtlGetUserInfoHeap(IN PVOID HeapHandle
,
3931 IN PVOID BaseAddress
,
3932 OUT PVOID
*UserValue
,
3933 OUT PULONG UserFlags
)
3935 PHEAP Heap
= (PHEAP
)HeapHandle
;
3936 PHEAP_ENTRY HeapEntry
;
3937 PHEAP_ENTRY_EXTRA Extra
;
3938 BOOLEAN HeapLocked
= FALSE
;
3941 Flags
|= Heap
->Flags
;
3943 /* Call special heap */
3944 if (RtlpHeapIsSpecial(Flags
))
3945 return RtlDebugGetUserInfoHeap(Heap
, Flags
, BaseAddress
, UserValue
, UserFlags
);
3947 /* Lock if it's lockable */
3948 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
3950 RtlEnterHeapLock(Heap
->LockVariable
);
3954 /* Get a pointer to the entry */
3955 HeapEntry
= (PHEAP_ENTRY
)BaseAddress
- 1;
3957 /* If it's a free entry - return error */
3958 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
))
3960 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
3962 /* Release the heap lock if it was acquired */
3964 RtlLeaveHeapLock(Heap
->LockVariable
);
3969 /* Check if this entry has an extra stuff associated with it */
3970 if (HeapEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
3972 /* Get pointer to extra data */
3973 Extra
= RtlpGetExtraStuffPointer(HeapEntry
);
3975 /* Pass user value */
3977 *UserValue
= (PVOID
)Extra
->Settable
;
3979 /* Decode and return user flags */
3981 *UserFlags
= (HeapEntry
->Flags
& HEAP_ENTRY_SETTABLE_FLAGS
) << 4;
3984 /* Release the heap lock if it was acquired */
3986 RtlLeaveHeapLock(Heap
->LockVariable
);
3996 RtlUsageHeap(IN HANDLE Heap
,
3998 OUT PRTL_HEAP_USAGE Usage
)
4002 return STATUS_NOT_IMPLEMENTED
;
4007 RtlQueryTagHeap(IN PVOID HeapHandle
,
4010 IN BOOLEAN ResetCounters
,
4011 OUT PRTL_HEAP_TAG_INFO HeapTagInfo
)
4020 RtlExtendHeap(IN HANDLE Heap
,
4032 RtlCreateTagHeap(IN HANDLE HeapHandle
,
4035 IN PWSTR TagSubName
)
4044 RtlWalkHeap(IN HANDLE HeapHandle
,
4048 return STATUS_NOT_IMPLEMENTED
;
4053 RtlProtectHeap(IN PVOID HeapHandle
,
4054 IN BOOLEAN ReadOnly
)
4062 RtlSetHeapInformation(IN HANDLE HeapHandle OPTIONAL
,
4063 IN HEAP_INFORMATION_CLASS HeapInformationClass
,
4064 IN PVOID HeapInformation
,
4065 IN SIZE_T HeapInformationLength
)
4067 /* Setting heap information is not really supported except for enabling LFH */
4068 if (HeapInformationClass
== 0) return STATUS_SUCCESS
;
4070 /* Check buffer length */
4071 if (HeapInformationLength
< sizeof(ULONG
))
4073 /* The provided buffer is too small */
4074 return STATUS_BUFFER_TOO_SMALL
;
4077 /* Check for a special magic value for enabling LFH */
4078 if (*(PULONG
)HeapInformation
== 2)
4080 DPRINT1("RtlSetHeapInformation() needs to enable LFH\n");
4081 return STATUS_SUCCESS
;
4084 return STATUS_UNSUCCESSFUL
;
4089 RtlQueryHeapInformation(HANDLE HeapHandle
,
4090 HEAP_INFORMATION_CLASS HeapInformationClass
,
4091 PVOID HeapInformation OPTIONAL
,
4092 SIZE_T HeapInformationLength OPTIONAL
,
4093 PSIZE_T ReturnLength OPTIONAL
)
4095 PHEAP Heap
= (PHEAP
)HeapHandle
;
4097 /* Only HeapCompatibilityInformation is supported */
4098 if (HeapInformationClass
!= HeapCompatibilityInformation
)
4099 return STATUS_UNSUCCESSFUL
;
4101 /* Set result length */
4102 if (ReturnLength
) *ReturnLength
= sizeof(ULONG
);
4104 /* Check buffer length */
4105 if (HeapInformationLength
< sizeof(ULONG
))
4107 /* It's too small, return needed length */
4108 return STATUS_BUFFER_TOO_SMALL
;
4111 /* Return front end heap type */
4112 *(PULONG
)HeapInformation
= Heap
->FrontEndHeapType
;
4114 return STATUS_SUCCESS
;
4119 RtlMultipleAllocateHeap(IN PVOID HeapHandle
,
4131 RtlMultipleFreeHeap(IN PVOID HeapHandle
,