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
;
345 /* Remove the free block and update the freelists bitmap */
346 if (RemoveEntryList(&FreeEntry
->FreeList
) &&
347 (Dedicated
|| (!Dedicated
&& FreeEntry
->Size
< HEAP_FREELISTS
)))
349 RtlpClearFreeListsBit(Heap
, FreeEntry
);
352 /* Fill with pattern if necessary */
354 (FreeEntry
->Flags
& HEAP_ENTRY_FILL_PATTERN
))
356 RealSize
= (FreeEntry
->Size
<< HEAP_ENTRY_SHIFT
) - sizeof(*FreeEntry
);
358 /* Deduct extra stuff from block's real size */
359 if (FreeEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
&&
360 RealSize
> sizeof(HEAP_FREE_ENTRY_EXTRA
))
362 RealSize
-= sizeof(HEAP_FREE_ENTRY_EXTRA
);
365 /* Check if the free filler is intact */
366 Result
= RtlCompareMemoryUlong((PCHAR
)(FreeEntry
+ 1),
370 if (Result
!= RealSize
)
372 DPRINT1("Free heap block %p modified at %p after it was freed\n",
374 (PCHAR
)(FreeEntry
+ 1) + Result
);
380 RtlpGetSizeOfBigBlock(PHEAP_ENTRY HeapEntry
)
382 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry
;
384 /* Get pointer to the containing record */
385 VirtualEntry
= CONTAINING_RECORD(HeapEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
387 /* Restore the real size */
388 return VirtualEntry
->CommitSize
- HeapEntry
->Size
;
391 PHEAP_UCR_DESCRIPTOR NTAPI
392 RtlpCreateUnCommittedRange(PHEAP_SEGMENT Segment
)
395 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
396 PHEAP_UCR_SEGMENT UcrSegment
;
397 PHEAP Heap
= Segment
->Heap
;
398 SIZE_T ReserveSize
= 16 * PAGE_SIZE
;
399 SIZE_T CommitSize
= 1 * PAGE_SIZE
;
402 DPRINT("RtlpCreateUnCommittedRange(%p)\n", Segment
);
404 /* Check if we have unused UCRs */
405 if (IsListEmpty(&Heap
->UCRList
))
407 /* Get a pointer to the first UCR segment */
408 UcrSegment
= CONTAINING_RECORD(Heap
->UCRSegments
.Flink
, HEAP_UCR_SEGMENT
, ListEntry
);
410 /* Check the list of UCR segments */
411 if (IsListEmpty(&Heap
->UCRSegments
) ||
412 UcrSegment
->ReservedSize
== UcrSegment
->CommittedSize
)
414 /* We need to create a new one. Reserve 16 pages for it */
416 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
417 (PVOID
*)&UcrSegment
,
423 if (!NT_SUCCESS(Status
)) return NULL
;
425 /* Commit one page */
426 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
427 (PVOID
*)&UcrSegment
,
433 if (!NT_SUCCESS(Status
))
435 /* Release reserved memory */
436 ZwFreeVirtualMemory(NtCurrentProcess(),
437 (PVOID
*)&UcrDescriptor
,
444 UcrSegment
->ReservedSize
= ReserveSize
;
445 UcrSegment
->CommittedSize
= CommitSize
;
447 /* Add it to the head of the list */
448 InsertHeadList(&Heap
->UCRSegments
, &UcrSegment
->ListEntry
);
450 /* Get a pointer to the first available UCR descriptor */
451 UcrDescriptor
= (PHEAP_UCR_DESCRIPTOR
)(UcrSegment
+ 1);
455 /* It's possible to use existing UCR segment. Commit one more page */
456 UcrDescriptor
= (PHEAP_UCR_DESCRIPTOR
)((PCHAR
)UcrSegment
+ UcrSegment
->CommittedSize
);
457 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
458 (PVOID
*)&UcrDescriptor
,
464 if (!NT_SUCCESS(Status
)) return NULL
;
467 UcrSegment
->CommittedSize
+= CommitSize
;
470 /* There is a whole bunch of new UCR descriptors. Put them into the unused list */
471 while ((PCHAR
)UcrDescriptor
< ((PCHAR
)UcrSegment
+ UcrSegment
->CommittedSize
))
473 InsertTailList(&Heap
->UCRList
, &UcrDescriptor
->ListEntry
);
478 /* There are unused UCRs, just get the first one */
479 Entry
= RemoveHeadList(&Heap
->UCRList
);
480 UcrDescriptor
= CONTAINING_RECORD(Entry
, HEAP_UCR_DESCRIPTOR
, ListEntry
);
481 return UcrDescriptor
;
485 RtlpDestroyUnCommittedRange(PHEAP_SEGMENT Segment
,
486 PHEAP_UCR_DESCRIPTOR UcrDescriptor
)
489 UcrDescriptor
->Address
= NULL
;
490 UcrDescriptor
->Size
= 0;
492 /* Put it into the heap's list of unused UCRs */
493 InsertHeadList(&Segment
->Heap
->UCRList
, &UcrDescriptor
->ListEntry
);
497 RtlpInsertUnCommittedPages(PHEAP_SEGMENT Segment
,
502 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
504 DPRINT("RtlpInsertUnCommittedPages(%p %p %x)\n", Segment
, Address
, Size
);
506 /* Go through the list of UCR descriptors, they are sorted from lowest address
508 Current
= Segment
->UCRSegmentList
.Flink
;
509 while(Current
!= &Segment
->UCRSegmentList
)
511 UcrDescriptor
= CONTAINING_RECORD(Current
, HEAP_UCR_DESCRIPTOR
, SegmentEntry
);
513 if ((ULONG_PTR
)UcrDescriptor
->Address
> Address
)
515 /* Check for a really lucky case */
516 if ((Address
+ Size
) == (ULONG_PTR
)UcrDescriptor
->Address
)
519 UcrDescriptor
->Address
= (PVOID
)Address
;
520 UcrDescriptor
->Size
+= Size
;
524 /* We found the block after which the new one should go */
527 else if (((ULONG_PTR
)UcrDescriptor
->Address
+ UcrDescriptor
->Size
) == Address
)
529 /* Modify this entry */
530 Address
= (ULONG_PTR
)UcrDescriptor
->Address
;
531 Size
+= UcrDescriptor
->Size
;
533 /* Advance to the next descriptor */
534 Current
= Current
->Flink
;
536 /* Remove the current descriptor from the list and destroy it */
537 RemoveEntryList(&UcrDescriptor
->SegmentEntry
);
538 RtlpDestroyUnCommittedRange(Segment
, UcrDescriptor
);
540 Segment
->NumberOfUnCommittedRanges
--;
544 /* Advance to the next descriptor */
545 Current
= Current
->Flink
;
549 /* Create a new UCR descriptor */
550 UcrDescriptor
= RtlpCreateUnCommittedRange(Segment
);
551 if (!UcrDescriptor
) return;
553 UcrDescriptor
->Address
= (PVOID
)Address
;
554 UcrDescriptor
->Size
= Size
;
556 /* "Current" is the descriptor after which our one should go */
557 InsertTailList(Current
, &UcrDescriptor
->SegmentEntry
);
559 DPRINT("Added segment UCR with base %p, size 0x%x\n", Address
, Size
);
561 /* Increase counters */
562 Segment
->NumberOfUnCommittedRanges
++;
565 PHEAP_FREE_ENTRY NTAPI
566 RtlpFindAndCommitPages(PHEAP Heap
,
567 PHEAP_SEGMENT Segment
,
569 PVOID AddressRequested
)
572 ULONG_PTR Address
= 0;
573 PHEAP_UCR_DESCRIPTOR UcrDescriptor
, PreviousUcr
= NULL
;
574 PHEAP_ENTRY FirstEntry
, LastEntry
, PreviousLastEntry
;
577 DPRINT("RtlpFindAndCommitPages(%p %p %x %p)\n", Heap
, Segment
, *Size
, Address
);
579 /* Go through UCRs in a segment */
580 Current
= Segment
->UCRSegmentList
.Flink
;
581 while(Current
!= &Segment
->UCRSegmentList
)
583 UcrDescriptor
= CONTAINING_RECORD(Current
, HEAP_UCR_DESCRIPTOR
, SegmentEntry
);
585 /* Check if we can use that one right away */
586 if (UcrDescriptor
->Size
>= *Size
&&
587 (UcrDescriptor
->Address
== AddressRequested
|| !AddressRequested
))
589 /* Get the address */
590 Address
= (ULONG_PTR
)UcrDescriptor
->Address
;
593 if (Heap
->CommitRoutine
)
595 Status
= Heap
->CommitRoutine(Heap
, (PVOID
*)&Address
, Size
);
599 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
607 DPRINT("Committed %d bytes at base %p, UCR size is %d\n", *Size
, Address
, UcrDescriptor
->Size
);
609 /* Fail in unsuccessful case */
610 if (!NT_SUCCESS(Status
))
612 DPRINT1("Committing page failed with status 0x%08X\n", Status
);
616 /* Update tracking numbers */
617 Segment
->NumberOfUnCommittedPages
-= *Size
/ PAGE_SIZE
;
619 /* Calculate first and last entries */
620 FirstEntry
= (PHEAP_ENTRY
)Address
;
622 if ((Segment
->LastEntryInSegment
->Flags
& HEAP_ENTRY_LAST_ENTRY
) &&
623 (ULONG_PTR
)(Segment
->LastEntryInSegment
+ Segment
->LastEntryInSegment
->Size
) == (ULONG_PTR
)UcrDescriptor
->Address
)
625 LastEntry
= Segment
->LastEntryInSegment
;
629 /* Go through the entries to find the last one */
632 LastEntry
= (PHEAP_ENTRY
)((ULONG_PTR
)PreviousUcr
->Address
+ PreviousUcr
->Size
);
634 LastEntry
= Segment
->FirstEntry
;
636 while (!(LastEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
638 PreviousLastEntry
= LastEntry
;
639 LastEntry
+= LastEntry
->Size
;
641 if ((ULONG_PTR
)LastEntry
>= (ULONG_PTR
)Segment
->LastValidEntry
||
642 LastEntry
->Size
== 0)
644 if (LastEntry
== (PHEAP_ENTRY
)Address
)
647 LastEntry
= PreviousLastEntry
;
651 DPRINT1("Last entry not found in a committed range near to %p\n", PreviousLastEntry
);
657 /* Unmark it as a last entry */
658 LastEntry
->Flags
&= ~HEAP_ENTRY_LAST_ENTRY
;
660 /* Update UCR descriptor */
661 UcrDescriptor
->Address
= (PVOID
)((ULONG_PTR
)UcrDescriptor
->Address
+ *Size
);
662 UcrDescriptor
->Size
-= *Size
;
664 DPRINT("Updating UcrDescriptor %p, new Address %p, size %d\n",
665 UcrDescriptor
, UcrDescriptor
->Address
, UcrDescriptor
->Size
);
667 /* Check if anything left in this UCR */
668 if (UcrDescriptor
->Size
== 0)
670 /* It's fully exhausted */
671 if (UcrDescriptor
->Address
== Segment
->LastValidEntry
)
673 FirstEntry
->Flags
= HEAP_ENTRY_LAST_ENTRY
;
674 Segment
->LastEntryInSegment
= FirstEntry
;
678 FirstEntry
->Flags
= 0;
679 Segment
->LastEntryInSegment
= Segment
->FirstEntry
;
682 /* This UCR needs to be removed because it became useless */
683 RemoveEntryList(&UcrDescriptor
->SegmentEntry
);
685 RtlpDestroyUnCommittedRange(Segment
, UcrDescriptor
);
686 Segment
->NumberOfUnCommittedRanges
--;
690 FirstEntry
->Flags
= HEAP_ENTRY_LAST_ENTRY
;
691 Segment
->LastEntryInSegment
= FirstEntry
;
694 /* Set various first entry fields*/
695 FirstEntry
->SegmentOffset
= LastEntry
->SegmentOffset
;
696 FirstEntry
->Size
= *Size
>> HEAP_ENTRY_SHIFT
;
697 FirstEntry
->PreviousSize
= LastEntry
->Size
;
699 /* Update previous size */
700 if (!(FirstEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
701 (FirstEntry
+ FirstEntry
->Size
)->PreviousSize
= FirstEntry
->Size
;
704 return (PHEAP_FREE_ENTRY
)FirstEntry
;
707 /* Advance to the next descriptor */
708 PreviousUcr
= UcrDescriptor
;
709 Current
= Current
->Flink
;
716 RtlpDeCommitFreeBlock(PHEAP Heap
,
717 PHEAP_FREE_ENTRY FreeEntry
,
720 PHEAP_SEGMENT Segment
;
721 PHEAP_ENTRY PrecedingInUseEntry
= NULL
, NextInUseEntry
= NULL
;
722 PHEAP_FREE_ENTRY NextFreeEntry
;
723 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
724 ULONG PrecedingSize
, NextSize
, DecommitSize
;
725 ULONG_PTR DecommitBase
;
728 DPRINT("Decommitting %p %p %x\n", Heap
, FreeEntry
, Size
);
730 /* We can't decommit if there is a commit routine! */
731 if (Heap
->CommitRoutine
)
733 /* Just add it back the usual way */
734 RtlpInsertFreeBlock(Heap
, FreeEntry
, Size
);
738 /* Get the segment */
739 Segment
= Heap
->Segments
[FreeEntry
->SegmentOffset
];
741 /* Get the preceding entry */
742 DecommitBase
= ROUND_UP(FreeEntry
, PAGE_SIZE
);
743 PrecedingSize
= (PHEAP_ENTRY
)DecommitBase
- (PHEAP_ENTRY
)FreeEntry
;
745 if (PrecedingSize
== 1)
747 /* Just 1 heap entry, increase the base/size */
748 DecommitBase
+= PAGE_SIZE
;
749 PrecedingSize
+= PAGE_SIZE
>> HEAP_ENTRY_SHIFT
;
751 else if (FreeEntry
->PreviousSize
&&
752 (DecommitBase
== (ULONG_PTR
)FreeEntry
))
754 PrecedingInUseEntry
= (PHEAP_ENTRY
)FreeEntry
- FreeEntry
->PreviousSize
;
757 /* Get the next entry */
758 NextFreeEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)FreeEntry
+ Size
);
759 DecommitSize
= ROUND_DOWN(NextFreeEntry
, PAGE_SIZE
);
760 NextSize
= (PHEAP_ENTRY
)NextFreeEntry
- (PHEAP_ENTRY
)DecommitSize
;
764 /* Just 1 heap entry, increase the size */
765 DecommitSize
-= PAGE_SIZE
;
766 NextSize
+= PAGE_SIZE
>> HEAP_ENTRY_SHIFT
;
768 else if (NextSize
== 0 &&
769 !(FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
771 NextInUseEntry
= (PHEAP_ENTRY
)NextFreeEntry
;
774 NextFreeEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)NextFreeEntry
- NextSize
);
776 /* Calculate real decommit size */
777 if (DecommitSize
> DecommitBase
)
779 DecommitSize
-= DecommitBase
;
783 /* Nothing to decommit */
784 RtlpInsertFreeBlock(Heap
, FreeEntry
, Size
);
788 /* A decommit is necessary. Create a UCR descriptor */
789 UcrDescriptor
= RtlpCreateUnCommittedRange(Segment
);
792 DPRINT1("HEAP: Failed to create UCR descriptor\n");
793 RtlpInsertFreeBlock(Heap
, FreeEntry
, PrecedingSize
);
797 /* Decommit the memory */
798 Status
= ZwFreeVirtualMemory(NtCurrentProcess(),
799 (PVOID
*)&DecommitBase
,
803 /* Delete that UCR. This is needed to assure there is an unused UCR entry in the list */
804 RtlpDestroyUnCommittedRange(Segment
, UcrDescriptor
);
806 if (!NT_SUCCESS(Status
))
808 RtlpInsertFreeBlock(Heap
, FreeEntry
, Size
);
812 /* Insert uncommitted pages */
813 RtlpInsertUnCommittedPages(Segment
, DecommitBase
, DecommitSize
);
814 Segment
->NumberOfUnCommittedPages
+= (DecommitSize
/ PAGE_SIZE
);
818 /* Adjust size of this free entry and insert it */
819 FreeEntry
->Flags
= HEAP_ENTRY_LAST_ENTRY
;
820 FreeEntry
->Size
= PrecedingSize
;
821 Heap
->TotalFreeSize
+= PrecedingSize
;
823 /* Set last entry in the segment to this entry */
824 Segment
->LastEntryInSegment
= (PHEAP_ENTRY
)FreeEntry
;
826 /* Insert it into the free list */
827 RtlpInsertFreeBlockHelper(Heap
, FreeEntry
, PrecedingSize
, FALSE
);
829 else if (PrecedingInUseEntry
)
831 /* Adjust preceding in use entry */
832 PrecedingInUseEntry
->Flags
|= HEAP_ENTRY_LAST_ENTRY
;
833 Segment
->LastEntryInSegment
= PrecedingInUseEntry
;
834 } else if ((ULONG_PTR
)Segment
->LastEntryInSegment
>= DecommitBase
&&
835 ((PCHAR
)Segment
->LastEntryInSegment
< ((PCHAR
)DecommitBase
+ DecommitSize
)))
837 /* Update this segment's last entry */
838 Segment
->LastEntryInSegment
= Segment
->FirstEntry
;
841 /* Now the next one */
844 /* Adjust size of this free entry and insert it */
845 NextFreeEntry
->Flags
= 0;
846 NextFreeEntry
->PreviousSize
= 0;
847 NextFreeEntry
->SegmentOffset
= Segment
->Entry
.SegmentOffset
;
848 NextFreeEntry
->Size
= NextSize
;
850 ((PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)NextFreeEntry
+ NextSize
))->PreviousSize
= NextSize
;
852 Heap
->TotalFreeSize
+= NextSize
;
853 RtlpInsertFreeBlockHelper(Heap
, NextFreeEntry
, NextSize
, FALSE
);
855 else if (NextInUseEntry
)
857 NextInUseEntry
->PreviousSize
= 0;
862 RtlpInitializeHeapSegment(PHEAP Heap
,
863 PHEAP_SEGMENT Segment
,
867 PVOID UncommittedBase
,
870 ULONG Pages
, CommitSize
;
871 PHEAP_ENTRY HeapEntry
;
872 USHORT PreviousSize
= 0, NewSize
;
875 Pages
= ((PCHAR
)LimitAddress
- (PCHAR
)BaseAddress
) / PAGE_SIZE
;
877 HeapEntry
= (PHEAP_ENTRY
)ROUND_UP(Segment
+ 1, HEAP_ENTRY_SIZE
);
879 DPRINT("RtlpInitializeHeapSegment(%p %p %x %x %p %p %p)\n", Heap
, Segment
, SegmentIndex
, Flags
, BaseAddress
, UncommittedBase
, LimitAddress
);
880 DPRINT("Pages %x, HeapEntry %p, sizeof(HEAP_SEGMENT) %x\n", Pages
, HeapEntry
, sizeof(HEAP_SEGMENT
));
882 /* Check if it's the first segment and remember its size */
883 if (Heap
== BaseAddress
)
884 PreviousSize
= Heap
->Entry
.Size
;
886 NewSize
= ((PCHAR
)HeapEntry
- (PCHAR
)Segment
) >> HEAP_ENTRY_SHIFT
;
888 if ((PVOID
)(HeapEntry
+ 1) >= UncommittedBase
)
890 /* Check if it goes beyond the limit */
891 if ((PVOID
)(HeapEntry
+ 1) >= LimitAddress
)
894 /* Need to commit memory */
895 CommitSize
= (PCHAR
)(HeapEntry
+ 1) - (PCHAR
)UncommittedBase
;
896 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
897 (PVOID
)&UncommittedBase
,
902 if (!NT_SUCCESS(Status
))
904 DPRINT1("Committing page failed with status 0x%08X\n", Status
);
908 DPRINT("Committed %d bytes at base %p\n", CommitSize
, UncommittedBase
);
910 /* Calcule the new uncommitted base */
911 UncommittedBase
= (PVOID
)((PCHAR
)UncommittedBase
+ CommitSize
);
914 /* Initialize the segment entry */
915 Segment
->Entry
.PreviousSize
= PreviousSize
;
916 Segment
->Entry
.Size
= NewSize
;
917 Segment
->Entry
.Flags
= HEAP_ENTRY_BUSY
;
918 Segment
->Entry
.SegmentOffset
= SegmentIndex
;
920 /* Initialize the segment itself */
921 Segment
->SegmentSignature
= HEAP_SEGMENT_SIGNATURE
;
922 Segment
->Heap
= Heap
;
923 Segment
->BaseAddress
= BaseAddress
;
924 Segment
->FirstEntry
= HeapEntry
;
925 Segment
->LastValidEntry
= (PHEAP_ENTRY
)((PCHAR
)BaseAddress
+ Pages
* PAGE_SIZE
);
926 Segment
->NumberOfPages
= Pages
;
927 Segment
->NumberOfUnCommittedPages
= ((PCHAR
)LimitAddress
- (PCHAR
)UncommittedBase
) / PAGE_SIZE
;
928 InitializeListHead(&Segment
->UCRSegmentList
);
930 /* Insert uncommitted pages into UCR (uncommitted ranges) list */
931 if (Segment
->NumberOfUnCommittedPages
)
933 RtlpInsertUnCommittedPages(Segment
, (ULONG_PTR
)UncommittedBase
, Segment
->NumberOfUnCommittedPages
* PAGE_SIZE
);
936 /* Set the segment index pointer */
937 Heap
->Segments
[SegmentIndex
] = Segment
;
939 /* Prepare a free heap entry */
940 HeapEntry
->Flags
= HEAP_ENTRY_LAST_ENTRY
;
941 HeapEntry
->PreviousSize
= Segment
->Entry
.Size
;
942 HeapEntry
->SegmentOffset
= SegmentIndex
;
944 /* Set last entry in segment */
945 Segment
->LastEntryInSegment
= HeapEntry
;
948 RtlpInsertFreeBlock(Heap
, (PHEAP_FREE_ENTRY
)HeapEntry
, (PHEAP_ENTRY
)UncommittedBase
- HeapEntry
);
954 RtlpDestroyHeapSegment(PHEAP_SEGMENT Segment
)
960 /* Make sure it's not user allocated */
961 if (Segment
->SegmentFlags
& HEAP_USER_ALLOCATED
) return;
963 BaseAddress
= Segment
->BaseAddress
;
964 DPRINT("Destroying segment %p, BA %p\n", Segment
, BaseAddress
);
966 /* Release virtual memory */
967 Status
= ZwFreeVirtualMemory(NtCurrentProcess(),
972 if (!NT_SUCCESS(Status
))
974 DPRINT1("HEAP: Failed to release segment's memory with status 0x%08X\n", Status
);
980 RtlpAddHeapToProcessList(PHEAP Heap
)
985 Peb
= RtlGetCurrentPeb();
987 /* Acquire the lock */
988 RtlEnterHeapLock(&RtlpProcessHeapsListLock
);
991 /* Check if max number of heaps reached */
992 if (Peb
->NumberOfHeaps
== Peb
->MaximumNumberOfHeaps
)
994 // TODO: Handle this case
998 /* Add the heap to the process heaps */
999 Peb
->ProcessHeaps
[Peb
->NumberOfHeaps
] = Heap
;
1000 Peb
->NumberOfHeaps
++;
1001 Heap
->ProcessHeapsListIndex
= Peb
->NumberOfHeaps
;
1002 // } _SEH2_FINALLY {
1004 /* Release the lock */
1005 RtlLeaveHeapLock(&RtlpProcessHeapsListLock
);
1010 /* Usermode only! */
1012 RtlpRemoveHeapFromProcessList(PHEAP Heap
)
1015 PHEAP
*Current
, *Next
;
1019 Peb
= RtlGetCurrentPeb();
1021 /* Acquire the lock */
1022 RtlEnterHeapLock(&RtlpProcessHeapsListLock
);
1024 /* Check if we don't need anything to do */
1025 if ((Heap
->ProcessHeapsListIndex
== 0) ||
1026 (Heap
->ProcessHeapsListIndex
> Peb
->NumberOfHeaps
) ||
1027 (Peb
->NumberOfHeaps
== 0))
1029 /* Release the lock */
1030 RtlLeaveHeapLock(&RtlpProcessHeapsListLock
);
1035 /* The process actually has more than one heap.
1036 Use classic, lernt from university times algorithm for removing an entry
1037 from a static array */
1039 Current
= (PHEAP
*)&Peb
->ProcessHeaps
[Heap
->ProcessHeapsListIndex
- 1];
1042 /* How many items we need to shift to the left */
1043 Count
= Peb
->NumberOfHeaps
- (Heap
->ProcessHeapsListIndex
- 1);
1045 /* Move them all in a loop */
1048 /* Copy it and advance next pointer */
1051 /* Update its index */
1052 (*Current
)->ProcessHeapsListIndex
-= 1;
1054 /* Advance pointers */
1059 /* Decrease total number of heaps */
1060 Peb
->NumberOfHeaps
--;
1062 /* Zero last unused item */
1063 Peb
->ProcessHeaps
[Peb
->NumberOfHeaps
] = NULL
;
1064 Heap
->ProcessHeapsListIndex
= 0;
1066 /* Release the lock */
1067 RtlLeaveHeapLock(&RtlpProcessHeapsListLock
);
1070 PHEAP_FREE_ENTRY NTAPI
1071 RtlpCoalesceHeap(PHEAP Heap
)
1077 PHEAP_FREE_ENTRY NTAPI
1078 RtlpCoalesceFreeBlocks (PHEAP Heap
,
1079 PHEAP_FREE_ENTRY FreeEntry
,
1083 PHEAP_FREE_ENTRY CurrentEntry
, NextEntry
;
1085 /* Get the previous entry */
1086 CurrentEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)FreeEntry
- FreeEntry
->PreviousSize
);
1089 if (CurrentEntry
!= FreeEntry
&&
1090 !(CurrentEntry
->Flags
& HEAP_ENTRY_BUSY
) &&
1091 (*FreeSize
+ CurrentEntry
->Size
) <= HEAP_MAX_BLOCK_SIZE
)
1093 ASSERT(FreeEntry
->PreviousSize
== CurrentEntry
->Size
);
1095 /* Remove it if asked for */
1098 RtlpRemoveFreeBlock(Heap
, FreeEntry
, FALSE
, FALSE
);
1099 Heap
->TotalFreeSize
-= FreeEntry
->Size
;
1101 /* Remove it only once! */
1105 /* Remove previous entry too */
1106 RtlpRemoveFreeBlock(Heap
, CurrentEntry
, FALSE
, FALSE
);
1109 CurrentEntry
->Flags
= FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
;
1111 /* Update last entry in the segment */
1112 if (CurrentEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
)
1113 Heap
->Segments
[CurrentEntry
->SegmentOffset
]->LastEntryInSegment
= (PHEAP_ENTRY
)CurrentEntry
;
1115 /* Advance FreeEntry and update sizes */
1116 FreeEntry
= CurrentEntry
;
1117 *FreeSize
= *FreeSize
+ CurrentEntry
->Size
;
1118 Heap
->TotalFreeSize
-= CurrentEntry
->Size
;
1119 FreeEntry
->Size
= *FreeSize
;
1121 /* Also update previous size if needed */
1122 if (!(FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
1124 ((PHEAP_ENTRY
)FreeEntry
+ *FreeSize
)->PreviousSize
= *FreeSize
;
1128 /* Check the next block if it exists */
1129 if (!(FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
1131 NextEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)FreeEntry
+ *FreeSize
);
1133 if (!(NextEntry
->Flags
& HEAP_ENTRY_BUSY
) &&
1134 NextEntry
->Size
+ *FreeSize
<= HEAP_MAX_BLOCK_SIZE
)
1136 ASSERT(*FreeSize
== NextEntry
->PreviousSize
);
1138 /* Remove it if asked for */
1141 RtlpRemoveFreeBlock(Heap
, FreeEntry
, FALSE
, FALSE
);
1142 Heap
->TotalFreeSize
-= FreeEntry
->Size
;
1146 FreeEntry
->Flags
= NextEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
;
1148 /* Update last entry in the segment */
1149 if (FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
)
1150 Heap
->Segments
[FreeEntry
->SegmentOffset
]->LastEntryInSegment
= (PHEAP_ENTRY
)FreeEntry
;
1152 /* Remove next entry now */
1153 RtlpRemoveFreeBlock(Heap
, NextEntry
, FALSE
, FALSE
);
1156 *FreeSize
= *FreeSize
+ NextEntry
->Size
;
1157 Heap
->TotalFreeSize
-= NextEntry
->Size
;
1158 FreeEntry
->Size
= *FreeSize
;
1160 /* Also update previous size if needed */
1161 if (!(FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
1163 ((PHEAP_ENTRY
)FreeEntry
+ *FreeSize
)->PreviousSize
= *FreeSize
;
1170 PHEAP_FREE_ENTRY NTAPI
1171 RtlpExtendHeap(PHEAP Heap
,
1175 UCHAR Index
, EmptyIndex
;
1176 SIZE_T FreeSize
, CommitSize
, ReserveSize
;
1177 PHEAP_SEGMENT Segment
;
1178 PHEAP_FREE_ENTRY FreeEntry
;
1181 DPRINT("RtlpExtendHeap(%p %x)\n", Heap
, Size
);
1183 /* Calculate amount in pages */
1184 Pages
= (Size
+ PAGE_SIZE
- 1) / PAGE_SIZE
;
1185 FreeSize
= Pages
* PAGE_SIZE
;
1186 DPRINT("Pages %x, FreeSize %x. Going through segments...\n", Pages
, FreeSize
);
1188 /* Find an empty segment */
1189 EmptyIndex
= HEAP_SEGMENTS
;
1190 for (Index
= 0; Index
< HEAP_SEGMENTS
; Index
++)
1192 Segment
= Heap
->Segments
[Index
];
1194 if (Segment
) DPRINT("Segment[%d] %p with NOUCP %x\n", Index
, Segment
, Segment
->NumberOfUnCommittedPages
);
1196 /* Check if its size suits us */
1198 Pages
<= Segment
->NumberOfUnCommittedPages
)
1200 DPRINT("This segment is suitable\n");
1202 /* Commit needed amount */
1203 FreeEntry
= RtlpFindAndCommitPages(Heap
, Segment
, &FreeSize
, NULL
);
1205 /* Coalesce it with adjacent entries */
1208 FreeSize
= FreeSize
>> HEAP_ENTRY_SHIFT
;
1209 FreeEntry
= RtlpCoalesceFreeBlocks(Heap
, FreeEntry
, &FreeSize
, FALSE
);
1210 RtlpInsertFreeBlock(Heap
, FreeEntry
, FreeSize
);
1214 else if (!Segment
&&
1215 EmptyIndex
== HEAP_SEGMENTS
)
1217 /* Remember the first unused segment index */
1222 /* No luck, need to grow the heap */
1223 if ((Heap
->Flags
& HEAP_GROWABLE
) &&
1224 (EmptyIndex
!= HEAP_SEGMENTS
))
1228 /* Reserve the memory */
1229 if ((Size
+ PAGE_SIZE
) <= Heap
->SegmentReserve
)
1230 ReserveSize
= Heap
->SegmentReserve
;
1232 ReserveSize
= Size
+ PAGE_SIZE
;
1234 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1241 /* If it failed, retry again with a half division algorithm */
1242 while (!NT_SUCCESS(Status
) &&
1243 ReserveSize
!= Size
+ PAGE_SIZE
)
1247 if (ReserveSize
< (Size
+ PAGE_SIZE
))
1248 ReserveSize
= Size
+ PAGE_SIZE
;
1250 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1258 /* Proceed only if it's success */
1259 if (NT_SUCCESS(Status
))
1261 Heap
->SegmentReserve
+= ReserveSize
;
1263 /* Now commit the memory */
1264 if ((Size
+ PAGE_SIZE
) <= Heap
->SegmentCommit
)
1265 CommitSize
= Heap
->SegmentCommit
;
1267 CommitSize
= Size
+ PAGE_SIZE
;
1269 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1276 DPRINT("Committed %d bytes at base %p\n", CommitSize
, Segment
);
1278 /* Initialize heap segment if commit was successful */
1279 if (NT_SUCCESS(Status
))
1281 if (!RtlpInitializeHeapSegment(Heap
, Segment
, EmptyIndex
, 0, Segment
,
1282 (PCHAR
)Segment
+ CommitSize
, (PCHAR
)Segment
+ ReserveSize
))
1284 Status
= STATUS_NO_MEMORY
;
1288 /* If everything worked - cool */
1289 if (NT_SUCCESS(Status
)) return (PHEAP_FREE_ENTRY
)Segment
->FirstEntry
;
1291 DPRINT1("Committing failed with status 0x%08X\n", Status
);
1293 /* Nope, we failed. Free memory */
1294 ZwFreeVirtualMemory(NtCurrentProcess(),
1301 DPRINT1("Reserving failed with status 0x%08X\n", Status
);
1305 if (RtlpGetMode() == UserMode
)
1307 /* If coalescing on free is disabled in usermode, then do it here */
1308 if (Heap
->Flags
& HEAP_DISABLE_COALESCE_ON_FREE
)
1310 FreeEntry
= RtlpCoalesceHeap(Heap
);
1312 /* If it's a suitable one - return it */
1314 FreeEntry
->Size
>= Size
)
1324 /***********************************************************************
1327 * Handle of heap: Success
1333 RtlCreateHeap(ULONG Flags
,
1338 PRTL_HEAP_PARAMETERS Parameters
)
1340 PVOID CommittedAddress
= NULL
, UncommittedAddress
= NULL
;
1342 RTL_HEAP_PARAMETERS SafeParams
= {0};
1344 ULONG_PTR MaximumUserModeAddress
;
1345 SYSTEM_BASIC_INFORMATION SystemInformation
;
1346 MEMORY_BASIC_INFORMATION MemoryInfo
;
1347 ULONG NtGlobalFlags
= RtlGetNtGlobalFlags();
1348 ULONG HeapSegmentFlags
= 0;
1350 ULONG MaxBlockSize
, HeaderSize
;
1351 BOOLEAN AllocateLock
= FALSE
;
1353 /* Check for a special heap */
1354 if (RtlpPageHeapEnabled
&& !Addr
&& !Lock
)
1356 Heap
= RtlpPageHeapCreate(Flags
, Addr
, TotalSize
, CommitSize
, Lock
, Parameters
);
1357 if (Heap
) return Heap
;
1359 /* Reset a special Parameters == -1 hack */
1360 if ((ULONG_PTR
)Parameters
== (ULONG_PTR
)-1)
1363 DPRINT1("Enabling page heap failed\n");
1366 /* Check validation flags */
1367 if (!(Flags
& HEAP_SKIP_VALIDATION_CHECKS
) && (Flags
& ~HEAP_CREATE_VALID_MASK
))
1369 DPRINT1("Invalid flags 0x%08x, fixing...\n", Flags
);
1370 Flags
&= HEAP_CREATE_VALID_MASK
;
1373 /* TODO: Capture parameters, once we decide to use SEH */
1374 if (!Parameters
) Parameters
= &SafeParams
;
1376 /* Check global flags */
1377 if (NtGlobalFlags
& FLG_HEAP_DISABLE_COALESCING
)
1378 Flags
|= HEAP_DISABLE_COALESCE_ON_FREE
;
1380 if (NtGlobalFlags
& FLG_HEAP_ENABLE_FREE_CHECK
)
1381 Flags
|= HEAP_FREE_CHECKING_ENABLED
;
1383 if (NtGlobalFlags
& FLG_HEAP_ENABLE_TAIL_CHECK
)
1384 Flags
|= HEAP_TAIL_CHECKING_ENABLED
;
1386 if (RtlpGetMode() == UserMode
)
1388 /* Also check these flags if in usermode */
1389 if (NtGlobalFlags
& FLG_HEAP_VALIDATE_ALL
)
1390 Flags
|= HEAP_VALIDATE_ALL_ENABLED
;
1392 if (NtGlobalFlags
& FLG_HEAP_VALIDATE_PARAMETERS
)
1393 Flags
|= HEAP_VALIDATE_PARAMETERS_ENABLED
;
1395 if (NtGlobalFlags
& FLG_USER_STACK_TRACE_DB
)
1396 Flags
|= HEAP_CAPTURE_STACK_BACKTRACES
;
1399 Peb
= RtlGetCurrentPeb();
1401 /* Apply defaults for non-set parameters */
1402 if (!Parameters
->SegmentCommit
) Parameters
->SegmentCommit
= Peb
->HeapSegmentCommit
;
1403 if (!Parameters
->SegmentReserve
) Parameters
->SegmentReserve
= Peb
->HeapSegmentReserve
;
1404 if (!Parameters
->DeCommitFreeBlockThreshold
) Parameters
->DeCommitFreeBlockThreshold
= Peb
->HeapDeCommitFreeBlockThreshold
;
1405 if (!Parameters
->DeCommitTotalFreeThreshold
) Parameters
->DeCommitTotalFreeThreshold
= Peb
->HeapDeCommitTotalFreeThreshold
;
1409 /* Apply defaults for non-set parameters */
1411 if (!Parameters
->SegmentCommit
) Parameters
->SegmentCommit
= MmHeapSegmentCommit
;
1412 if (!Parameters
->SegmentReserve
) Parameters
->SegmentReserve
= MmHeapSegmentReserve
;
1413 if (!Parameters
->DeCommitFreeBlockThreshold
) Parameters
->DeCommitFreeBlockThreshold
= MmHeapDeCommitFreeBlockThreshold
;
1414 if (!Parameters
->DeCommitTotalFreeThreshold
) Parameters
->DeCommitTotalFreeThreshold
= MmHeapDeCommitTotalFreeThreshold
;
1418 // FIXME: Move to memory manager
1419 if (!Parameters
->SegmentCommit
) Parameters
->SegmentCommit
= PAGE_SIZE
* 2;
1420 if (!Parameters
->SegmentReserve
) Parameters
->SegmentReserve
= 1048576;
1421 if (!Parameters
->DeCommitFreeBlockThreshold
) Parameters
->DeCommitFreeBlockThreshold
= PAGE_SIZE
;
1422 if (!Parameters
->DeCommitTotalFreeThreshold
) Parameters
->DeCommitTotalFreeThreshold
= 65536;
1424 /* Get the max um address */
1425 Status
= ZwQuerySystemInformation(SystemBasicInformation
,
1427 sizeof(SystemInformation
),
1430 if (!NT_SUCCESS(Status
))
1432 DPRINT1("Getting max usermode address failed with status 0x%08x\n", Status
);
1436 MaximumUserModeAddress
= SystemInformation
.MaximumUserModeAddress
;
1438 /* Calculate max alloc size */
1439 if (!Parameters
->MaximumAllocationSize
)
1440 Parameters
->MaximumAllocationSize
= MaximumUserModeAddress
- (ULONG_PTR
)0x10000 - PAGE_SIZE
;
1442 MaxBlockSize
= 0x80000 - PAGE_SIZE
;
1444 if (!Parameters
->VirtualMemoryThreshold
||
1445 Parameters
->VirtualMemoryThreshold
> MaxBlockSize
)
1447 Parameters
->VirtualMemoryThreshold
= MaxBlockSize
;
1450 /* Check reserve/commit sizes and set default values */
1453 CommitSize
= PAGE_SIZE
;
1455 TotalSize
= ROUND_UP(TotalSize
, PAGE_SIZE
);
1457 TotalSize
= 64 * PAGE_SIZE
;
1461 /* Round up the commit size to be at least the page size */
1462 CommitSize
= ROUND_UP(CommitSize
, PAGE_SIZE
);
1465 TotalSize
= ROUND_UP(TotalSize
, PAGE_SIZE
);
1467 TotalSize
= ROUND_UP(CommitSize
, 16 * PAGE_SIZE
);
1470 /* Call special heap */
1471 if (RtlpHeapIsSpecial(Flags
))
1472 return RtlDebugCreateHeap(Flags
, Addr
, TotalSize
, CommitSize
, Lock
, Parameters
);
1474 /* Calculate header size */
1475 HeaderSize
= sizeof(HEAP
);
1476 if (!(Flags
& HEAP_NO_SERIALIZE
))
1480 Flags
|= HEAP_LOCK_USER_ALLOCATED
;
1484 HeaderSize
+= sizeof(HEAP_LOCK
);
1485 AllocateLock
= TRUE
;
1490 /* Invalid parameters */
1494 /* See if we are already provided with an address for the heap */
1497 if (Parameters
->CommitRoutine
)
1499 /* There is a commit routine, so no problem here, check params */
1500 if ((Flags
& HEAP_GROWABLE
) ||
1501 !Parameters
->InitialCommit
||
1502 !Parameters
->InitialReserve
||
1503 (Parameters
->InitialCommit
> Parameters
->InitialReserve
))
1509 /* Calculate committed and uncommitted addresses */
1510 CommittedAddress
= Addr
;
1511 UncommittedAddress
= (PCHAR
)Addr
+ Parameters
->InitialCommit
;
1512 TotalSize
= Parameters
->InitialReserve
;
1514 /* Zero the initial page ourselves */
1515 RtlZeroMemory(CommittedAddress
, PAGE_SIZE
);
1519 /* Commit routine is absent, so query how much memory caller reserved */
1520 Status
= ZwQueryVirtualMemory(NtCurrentProcess(),
1522 MemoryBasicInformation
,
1527 if (!NT_SUCCESS(Status
))
1529 DPRINT1("Querying amount of user supplied memory failed with status 0x%08X\n", Status
);
1534 if (MemoryInfo
.BaseAddress
!= Addr
||
1535 MemoryInfo
.State
== MEM_FREE
)
1540 /* Validation checks passed, set committed/uncommitted addresses */
1541 CommittedAddress
= Addr
;
1543 /* Check if it's committed or not */
1544 if (MemoryInfo
.State
== MEM_COMMIT
)
1546 /* Zero it out because it's already committed */
1547 RtlZeroMemory(CommittedAddress
, PAGE_SIZE
);
1549 /* Calculate uncommitted address value */
1550 CommitSize
= MemoryInfo
.RegionSize
;
1551 TotalSize
= CommitSize
;
1552 UncommittedAddress
= (PCHAR
)Addr
+ CommitSize
;
1554 /* Check if uncommitted address is reserved */
1555 Status
= ZwQueryVirtualMemory(NtCurrentProcess(),
1557 MemoryBasicInformation
,
1562 if (NT_SUCCESS(Status
) &&
1563 MemoryInfo
.State
== MEM_RESERVE
)
1565 /* It is, so add it up to the reserve size */
1566 TotalSize
+= MemoryInfo
.RegionSize
;
1571 /* It's not committed, inform following code that a commit is necessary */
1572 CommitSize
= PAGE_SIZE
;
1573 UncommittedAddress
= Addr
;
1577 /* Mark this as a user-committed mem */
1578 HeapSegmentFlags
= HEAP_USER_ALLOCATED
;
1583 /* Check commit routine */
1584 if (Parameters
->CommitRoutine
) return NULL
;
1586 /* Reserve memory */
1587 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1594 if (!NT_SUCCESS(Status
))
1596 DPRINT1("Failed to reserve memory with status 0x%08x\n", Status
);
1600 /* Set base addresses */
1601 CommittedAddress
= Heap
;
1602 UncommittedAddress
= Heap
;
1605 /* Check if we need to commit something */
1606 if (CommittedAddress
== UncommittedAddress
)
1608 /* Commit the required size */
1609 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1616 DPRINT("Committed %d bytes at base %p\n", CommitSize
, CommittedAddress
);
1618 if (!NT_SUCCESS(Status
))
1620 DPRINT1("Failure, Status 0x%08X\n", Status
);
1622 /* Release memory if it was reserved */
1623 if (!Addr
) ZwFreeVirtualMemory(NtCurrentProcess(),
1631 /* Calculate new uncommitted address */
1632 UncommittedAddress
= (PCHAR
)UncommittedAddress
+ CommitSize
;
1635 DPRINT("Created heap %p, CommitSize %x, ReserveSize %x\n", Heap
, CommitSize
, TotalSize
);
1637 /* Initialize the heap */
1638 RtlpInitializeHeap(Heap
, &HeaderSize
, Flags
, AllocateLock
, Lock
);
1640 /* Initialize heap's first segment */
1641 if (!RtlpInitializeHeapSegment(Heap
,
1642 (PHEAP_SEGMENT
)((PCHAR
)Heap
+ HeaderSize
),
1647 (PCHAR
)CommittedAddress
+ TotalSize
))
1649 DPRINT1("Failed to initialize heap segment\n");
1653 /* Set other data */
1654 Heap
->ProcessHeapsListIndex
= 0;
1655 Heap
->SegmentCommit
= Parameters
->SegmentCommit
;
1656 Heap
->SegmentReserve
= Parameters
->SegmentReserve
;
1657 Heap
->DeCommitFreeBlockThreshold
= Parameters
->DeCommitFreeBlockThreshold
>> HEAP_ENTRY_SHIFT
;
1658 Heap
->DeCommitTotalFreeThreshold
= Parameters
->DeCommitTotalFreeThreshold
>> HEAP_ENTRY_SHIFT
;
1659 Heap
->MaximumAllocationSize
= Parameters
->MaximumAllocationSize
;
1660 Heap
->VirtualMemoryThreshold
= ROUND_UP(Parameters
->VirtualMemoryThreshold
, HEAP_ENTRY_SIZE
) >> HEAP_ENTRY_SHIFT
;
1661 Heap
->CommitRoutine
= Parameters
->CommitRoutine
;
1664 if (Flags
& HEAP_CREATE_ALIGN_16
)
1666 Heap
->AlignMask
= (ULONG
)~15;
1667 Heap
->AlignRound
= 15 + sizeof(HEAP_ENTRY
);
1671 Heap
->AlignMask
= (ULONG
)~(HEAP_ENTRY_SIZE
- 1);
1672 Heap
->AlignRound
= HEAP_ENTRY_SIZE
- 1 + sizeof(HEAP_ENTRY
);
1675 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
1676 Heap
->AlignRound
+= HEAP_ENTRY_SIZE
;
1678 /* Add heap to process list in case of usermode heap */
1679 if (RtlpGetMode() == UserMode
)
1681 RtlpAddHeapToProcessList(Heap
);
1683 // FIXME: What about lookasides?
1686 DPRINT("Heap %p, flags 0x%08x\n", Heap
, Heap
->Flags
);
1690 /***********************************************************************
1699 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1700 * Failure: The Heap handle, if heap is the process heap.
1703 RtlDestroyHeap(HANDLE HeapPtr
) /* [in] Handle of heap */
1705 PHEAP Heap
= (PHEAP
)HeapPtr
;
1706 PLIST_ENTRY Current
;
1707 PHEAP_UCR_SEGMENT UcrSegment
;
1708 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry
;
1712 PHEAP_SEGMENT Segment
;
1714 if (!HeapPtr
) return NULL
;
1716 /* Call page heap routine if required */
1717 if (Heap
->ForceFlags
& HEAP_FLAG_PAGE_ALLOCS
) return RtlpPageHeapDestroy(HeapPtr
);
1719 /* Call special heap */
1720 if (RtlpHeapIsSpecial(Heap
->Flags
))
1722 if (!RtlDebugDestroyHeap(Heap
)) return HeapPtr
;
1725 /* Check for a process heap */
1726 if (RtlpGetMode() == UserMode
&&
1727 HeapPtr
== NtCurrentPeb()->ProcessHeap
) return HeapPtr
;
1729 /* Free up all big allocations */
1730 Current
= Heap
->VirtualAllocdBlocks
.Flink
;
1731 while (Current
!= &Heap
->VirtualAllocdBlocks
)
1733 VirtualEntry
= CONTAINING_RECORD(Current
, HEAP_VIRTUAL_ALLOC_ENTRY
, Entry
);
1734 BaseAddress
= (PVOID
)VirtualEntry
;
1735 Current
= Current
->Flink
;
1737 ZwFreeVirtualMemory(NtCurrentProcess(),
1743 /* Delete tags and remove heap from the process heaps list in user mode */
1744 if (RtlpGetMode() == UserMode
)
1746 // FIXME DestroyTags
1747 RtlpRemoveHeapFromProcessList(Heap
);
1750 /* Delete the heap lock */
1751 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
1753 /* Delete it if it wasn't user allocated */
1754 if (!(Heap
->Flags
& HEAP_LOCK_USER_ALLOCATED
))
1755 RtlDeleteHeapLock(Heap
->LockVariable
);
1757 /* Clear out the lock variable */
1758 Heap
->LockVariable
= NULL
;
1761 /* Free UCR segments if any were created */
1762 Current
= Heap
->UCRSegments
.Flink
;
1763 while(Current
!= &Heap
->UCRSegments
)
1765 UcrSegment
= CONTAINING_RECORD(Current
, HEAP_UCR_SEGMENT
, ListEntry
);
1767 /* Advance to the next descriptor */
1768 Current
= Current
->Flink
;
1770 BaseAddress
= (PVOID
)UcrSegment
;
1773 /* Release that memory */
1774 ZwFreeVirtualMemory(NtCurrentProcess(),
1780 /* Go through segments and destroy them */
1781 for (i
= HEAP_SEGMENTS
- 1; i
>= 0; i
--)
1783 Segment
= Heap
->Segments
[i
];
1784 if (Segment
) RtlpDestroyHeapSegment(Segment
);
1791 RtlpSplitEntry(PHEAP Heap
,
1792 PHEAP_FREE_ENTRY FreeBlock
,
1793 SIZE_T AllocationSize
,
1797 PHEAP_FREE_ENTRY SplitBlock
, SplitBlock2
;
1799 PHEAP_ENTRY InUseEntry
;
1802 /* Save flags, update total free size */
1803 FreeFlags
= FreeBlock
->Flags
;
1804 Heap
->TotalFreeSize
-= FreeBlock
->Size
;
1806 /* Make this block an in-use one */
1807 InUseEntry
= (PHEAP_ENTRY
)FreeBlock
;
1808 InUseEntry
->Flags
= HEAP_ENTRY_BUSY
;
1809 InUseEntry
->SmallTagIndex
= 0;
1811 /* Calculate the extra amount */
1812 FreeSize
= InUseEntry
->Size
- Index
;
1814 /* Update it's size fields (we don't need their data anymore) */
1815 InUseEntry
->Size
= Index
;
1816 InUseEntry
->UnusedBytes
= AllocationSize
- Size
;
1818 /* If there is something to split - do the split */
1821 /* Don't split if resulting entry can't contain any payload data
1822 (i.e. being just HEAP_ENTRY_SIZE) */
1825 /* Increase sizes of the in-use entry */
1827 InUseEntry
->UnusedBytes
+= sizeof(HEAP_ENTRY
);
1831 /* Calculate a pointer to the new entry */
1832 SplitBlock
= (PHEAP_FREE_ENTRY
)(InUseEntry
+ Index
);
1835 SplitBlock
->Flags
= FreeFlags
;
1836 SplitBlock
->SegmentOffset
= InUseEntry
->SegmentOffset
;
1837 SplitBlock
->Size
= FreeSize
;
1838 SplitBlock
->PreviousSize
= Index
;
1840 /* Check if it's the last entry */
1841 if (FreeFlags
& HEAP_ENTRY_LAST_ENTRY
)
1843 /* Insert it to the free list if it's the last entry */
1844 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
1845 Heap
->TotalFreeSize
+= FreeSize
;
1849 /* Not so easy - need to update next's previous size too */
1850 SplitBlock2
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
);
1852 if (SplitBlock2
->Flags
& HEAP_ENTRY_BUSY
)
1854 SplitBlock2
->PreviousSize
= (USHORT
)FreeSize
;
1855 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
1856 Heap
->TotalFreeSize
+= FreeSize
;
1860 /* Even more complex - the next entry is free, so we can merge them into one! */
1861 SplitBlock
->Flags
= SplitBlock2
->Flags
;
1863 /* Remove that next entry */
1864 RtlpRemoveFreeBlock(Heap
, SplitBlock2
, FALSE
, FALSE
);
1867 FreeSize
+= SplitBlock2
->Size
;
1868 Heap
->TotalFreeSize
-= SplitBlock2
->Size
;
1870 if (FreeSize
<= HEAP_MAX_BLOCK_SIZE
)
1872 /* Insert it back */
1873 SplitBlock
->Size
= FreeSize
;
1875 /* Don't forget to update previous size of the next entry! */
1876 if (!(SplitBlock
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
1878 ((PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
))->PreviousSize
= FreeSize
;
1881 /* Actually insert it */
1882 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, (USHORT
)FreeSize
, FALSE
);
1884 /* Update total size */
1885 Heap
->TotalFreeSize
+= FreeSize
;
1889 /* Resulting block is quite big */
1890 RtlpInsertFreeBlock(Heap
, SplitBlock
, FreeSize
);
1895 /* Reset flags of the free entry */
1898 /* Update last entry in segment */
1899 if (SplitBlock
->Flags
& HEAP_ENTRY_LAST_ENTRY
)
1901 Heap
->Segments
[SplitBlock
->SegmentOffset
]->LastEntryInSegment
= (PHEAP_ENTRY
)SplitBlock
;
1906 /* Set last entry flag */
1907 if (FreeFlags
& HEAP_ENTRY_LAST_ENTRY
)
1908 InUseEntry
->Flags
|= HEAP_ENTRY_LAST_ENTRY
;
1914 RtlpAllocateNonDedicated(PHEAP Heap
,
1917 SIZE_T AllocationSize
,
1921 PLIST_ENTRY FreeListHead
, Next
;
1922 PHEAP_FREE_ENTRY FreeBlock
;
1923 PHEAP_ENTRY InUseEntry
;
1924 PHEAP_ENTRY_EXTRA Extra
;
1925 EXCEPTION_RECORD ExceptionRecord
;
1927 /* Go through the zero list to find a place where to insert the new entry */
1928 FreeListHead
= &Heap
->FreeLists
[0];
1930 /* Start from the largest block to reduce time */
1931 Next
= FreeListHead
->Blink
;
1932 if (FreeListHead
!= Next
)
1934 FreeBlock
= CONTAINING_RECORD(Next
, HEAP_FREE_ENTRY
, FreeList
);
1936 if (FreeBlock
->Size
>= Index
)
1938 /* Our request is smaller than the largest entry in the zero list */
1940 /* Go through the list to find insertion place */
1941 Next
= FreeListHead
->Flink
;
1942 while (FreeListHead
!= Next
)
1944 FreeBlock
= CONTAINING_RECORD(Next
, HEAP_FREE_ENTRY
, FreeList
);
1946 if (FreeBlock
->Size
>= Index
)
1948 /* Found minimally fitting entry. Proceed to either using it as it is
1949 or splitting it to two entries */
1950 RemoveEntryList(&FreeBlock
->FreeList
);
1953 InUseEntry
= RtlpSplitEntry(Heap
, FreeBlock
, AllocationSize
, Index
, Size
);
1955 /* Release the lock */
1956 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
1958 /* Zero memory if that was requested */
1959 if (Flags
& HEAP_ZERO_MEMORY
)
1960 RtlZeroMemory(InUseEntry
+ 1, Size
);
1961 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
1963 /* Fill this block with a special pattern */
1964 RtlFillMemoryUlong(InUseEntry
+ 1, Size
& ~0x3, ARENA_INUSE_FILLER
);
1967 /* Fill tail of the block with a special pattern too if requested */
1968 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
1970 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
, sizeof(HEAP_ENTRY
), HEAP_TAIL_FILL
);
1971 InUseEntry
->Flags
|= HEAP_ENTRY_FILL_PATTERN
;
1974 /* Prepare extra if it's present */
1975 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
1977 Extra
= RtlpGetExtraStuffPointer(InUseEntry
);
1978 RtlZeroMemory(Extra
, sizeof(HEAP_ENTRY_EXTRA
));
1983 /* Return pointer to the */
1984 return InUseEntry
+ 1;
1987 /* Advance to the next entry */
1993 /* Extend the heap, 0 list didn't have anything suitable */
1994 FreeBlock
= RtlpExtendHeap(Heap
, AllocationSize
);
1996 /* Use the new biggest entry we've got */
1999 RemoveEntryList(&FreeBlock
->FreeList
);
2002 InUseEntry
= RtlpSplitEntry(Heap
, FreeBlock
, AllocationSize
, Index
, Size
);
2004 /* Release the lock */
2005 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2007 /* Zero memory if that was requested */
2008 if (Flags
& HEAP_ZERO_MEMORY
)
2009 RtlZeroMemory(InUseEntry
+ 1, Size
);
2010 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
2012 /* Fill this block with a special pattern */
2013 RtlFillMemoryUlong(InUseEntry
+ 1, Size
& ~0x3, ARENA_INUSE_FILLER
);
2016 /* Fill tail of the block with a special pattern too if requested */
2017 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
2019 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
, sizeof(HEAP_ENTRY
), HEAP_TAIL_FILL
);
2020 InUseEntry
->Flags
|= HEAP_ENTRY_FILL_PATTERN
;
2023 /* Prepare extra if it's present */
2024 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
2026 Extra
= RtlpGetExtraStuffPointer(InUseEntry
);
2027 RtlZeroMemory(Extra
, sizeof(HEAP_ENTRY_EXTRA
));
2032 /* Return pointer to the */
2033 return InUseEntry
+ 1;
2036 /* Really unfortunate, out of memory condition */
2037 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_NO_MEMORY
);
2039 /* Generate an exception */
2040 if (Flags
& HEAP_GENERATE_EXCEPTIONS
)
2042 ExceptionRecord
.ExceptionCode
= STATUS_NO_MEMORY
;
2043 ExceptionRecord
.ExceptionRecord
= NULL
;
2044 ExceptionRecord
.NumberParameters
= 1;
2045 ExceptionRecord
.ExceptionFlags
= 0;
2046 ExceptionRecord
.ExceptionInformation
[0] = AllocationSize
;
2048 RtlRaiseException(&ExceptionRecord
);
2051 /* Release the lock */
2052 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2053 DPRINT1("HEAP: Allocation failed!\n");
2054 DPRINT1("Flags %x\n", Heap
->Flags
);
2058 /***********************************************************************
2059 * HeapAlloc (KERNEL32.334)
2061 * Pointer to allocated memory block
2063 * 0x7d030f60--invalid flags in RtlHeapAllocate
2067 RtlAllocateHeap(IN PVOID HeapPtr
,
2071 PHEAP Heap
= (PHEAP
)HeapPtr
;
2072 PULONG FreeListsInUse
;
2073 ULONG FreeListsInUseUlong
;
2074 SIZE_T AllocationSize
;
2076 PLIST_ENTRY FreeListHead
;
2077 PHEAP_ENTRY InUseEntry
;
2078 PHEAP_FREE_ENTRY FreeBlock
;
2079 ULONG InUseIndex
, i
;
2081 EXCEPTION_RECORD ExceptionRecord
;
2082 BOOLEAN HeapLocked
= FALSE
;
2083 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualBlock
= NULL
;
2084 PHEAP_ENTRY_EXTRA Extra
;
2088 Flags
|= Heap
->ForceFlags
;
2090 /* Call special heap */
2091 if (RtlpHeapIsSpecial(Flags
))
2092 return RtlDebugAllocateHeap(Heap
, Flags
, Size
);
2094 /* Check for the maximum size */
2095 if (Size
>= 0x80000000)
2097 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_NO_MEMORY
);
2098 DPRINT1("HEAP: Allocation failed!\n");
2102 if (Flags
& (HEAP_CREATE_ENABLE_TRACING
|
2103 HEAP_CREATE_ALIGN_16
))
2105 DPRINT1("HEAP: RtlAllocateHeap is called with unsupported flags %x, ignoring\n", Flags
);
2108 //DPRINT("RtlAllocateHeap(%p %x %x)\n", Heap, Flags, Size);
2110 /* Calculate allocation size and index */
2112 AllocationSize
= Size
;
2115 AllocationSize
= (AllocationSize
+ Heap
->AlignRound
) & Heap
->AlignMask
;
2116 Index
= AllocationSize
>> HEAP_ENTRY_SHIFT
;
2118 /* Acquire the lock if necessary */
2119 if (!(Flags
& HEAP_NO_SERIALIZE
))
2121 RtlEnterHeapLock(Heap
->LockVariable
);
2125 /* Depending on the size, the allocation is going to be done from dedicated,
2126 non-dedicated lists or a virtual block of memory */
2127 if (Index
< HEAP_FREELISTS
)
2129 FreeListHead
= &Heap
->FreeLists
[Index
];
2131 if (!IsListEmpty(FreeListHead
))
2133 /* There is a free entry in this list */
2134 FreeBlock
= CONTAINING_RECORD(FreeListHead
->Blink
,
2138 /* Save flags and remove the free entry */
2139 FreeFlags
= FreeBlock
->Flags
;
2140 RtlpRemoveFreeBlock(Heap
, FreeBlock
, TRUE
, FALSE
);
2142 /* Update the total free size of the heap */
2143 Heap
->TotalFreeSize
-= Index
;
2145 /* Initialize this block */
2146 InUseEntry
= (PHEAP_ENTRY
)FreeBlock
;
2147 InUseEntry
->Flags
= HEAP_ENTRY_BUSY
| (FreeFlags
& HEAP_ENTRY_LAST_ENTRY
);
2148 InUseEntry
->UnusedBytes
= AllocationSize
- Size
;
2149 InUseEntry
->SmallTagIndex
= 0;
2153 /* Find smallest free block which this request could fit in */
2154 InUseIndex
= Index
>> 5;
2155 FreeListsInUse
= &Heap
->u
.FreeListsInUseUlong
[InUseIndex
];
2157 /* This bit magic disables all sizes which are less than the requested allocation size */
2158 FreeListsInUseUlong
= *FreeListsInUse
++ & ~((1 << ((ULONG
)Index
& 0x1f)) - 1);
2160 /* If size is definitily more than our lists - go directly to the non-dedicated one */
2162 return RtlpAllocateNonDedicated(Heap
, Flags
, Size
, AllocationSize
, Index
, HeapLocked
);
2164 /* Go through the list */
2165 for (i
= InUseIndex
; i
< 4; i
++)
2167 if (FreeListsInUseUlong
)
2169 FreeListHead
= &Heap
->FreeLists
[i
* 32];
2173 if (i
< 3) FreeListsInUseUlong
= *FreeListsInUse
++;
2176 /* Nothing found, search in the non-dedicated list */
2178 return RtlpAllocateNonDedicated(Heap
, Flags
, Size
, AllocationSize
, Index
, HeapLocked
);
2180 /* That list is found, now calculate exact block */
2181 FreeListHead
+= RtlpFindLeastSetBit(FreeListsInUseUlong
);
2183 /* Take this entry and remove it from the list of free blocks */
2184 FreeBlock
= CONTAINING_RECORD(FreeListHead
->Blink
,
2187 RtlpRemoveFreeBlock(Heap
, FreeBlock
, TRUE
, FALSE
);
2190 InUseEntry
= RtlpSplitEntry(Heap
, FreeBlock
, AllocationSize
, Index
, Size
);
2193 /* Release the lock */
2194 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2196 /* Zero memory if that was requested */
2197 if (Flags
& HEAP_ZERO_MEMORY
)
2198 RtlZeroMemory(InUseEntry
+ 1, Size
);
2199 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
2201 /* Fill this block with a special pattern */
2202 RtlFillMemoryUlong(InUseEntry
+ 1, Size
& ~0x3, ARENA_INUSE_FILLER
);
2205 /* Fill tail of the block with a special pattern too if requested */
2206 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
2208 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
, sizeof(HEAP_ENTRY
), HEAP_TAIL_FILL
);
2209 InUseEntry
->Flags
|= HEAP_ENTRY_FILL_PATTERN
;
2212 /* Prepare extra if it's present */
2213 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
2215 Extra
= RtlpGetExtraStuffPointer(InUseEntry
);
2216 RtlZeroMemory(Extra
, sizeof(HEAP_ENTRY_EXTRA
));
2221 /* User data starts right after the entry's header */
2222 return InUseEntry
+ 1;
2224 else if (Index
<= Heap
->VirtualMemoryThreshold
)
2226 /* The block is too large for dedicated lists, but fine for a non-dedicated one */
2227 return RtlpAllocateNonDedicated(Heap
, Flags
, Size
, AllocationSize
, Index
, HeapLocked
);
2229 else if (Heap
->Flags
& HEAP_GROWABLE
)
2231 /* We've got a very big allocation request, satisfy it by directly allocating virtual memory */
2232 AllocationSize
+= sizeof(HEAP_VIRTUAL_ALLOC_ENTRY
) - sizeof(HEAP_ENTRY
);
2234 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
2235 (PVOID
*)&VirtualBlock
,
2241 if (!NT_SUCCESS(Status
))
2244 /* Release the lock */
2245 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2246 DPRINT1("HEAP: Allocation failed!\n");
2250 /* Initialize the newly allocated block */
2251 VirtualBlock
->BusyBlock
.Size
= (AllocationSize
- Size
);
2252 VirtualBlock
->BusyBlock
.Flags
= HEAP_ENTRY_VIRTUAL_ALLOC
| HEAP_ENTRY_EXTRA_PRESENT
| HEAP_ENTRY_BUSY
;
2253 VirtualBlock
->CommitSize
= AllocationSize
;
2254 VirtualBlock
->ReserveSize
= AllocationSize
;
2256 /* Insert it into the list of virtual allocations */
2257 InsertTailList(&Heap
->VirtualAllocdBlocks
, &VirtualBlock
->Entry
);
2259 /* Release the lock */
2260 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2262 /* Return pointer to user data */
2263 return VirtualBlock
+ 1;
2266 /* Generate an exception */
2267 if (Flags
& HEAP_GENERATE_EXCEPTIONS
)
2269 ExceptionRecord
.ExceptionCode
= STATUS_NO_MEMORY
;
2270 ExceptionRecord
.ExceptionRecord
= NULL
;
2271 ExceptionRecord
.NumberParameters
= 1;
2272 ExceptionRecord
.ExceptionFlags
= 0;
2273 ExceptionRecord
.ExceptionInformation
[0] = AllocationSize
;
2275 RtlRaiseException(&ExceptionRecord
);
2278 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_BUFFER_TOO_SMALL
);
2280 /* Release the lock */
2281 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2282 DPRINT1("HEAP: Allocation failed!\n");
2287 /***********************************************************************
2288 * HeapFree (KERNEL32.338)
2295 BOOLEAN NTAPI
RtlFreeHeap(
2296 HANDLE HeapPtr
, /* [in] Handle of heap */
2297 ULONG Flags
, /* [in] Heap freeing flags */
2298 PVOID Ptr
/* [in] Address of memory to free */
2302 PHEAP_ENTRY HeapEntry
;
2303 USHORT TagIndex
= 0;
2305 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry
;
2306 BOOLEAN Locked
= FALSE
;
2309 /* Freeing NULL pointer is a legal operation */
2310 if (!Ptr
) return TRUE
;
2312 /* Get pointer to the heap and force flags */
2313 Heap
= (PHEAP
)HeapPtr
;
2314 Flags
|= Heap
->ForceFlags
;
2316 /* Call special heap */
2317 if (RtlpHeapIsSpecial(Flags
))
2318 return RtlDebugFreeHeap(Heap
, Flags
, Ptr
);
2320 /* Lock if necessary */
2321 if (!(Flags
& HEAP_NO_SERIALIZE
))
2323 RtlEnterHeapLock(Heap
->LockVariable
);
2327 /* Get pointer to the heap entry */
2328 HeapEntry
= (PHEAP_ENTRY
)Ptr
- 1;
2330 /* Check this entry, fail if it's invalid */
2331 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
) ||
2332 (((ULONG_PTR
)Ptr
& 0x7) != 0) ||
2333 (HeapEntry
->SegmentOffset
>= HEAP_SEGMENTS
))
2335 /* This is an invalid block */
2336 DPRINT1("HEAP: Trying to free an invalid address %p!\n", Ptr
);
2337 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
2339 /* Release the heap lock */
2340 if (Locked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2344 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2346 /* Big allocation */
2347 VirtualEntry
= CONTAINING_RECORD(HeapEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
2349 /* Remove it from the list */
2350 RemoveEntryList(&VirtualEntry
->Entry
);
2355 Status
= ZwFreeVirtualMemory(NtCurrentProcess(),
2356 (PVOID
*)&VirtualEntry
,
2360 if (!NT_SUCCESS(Status
))
2362 DPRINT1("HEAP: Failed releasing memory with Status 0x%08X. Heap %p, ptr %p, base address %p\n",
2363 Status
, Heap
, Ptr
, VirtualEntry
);
2364 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(Status
);
2369 /* Normal allocation */
2370 BlockSize
= HeapEntry
->Size
;
2374 /* Coalesce in kernel mode, and in usermode if it's not disabled */
2375 if (RtlpGetMode() == KernelMode
||
2376 (RtlpGetMode() == UserMode
&& !(Heap
->Flags
& HEAP_DISABLE_COALESCE_ON_FREE
)))
2378 HeapEntry
= (PHEAP_ENTRY
)RtlpCoalesceFreeBlocks(Heap
,
2379 (PHEAP_FREE_ENTRY
)HeapEntry
,
2384 /* If there is no need to decommit the block - put it into a free list */
2385 if (BlockSize
< Heap
->DeCommitFreeBlockThreshold
||
2386 (Heap
->TotalFreeSize
+ BlockSize
< Heap
->DeCommitTotalFreeThreshold
))
2388 /* Check if it needs to go to a 0 list */
2389 if (BlockSize
> HEAP_MAX_BLOCK_SIZE
)
2391 /* General-purpose 0 list */
2392 RtlpInsertFreeBlock(Heap
, (PHEAP_FREE_ENTRY
)HeapEntry
, BlockSize
);
2396 /* Usual free list */
2397 RtlpInsertFreeBlockHelper(Heap
, (PHEAP_FREE_ENTRY
)HeapEntry
, BlockSize
, FALSE
);
2399 /* Assert sizes are consistent */
2400 if (!(HeapEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
2402 ASSERT((HeapEntry
+ BlockSize
)->PreviousSize
== BlockSize
);
2405 /* Increase the free size */
2406 Heap
->TotalFreeSize
+= BlockSize
;
2410 if (RtlpGetMode() == UserMode
&&
2419 /* Decommit this block */
2420 RtlpDeCommitFreeBlock(Heap
, (PHEAP_FREE_ENTRY
)HeapEntry
, BlockSize
);
2424 /* Release the heap lock */
2425 if (Locked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2431 RtlpGrowBlockInPlace (IN PHEAP Heap
,
2433 IN PHEAP_ENTRY InUseEntry
,
2437 UCHAR EntryFlags
, RememberFlags
;
2438 PHEAP_FREE_ENTRY FreeEntry
, UnusedEntry
, FollowingEntry
;
2439 SIZE_T FreeSize
, PrevSize
, TailPart
, AddedSize
= 0;
2440 PHEAP_ENTRY_EXTRA OldExtra
, NewExtra
;
2442 /* We can't grow beyond specified threshold */
2443 if (Index
> Heap
->VirtualMemoryThreshold
)
2446 /* Get entry flags */
2447 EntryFlags
= InUseEntry
->Flags
;
2449 /* Get the next free entry */
2450 FreeEntry
= (PHEAP_FREE_ENTRY
)(InUseEntry
+ InUseEntry
->Size
);
2452 if (EntryFlags
& HEAP_ENTRY_LAST_ENTRY
)
2454 /* There is no next block, just uncommitted space. Calculate how much is needed */
2455 FreeSize
= (Index
- InUseEntry
->Size
) << HEAP_ENTRY_SHIFT
;
2456 FreeSize
= ROUND_UP(FreeSize
, PAGE_SIZE
);
2458 /* Find and commit those pages */
2459 FreeEntry
= RtlpFindAndCommitPages(Heap
,
2460 Heap
->Segments
[InUseEntry
->SegmentOffset
],
2464 /* Fail if it failed... */
2465 if (!FreeEntry
) return FALSE
;
2467 /* It was successful, perform coalescing */
2468 FreeSize
= FreeSize
>> HEAP_ENTRY_SHIFT
;
2469 FreeEntry
= RtlpCoalesceFreeBlocks(Heap
, FreeEntry
, &FreeSize
, FALSE
);
2471 /* Check if it's enough */
2472 if (FreeSize
+ InUseEntry
->Size
< Index
)
2474 /* Still not enough */
2475 RtlpInsertFreeBlock(Heap
, FreeEntry
, FreeSize
);
2476 Heap
->TotalFreeSize
+= FreeSize
;
2480 /* Remember flags of this free entry */
2481 RememberFlags
= FreeEntry
->Flags
;
2484 FreeSize
+= InUseEntry
->Size
;
2488 /* The next block indeed exists. Check if it's free or in use */
2489 if (FreeEntry
->Flags
& HEAP_ENTRY_BUSY
) return FALSE
;
2491 /* Next entry is free, check if it can fit the block we need */
2492 FreeSize
= InUseEntry
->Size
+ FreeEntry
->Size
;
2493 if (FreeSize
< Index
) return FALSE
;
2495 /* Remember flags of this free entry */
2496 RememberFlags
= FreeEntry
->Flags
;
2498 /* Remove this block from the free list */
2499 RtlpRemoveFreeBlock(Heap
, FreeEntry
, FALSE
, FALSE
);
2500 Heap
->TotalFreeSize
-= FreeEntry
->Size
;
2503 PrevSize
= (InUseEntry
->Size
<< HEAP_ENTRY_SHIFT
) - InUseEntry
->UnusedBytes
;
2506 /* Don't produce too small blocks */
2513 /* Process extra stuff */
2514 if (RememberFlags
& HEAP_ENTRY_EXTRA_PRESENT
)
2516 /* Calculate pointers */
2517 OldExtra
= (PHEAP_ENTRY_EXTRA
)(InUseEntry
+ InUseEntry
->Size
- 1);
2518 NewExtra
= (PHEAP_ENTRY_EXTRA
)(InUseEntry
+ Index
- 1);
2521 *NewExtra
= *OldExtra
;
2527 InUseEntry
->Size
= Index
;
2528 InUseEntry
->UnusedBytes
= ((Index
<< HEAP_ENTRY_SHIFT
) - Size
);
2530 /* Check if there is a free space remaining after merging those blocks */
2533 /* Update flags and sizes */
2534 InUseEntry
->Flags
|= RememberFlags
& HEAP_ENTRY_LAST_ENTRY
;
2536 /* Either update previous size of the next entry or mark it as a last
2537 entry in the segment*/
2538 if (RememberFlags
& HEAP_ENTRY_LAST_ENTRY
)
2539 Heap
->Segments
[InUseEntry
->SegmentOffset
]->LastEntryInSegment
= InUseEntry
;
2541 (InUseEntry
+ InUseEntry
->Size
)->PreviousSize
= InUseEntry
->Size
;
2545 /* Complex case, we need to split the block to give unused free space
2547 UnusedEntry
= (PHEAP_FREE_ENTRY
)(InUseEntry
+ Index
);
2548 UnusedEntry
->PreviousSize
= Index
;
2549 UnusedEntry
->SegmentOffset
= InUseEntry
->SegmentOffset
;
2551 /* Update the following block or set the last entry in the segment */
2552 if (RememberFlags
& HEAP_ENTRY_LAST_ENTRY
)
2554 /* Set last entry and set flags and size */
2555 Heap
->Segments
[InUseEntry
->SegmentOffset
]->LastEntryInSegment
= InUseEntry
;
2556 UnusedEntry
->Flags
= RememberFlags
;
2557 UnusedEntry
->Size
= FreeSize
;
2559 /* Insert it to the heap and update total size */
2560 RtlpInsertFreeBlockHelper(Heap
, UnusedEntry
, FreeSize
, FALSE
);
2561 Heap
->TotalFreeSize
+= FreeSize
;
2565 /* There is a block after this one */
2566 FollowingEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)UnusedEntry
+ FreeSize
);
2568 if (FollowingEntry
->Flags
& HEAP_ENTRY_BUSY
)
2570 /* Update flags and set size of the unused space entry */
2571 UnusedEntry
->Flags
= RememberFlags
& (~HEAP_ENTRY_LAST_ENTRY
);
2572 UnusedEntry
->Size
= FreeSize
;
2574 /* Update previous size of the following entry */
2575 FollowingEntry
->PreviousSize
= FreeSize
;
2577 /* Insert it to the heap and update total free size */
2578 RtlpInsertFreeBlockHelper(Heap
, UnusedEntry
, FreeSize
, FALSE
);
2579 Heap
->TotalFreeSize
+= FreeSize
;
2583 /* That following entry is also free, what a fortune! */
2584 RememberFlags
= FollowingEntry
->Flags
;
2587 RtlpRemoveFreeBlock(Heap
, FollowingEntry
, FALSE
, FALSE
);
2588 Heap
->TotalFreeSize
-= FollowingEntry
->Size
;
2590 /* And make up a new combined block */
2591 FreeSize
+= FollowingEntry
->Size
;
2592 UnusedEntry
->Flags
= RememberFlags
;
2594 /* Check where to put it */
2595 if (FreeSize
<= HEAP_MAX_BLOCK_SIZE
)
2597 /* Fine for a dedicated list */
2598 UnusedEntry
->Size
= FreeSize
;
2600 if (RememberFlags
& HEAP_ENTRY_LAST_ENTRY
)
2601 Heap
->Segments
[UnusedEntry
->SegmentOffset
]->LastEntryInSegment
= (PHEAP_ENTRY
)UnusedEntry
;
2603 ((PHEAP_ENTRY
)UnusedEntry
+ FreeSize
)->PreviousSize
= FreeSize
;
2605 /* Insert it back and update total size */
2606 RtlpInsertFreeBlockHelper(Heap
, UnusedEntry
, FreeSize
, FALSE
);
2607 Heap
->TotalFreeSize
+= FreeSize
;
2611 /* The block is very large, leave all the hassle to the insertion routine */
2612 RtlpInsertFreeBlock(Heap
, UnusedEntry
, FreeSize
);
2618 /* Copy user settable flags */
2619 InUseEntry
->Flags
&= ~HEAP_ENTRY_SETTABLE_FLAGS
;
2620 InUseEntry
->Flags
|= ((Flags
& HEAP_SETTABLE_USER_FLAGS
) >> 4);
2622 /* Properly "zero out" (and fill!) the space */
2623 if (Flags
& HEAP_ZERO_MEMORY
)
2625 RtlZeroMemory((PCHAR
)(InUseEntry
+ 1) + PrevSize
, Size
- PrevSize
);
2627 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
2629 /* Calculate tail part which we need to fill */
2630 TailPart
= PrevSize
& (sizeof(ULONG
) - 1);
2632 /* "Invert" it as usual */
2633 if (TailPart
) TailPart
= 4 - TailPart
;
2635 if (Size
> (PrevSize
+ TailPart
))
2636 AddedSize
= (Size
- (PrevSize
+ TailPart
)) & ~(sizeof(ULONG
) - 1);
2640 RtlFillMemoryUlong((PCHAR
)(InUseEntry
+ 1) + PrevSize
+ TailPart
,
2642 ARENA_INUSE_FILLER
);
2646 /* Fill the new tail */
2647 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
2649 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
,
2654 /* Return success */
2658 PHEAP_ENTRY_EXTRA NTAPI
2659 RtlpGetExtraStuffPointer(PHEAP_ENTRY HeapEntry
)
2661 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry
;
2663 /* Check if it's a big block */
2664 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2666 VirtualEntry
= CONTAINING_RECORD(HeapEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
2668 /* Return a pointer to the extra stuff*/
2669 return &VirtualEntry
->ExtraStuff
;
2673 /* This is a usual entry, which means extra stuff follows this block */
2674 return (PHEAP_ENTRY_EXTRA
)(HeapEntry
+ HeapEntry
->Size
- 1);
2679 /***********************************************************************
2682 * Heap [in] Handle of heap block
2683 * Flags [in] Heap reallocation flags
2684 * Ptr, [in] Address of memory to reallocate
2685 * Size [in] Number of bytes to reallocate
2688 * Pointer to reallocated memory block
2690 * 0x7d030f60--invalid flags in RtlHeapAllocate
2694 RtlReAllocateHeap(HANDLE HeapPtr
,
2699 PHEAP Heap
= (PHEAP
)HeapPtr
;
2700 PHEAP_ENTRY InUseEntry
, NewInUseEntry
;
2701 PHEAP_ENTRY_EXTRA OldExtra
, NewExtra
;
2702 SIZE_T AllocationSize
, FreeSize
, DecommitSize
;
2703 BOOLEAN HeapLocked
= FALSE
;
2704 PVOID NewBaseAddress
;
2705 PHEAP_FREE_ENTRY SplitBlock
, SplitBlock2
;
2706 SIZE_T OldSize
, Index
, OldIndex
;
2710 SIZE_T RemainderBytes
, ExtraSize
;
2711 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualAllocBlock
;
2712 EXCEPTION_RECORD ExceptionRecord
;
2714 /* Return success in case of a null pointer */
2717 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_SUCCESS
);
2721 /* Force heap flags */
2722 Flags
|= Heap
->ForceFlags
;
2724 /* Call special heap */
2725 if (RtlpHeapIsSpecial(Flags
))
2726 return RtlDebugReAllocateHeap(Heap
, Flags
, Ptr
, Size
);
2728 /* Make sure size is valid */
2729 if (Size
>= 0x80000000)
2731 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_NO_MEMORY
);
2735 /* Calculate allocation size and index */
2737 AllocationSize
= Size
;
2740 AllocationSize
= (AllocationSize
+ Heap
->AlignRound
) & Heap
->AlignMask
;
2742 /* Add up extra stuff, if it is present anywhere */
2743 if (((((PHEAP_ENTRY
)Ptr
)-1)->Flags
& HEAP_ENTRY_EXTRA_PRESENT
) ||
2744 (Flags
& HEAP_EXTRA_FLAGS_MASK
) ||
2745 Heap
->PseudoTagEntries
)
2747 AllocationSize
+= sizeof(HEAP_ENTRY_EXTRA
);
2750 /* Acquire the lock if necessary */
2751 if (!(Flags
& HEAP_NO_SERIALIZE
))
2753 RtlEnterHeapLock(Heap
->LockVariable
);
2755 Flags
^= HEAP_NO_SERIALIZE
;
2758 /* Get the pointer to the in-use entry */
2759 InUseEntry
= (PHEAP_ENTRY
)Ptr
- 1;
2761 /* If that entry is not really in-use, we have a problem */
2762 if (!(InUseEntry
->Flags
& HEAP_ENTRY_BUSY
))
2764 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
2766 /* Release the lock and return */
2768 RtlLeaveHeapLock(Heap
->LockVariable
);
2772 if (InUseEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2774 /* This is a virtually allocated block. Get its size */
2775 OldSize
= RtlpGetSizeOfBigBlock(InUseEntry
);
2777 /* Convert it to an index */
2778 OldIndex
= (OldSize
+ InUseEntry
->Size
) >> HEAP_ENTRY_SHIFT
;
2780 /* Calculate new allocation size and round it to the page size */
2781 AllocationSize
+= FIELD_OFFSET(HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
2782 AllocationSize
= ROUND_UP(AllocationSize
, PAGE_SIZE
);
2787 OldIndex
= InUseEntry
->Size
;
2789 OldSize
= (OldIndex
<< HEAP_ENTRY_SHIFT
) - InUseEntry
->UnusedBytes
;
2792 /* Calculate new index */
2793 Index
= AllocationSize
>> HEAP_ENTRY_SHIFT
;
2795 /* Check for 4 different scenarios (old size, new size, old index, new index) */
2796 if (Index
<= OldIndex
)
2798 /* Difference must be greater than 1, adjust if it's not so */
2799 if (Index
+ 1 == OldIndex
)
2802 AllocationSize
+= sizeof(HEAP_ENTRY
);
2805 /* Calculate new size */
2806 if (InUseEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2808 /* Simple in case of a virtual alloc - just an unused size */
2809 InUseEntry
->Size
= AllocationSize
- Size
;
2811 else if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
2813 /* There is extra stuff, take it into account */
2814 OldExtra
= (PHEAP_ENTRY_EXTRA
)(InUseEntry
+ InUseEntry
->Size
- 1);
2815 NewExtra
= (PHEAP_ENTRY_EXTRA
)(InUseEntry
+ Index
- 1);
2816 *NewExtra
= *OldExtra
;
2818 // FIXME Tagging, TagIndex
2820 /* Update unused bytes count */
2821 InUseEntry
->UnusedBytes
= AllocationSize
- Size
;
2825 // FIXME Tagging, SmallTagIndex
2826 InUseEntry
->UnusedBytes
= AllocationSize
- Size
;
2829 /* If new size is bigger than the old size */
2832 /* Zero out that additional space if required */
2833 if (Flags
& HEAP_ZERO_MEMORY
)
2835 RtlZeroMemory((PCHAR
)Ptr
+ OldSize
, Size
- OldSize
);
2837 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
2839 /* Fill it on free if required */
2840 RemainderBytes
= OldSize
& (sizeof(ULONG
) - 1);
2843 RemainderBytes
= 4 - RemainderBytes
;
2845 if (Size
> (OldSize
+ RemainderBytes
))
2847 /* Calculate actual amount of extra bytes to fill */
2848 ExtraSize
= (Size
- (OldSize
+ RemainderBytes
)) & ~(sizeof(ULONG
) - 1);
2850 /* Fill them if there are any */
2853 RtlFillMemoryUlong((PCHAR
)(InUseEntry
+ 1) + OldSize
+ RemainderBytes
,
2855 ARENA_INUSE_FILLER
);
2861 /* Fill tail of the heap entry if required */
2862 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
2864 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
,
2869 /* Check if the difference is significant or not */
2870 if (Index
!= OldIndex
)
2873 FreeFlags
= InUseEntry
->Flags
& ~HEAP_ENTRY_BUSY
;
2875 if (FreeFlags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2877 /* This is a virtual block allocation */
2878 VirtualAllocBlock
= CONTAINING_RECORD(InUseEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
2882 DecommitBase
= (PCHAR
)VirtualAllocBlock
+ AllocationSize
;
2883 DecommitSize
= (OldIndex
<< HEAP_ENTRY_SHIFT
) - AllocationSize
;
2885 /* Release the memory */
2886 Status
= ZwFreeVirtualMemory(NtCurrentProcess(),
2887 (PVOID
*)&DecommitBase
,
2891 if (!NT_SUCCESS(Status
))
2893 DPRINT1("HEAP: Unable to release memory (pointer %p, size 0x%x), Status %08x\n", DecommitBase
, DecommitSize
, Status
);
2897 /* Otherwise reduce the commit size */
2898 VirtualAllocBlock
->CommitSize
-= DecommitSize
;
2903 /* Reduce size of the block and possibly split it */
2904 SplitBlock
= (PHEAP_FREE_ENTRY
)(InUseEntry
+ Index
);
2906 /* Initialize this entry */
2907 SplitBlock
->Flags
= FreeFlags
;
2908 SplitBlock
->PreviousSize
= Index
;
2909 SplitBlock
->SegmentOffset
= InUseEntry
->SegmentOffset
;
2911 /* Remember free size */
2912 FreeSize
= InUseEntry
->Size
- Index
;
2915 InUseEntry
->Size
= Index
;
2916 InUseEntry
->Flags
&= ~HEAP_ENTRY_LAST_ENTRY
;
2918 /* Is that the last entry */
2919 if (FreeFlags
& HEAP_ENTRY_LAST_ENTRY
)
2921 /* Update segment's last entry */
2922 Heap
->Segments
[SplitBlock
->SegmentOffset
]->LastEntryInSegment
= (PHEAP_ENTRY
)SplitBlock
;
2924 /* Set its size and insert it to the list */
2925 SplitBlock
->Size
= (USHORT
)FreeSize
;
2926 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
2928 /* Update total free size */
2929 Heap
->TotalFreeSize
+= FreeSize
;
2933 /* Get the block after that one */
2934 SplitBlock2
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
);
2936 if (SplitBlock2
->Flags
& HEAP_ENTRY_BUSY
)
2938 /* It's in use, add it here*/
2939 SplitBlock
->Size
= (USHORT
)FreeSize
;
2941 /* Update previous size of the next entry */
2942 ((PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
))->PreviousSize
= (USHORT
)FreeSize
;
2944 /* Insert it to the list */
2945 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
2947 /* Update total size */
2948 Heap
->TotalFreeSize
+= FreeSize
;
2952 /* Next entry is free, so merge with it */
2953 SplitBlock
->Flags
= SplitBlock2
->Flags
;
2955 /* Remove it, update total size */
2956 RtlpRemoveFreeBlock(Heap
, SplitBlock2
, FALSE
, FALSE
);
2957 Heap
->TotalFreeSize
-= SplitBlock2
->Size
;
2959 /* Calculate total free size */
2960 FreeSize
+= SplitBlock2
->Size
;
2962 if (FreeSize
<= HEAP_MAX_BLOCK_SIZE
)
2964 SplitBlock
->Size
= FreeSize
;
2966 if (!(SplitBlock
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
2968 /* Update previous size of the next entry */
2969 ((PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
))->PreviousSize
= FreeSize
;
2973 Heap
->Segments
[SplitBlock
->SegmentOffset
]->LastEntryInSegment
= (PHEAP_ENTRY
)SplitBlock
;
2976 /* Insert the new one back and update total size */
2977 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
2978 Heap
->TotalFreeSize
+= FreeSize
;
2983 RtlpInsertFreeBlock(Heap
, SplitBlock
, FreeSize
);
2992 /* We're growing the block */
2993 if ((InUseEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
) ||
2994 !RtlpGrowBlockInPlace(Heap
, Flags
, InUseEntry
, Size
, Index
))
2996 /* Growing in place failed, so growing out of place */
2997 if (Flags
& HEAP_REALLOC_IN_PLACE_ONLY
)
2999 DPRINT1("Realloc in place failed, but it was the only option\n");
3004 /* Clear tag bits */
3005 Flags
&= ~HEAP_TAG_MASK
;
3007 /* Process extra stuff */
3008 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
3010 /* Preserve user settable flags */
3011 Flags
&= ~HEAP_SETTABLE_USER_FLAGS
;
3013 Flags
|= HEAP_SETTABLE_USER_VALUE
| ((InUseEntry
->Flags
& HEAP_ENTRY_SETTABLE_FLAGS
) << 4);
3015 /* Get pointer to the old extra data */
3016 OldExtra
= RtlpGetExtraStuffPointer(InUseEntry
);
3018 /* Save tag index if it was set */
3019 if (OldExtra
->TagIndex
&&
3020 !(OldExtra
->TagIndex
& HEAP_PSEUDO_TAG_FLAG
))
3022 Flags
|= OldExtra
->TagIndex
<< HEAP_TAG_SHIFT
;
3025 else if (InUseEntry
->SmallTagIndex
)
3027 /* Take small tag index into account */
3028 Flags
|= InUseEntry
->SmallTagIndex
<< HEAP_TAG_SHIFT
;
3031 /* Allocate new block from the heap */
3032 NewBaseAddress
= RtlAllocateHeap(HeapPtr
,
3033 Flags
& ~HEAP_ZERO_MEMORY
,
3036 /* Proceed if it didn't fail */
3039 /* Get new entry pointer */
3040 NewInUseEntry
= (PHEAP_ENTRY
)NewBaseAddress
- 1;
3042 /* Process extra stuff if it exists */
3043 if (NewInUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
3045 NewExtra
= RtlpGetExtraStuffPointer(NewInUseEntry
);
3047 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
3049 OldExtra
= RtlpGetExtraStuffPointer(InUseEntry
);
3050 NewExtra
->Settable
= OldExtra
->Settable
;
3054 RtlZeroMemory(NewExtra
, sizeof(*NewExtra
));
3058 /* Copy actual user bits */
3060 RtlMoveMemory(NewBaseAddress
, Ptr
, Size
);
3062 RtlMoveMemory(NewBaseAddress
, Ptr
, OldSize
);
3064 /* Zero remaining part if required */
3065 if (Size
> OldSize
&&
3066 (Flags
& HEAP_ZERO_MEMORY
))
3068 RtlZeroMemory((PCHAR
)NewBaseAddress
+ OldSize
, Size
- OldSize
);
3071 /* Free the old block */
3072 RtlFreeHeap(HeapPtr
, Flags
, Ptr
);
3075 Ptr
= NewBaseAddress
;
3080 /* Did resizing fail? */
3081 if (!Ptr
&& (Flags
& HEAP_GENERATE_EXCEPTIONS
))
3083 /* Generate an exception if required */
3084 ExceptionRecord
.ExceptionCode
= STATUS_NO_MEMORY
;
3085 ExceptionRecord
.ExceptionRecord
= NULL
;
3086 ExceptionRecord
.NumberParameters
= 1;
3087 ExceptionRecord
.ExceptionFlags
= 0;
3088 ExceptionRecord
.ExceptionInformation
[0] = AllocationSize
;
3090 RtlRaiseException(&ExceptionRecord
);
3093 /* Release the heap lock if it was acquired */
3095 RtlLeaveHeapLock(Heap
->LockVariable
);
3101 /***********************************************************************
3107 RtlCompactHeap(HANDLE Heap
,
3115 /***********************************************************************
3117 * Attempts to acquire the critical section object for a specified heap.
3120 * Heap [in] Handle of heap to lock for exclusive access
3129 RtlLockHeap(IN HANDLE HeapPtr
)
3131 PHEAP Heap
= (PHEAP
)HeapPtr
;
3133 // FIXME Check for special heap
3135 /* Check if it's really a heap */
3136 if (Heap
->Signature
!= HEAP_SIGNATURE
) return FALSE
;
3138 /* Lock if it's lockable */
3139 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
3141 RtlEnterHeapLock(Heap
->LockVariable
);
3148 /***********************************************************************
3150 * Releases ownership of the critical section object.
3153 * Heap [in] Handle to the heap to unlock
3162 RtlUnlockHeap(HANDLE HeapPtr
)
3164 PHEAP Heap
= (PHEAP
)HeapPtr
;
3166 // FIXME Check for special heap
3168 /* Check if it's really a heap */
3169 if (Heap
->Signature
!= HEAP_SIGNATURE
) return FALSE
;
3171 /* Unlock if it's lockable */
3172 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
3174 RtlLeaveHeapLock(Heap
->LockVariable
);
3181 /***********************************************************************
3184 * Heap [in] Handle of heap
3185 * Flags [in] Heap size control flags
3186 * Ptr [in] Address of memory to return size for
3189 * Size in bytes of allocated memory
3190 * 0xffffffff: Failure
3201 PHEAP Heap
= (PHEAP
)HeapPtr
;
3202 PHEAP_ENTRY HeapEntry
;
3205 // FIXME This is a hack around missing SEH support!
3208 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_HANDLE
);
3213 Flags
|= Heap
->ForceFlags
;
3215 /* Call special heap */
3216 if (RtlpHeapIsSpecial(Flags
))
3217 return RtlDebugSizeHeap(Heap
, Flags
, Ptr
);
3219 /* Get the heap entry pointer */
3220 HeapEntry
= (PHEAP_ENTRY
)Ptr
- 1;
3222 /* Return -1 if that entry is free */
3223 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
))
3225 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
3229 /* Get size of this block depending if it's a usual or a big one */
3230 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
3232 EntrySize
= RtlpGetSizeOfBigBlock(HeapEntry
);
3237 EntrySize
= (HeapEntry
->Size
<< HEAP_ENTRY_SHIFT
) - HeapEntry
->UnusedBytes
;
3240 /* Return calculated size */
3245 RtlpCheckInUsePattern(PHEAP_ENTRY HeapEntry
)
3247 SIZE_T Size
, Result
;
3250 /* Calculate size */
3251 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
3252 Size
= RtlpGetSizeOfBigBlock(HeapEntry
);
3254 Size
= (HeapEntry
->Size
<< HEAP_ENTRY_SHIFT
) - HeapEntry
->UnusedBytes
;
3256 /* Calculate pointer to the tail part of the block */
3257 TailPart
= (PCHAR
)(HeapEntry
+ 1) + Size
;
3259 /* Compare tail pattern */
3260 Result
= RtlCompareMemory(TailPart
,
3264 if (Result
!= HEAP_ENTRY_SIZE
)
3266 DPRINT1("HEAP: Heap entry (size %x) %p tail is modified at %p\n", Size
, HeapEntry
, TailPart
+ Result
);
3275 RtlpValidateHeapHeaders(
3277 BOOLEAN Recalculate
)
3279 // We skip header validation for now
3284 RtlpValidateHeapEntry(
3286 PHEAP_ENTRY HeapEntry
)
3288 BOOLEAN BigAllocation
, EntryFound
= FALSE
;
3289 PHEAP_SEGMENT Segment
;
3290 ULONG SegmentOffset
;
3292 /* Perform various consistency checks of this entry */
3293 if (!HeapEntry
) goto invalid_entry
;
3294 if ((ULONG_PTR
)HeapEntry
& (HEAP_ENTRY_SIZE
- 1)) goto invalid_entry
;
3295 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
)) goto invalid_entry
;
3297 BigAllocation
= HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
;
3298 Segment
= Heap
->Segments
[HeapEntry
->SegmentOffset
];
3300 if (BigAllocation
&&
3301 (((ULONG_PTR
)HeapEntry
& (PAGE_SIZE
- 1)) != FIELD_OFFSET(HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
)))
3304 if (!BigAllocation
&& (HeapEntry
->SegmentOffset
>= HEAP_SEGMENTS
||
3306 HeapEntry
< Segment
->FirstEntry
||
3307 HeapEntry
>= Segment
->LastValidEntry
))
3310 if ((HeapEntry
->Flags
& HEAP_ENTRY_FILL_PATTERN
) &&
3311 !RtlpCheckInUsePattern(HeapEntry
))
3314 /* Checks are done, if this is a virtual entry, that's all */
3315 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
) return TRUE
;
3317 /* Go through segments and check if this entry fits into any of them */
3318 for (SegmentOffset
= 0; SegmentOffset
< HEAP_SEGMENTS
; SegmentOffset
++)
3320 Segment
= Heap
->Segments
[SegmentOffset
];
3321 if (!Segment
) continue;
3323 if ((HeapEntry
>= Segment
->FirstEntry
) &&
3324 (HeapEntry
< Segment
->LastValidEntry
))
3332 /* Return our result of finding entry in the segments */
3336 DPRINT1("HEAP: Invalid heap entry %p in heap %p\n", HeapEntry
, Heap
);
3341 RtlpValidateHeapSegment(
3343 PHEAP_SEGMENT Segment
,
3344 UCHAR SegmentOffset
,
3345 PULONG FreeEntriesCount
,
3346 PSIZE_T TotalFreeSize
,
3348 PSIZE_T PseudoTagEntries
)
3350 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
3351 PLIST_ENTRY UcrEntry
;
3352 SIZE_T ByteSize
, Size
, Result
;
3353 PHEAP_ENTRY CurrentEntry
;
3354 ULONG UnCommittedPages
;
3355 ULONG UnCommittedRanges
;
3358 UnCommittedPages
= 0;
3359 UnCommittedRanges
= 0;
3361 if (IsListEmpty(&Segment
->UCRSegmentList
))
3364 UcrDescriptor
= NULL
;
3368 UcrEntry
= Segment
->UCRSegmentList
.Flink
;
3369 UcrDescriptor
= CONTAINING_RECORD(UcrEntry
, HEAP_UCR_DESCRIPTOR
, SegmentEntry
);
3372 if (Segment
->BaseAddress
== Heap
)
3373 CurrentEntry
= &Heap
->Entry
;
3375 CurrentEntry
= &Segment
->Entry
;
3377 while (CurrentEntry
< Segment
->LastValidEntry
)
3379 if (UcrDescriptor
&&
3380 ((PVOID
)CurrentEntry
>= UcrDescriptor
->Address
))
3382 DPRINT1("HEAP: Entry %p is not inside uncommited range [%p .. %p)\n",
3383 CurrentEntry
, UcrDescriptor
->Address
,
3384 (PCHAR
)UcrDescriptor
->Address
+ UcrDescriptor
->Size
);
3391 while (CurrentEntry
< Segment
->LastValidEntry
)
3393 if (PreviousSize
!= CurrentEntry
->PreviousSize
)
3395 DPRINT1("HEAP: Entry %p has incorrect PreviousSize %x instead of %x\n",
3396 CurrentEntry
, CurrentEntry
->PreviousSize
, PreviousSize
);
3401 PreviousSize
= CurrentEntry
->Size
;
3402 Size
= CurrentEntry
->Size
<< HEAP_ENTRY_SHIFT
;
3404 if (CurrentEntry
->Flags
& HEAP_ENTRY_BUSY
)
3411 /* Check fill pattern */
3412 if (CurrentEntry
->Flags
& HEAP_ENTRY_FILL_PATTERN
)
3414 if (!RtlpCheckInUsePattern(CurrentEntry
))
3420 /* The entry is free, increase free entries count and total free size */
3421 *FreeEntriesCount
= *FreeEntriesCount
+ 1;
3422 *TotalFreeSize
+= CurrentEntry
->Size
;
3424 if ((Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
) &&
3425 (CurrentEntry
->Flags
& HEAP_ENTRY_FILL_PATTERN
))
3427 ByteSize
= Size
- sizeof(HEAP_FREE_ENTRY
);
3429 if ((CurrentEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
) &&
3430 (ByteSize
> sizeof(HEAP_FREE_ENTRY_EXTRA
)))
3432 ByteSize
-= sizeof(HEAP_FREE_ENTRY_EXTRA
);
3435 Result
= RtlCompareMemoryUlong((PCHAR
)((PHEAP_FREE_ENTRY
)CurrentEntry
+ 1),
3439 if (Result
!= ByteSize
)
3441 DPRINT1("HEAP: Free heap block %p modified at %p after it was freed\n",
3443 (PCHAR
)(CurrentEntry
+ 1) + Result
);
3450 if (CurrentEntry
->SegmentOffset
!= SegmentOffset
)
3452 DPRINT1("HEAP: Heap entry %p SegmentOffset is incorrect %x (should be %x)\n", CurrentEntry
, SegmentOffset
, CurrentEntry
->SegmentOffset
);
3456 /* Check if it's the last entry */
3457 if (CurrentEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
)
3459 CurrentEntry
= (PHEAP_ENTRY
)((PCHAR
)CurrentEntry
+ Size
);
3463 /* Check if it's not really the last one */
3464 if (CurrentEntry
!= Segment
->LastValidEntry
)
3466 DPRINT1("HEAP: Heap entry %p is not last block in segment (%x)\n", CurrentEntry
, Segment
->LastValidEntry
);
3470 else if (CurrentEntry
!= UcrDescriptor
->Address
)
3472 DPRINT1("HEAP: Heap entry %p does not match next uncommitted address (%p)\n",
3473 CurrentEntry
, UcrDescriptor
->Address
);
3479 UnCommittedPages
+= (UcrDescriptor
->Size
/ PAGE_SIZE
);
3480 UnCommittedRanges
++;
3482 CurrentEntry
= (PHEAP_ENTRY
)((PCHAR
)UcrDescriptor
->Address
+ UcrDescriptor
->Size
);
3484 /* Go to the next UCR descriptor */
3485 UcrEntry
= UcrEntry
->Flink
;
3486 if (UcrEntry
== &Segment
->UCRSegmentList
)
3489 UcrDescriptor
= NULL
;
3493 UcrDescriptor
= CONTAINING_RECORD(UcrEntry
, HEAP_UCR_DESCRIPTOR
, SegmentEntry
);
3500 /* Advance to the next entry */
3501 CurrentEntry
= (PHEAP_ENTRY
)((PCHAR
)CurrentEntry
+ Size
);
3505 /* Check total numbers of UCP and UCR */
3506 if (Segment
->NumberOfUnCommittedPages
!= UnCommittedPages
)
3508 DPRINT1("HEAP: Segment %p NumberOfUnCommittedPages is invalid (%x != %x)\n",
3509 Segment
, Segment
->NumberOfUnCommittedPages
, UnCommittedPages
);
3514 if (Segment
->NumberOfUnCommittedRanges
!= UnCommittedRanges
)
3516 DPRINT1("HEAP: Segment %p NumberOfUnCommittedRanges is invalid (%x != %x)\n",
3517 Segment
, Segment
->NumberOfUnCommittedRanges
, UnCommittedRanges
);
3526 RtlpValidateHeap(PHEAP Heap
,
3527 BOOLEAN ForceValidation
)
3529 PHEAP_SEGMENT Segment
;
3531 UCHAR SegmentOffset
;
3532 SIZE_T Size
, TotalFreeSize
;
3534 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualAllocBlock
;
3535 PLIST_ENTRY ListHead
, NextEntry
;
3536 PHEAP_FREE_ENTRY FreeEntry
;
3537 ULONG FreeBlocksCount
, FreeListEntriesCount
;
3540 if (!RtlpValidateHeapHeaders(Heap
, FALSE
))
3543 /* Skip validation if it's not needed */
3544 if (!ForceValidation
&& !(Heap
->Flags
& HEAP_VALIDATE_ALL_ENABLED
))
3547 /* Check free lists bitmaps */
3548 FreeListEntriesCount
= 0;
3549 ListHead
= &Heap
->FreeLists
[0];
3551 for (Size
= 0; Size
< HEAP_FREELISTS
; Size
++)
3555 /* This is a dedicated list. Check if it's empty */
3556 EmptyList
= IsListEmpty(ListHead
);
3558 if (Heap
->u
.FreeListsInUseBytes
[Size
>> 3] & (1 << (Size
& 7)))
3562 DPRINT1("HEAP: Empty %x-free list marked as non-empty\n", Size
);
3570 DPRINT1("HEAP: Non-empty %x-free list marked as empty\n", Size
);
3576 /* Now check this list entries */
3577 NextEntry
= ListHead
->Flink
;
3580 while (ListHead
!= NextEntry
)
3582 FreeEntry
= CONTAINING_RECORD(NextEntry
, HEAP_FREE_ENTRY
, FreeList
);
3583 NextEntry
= NextEntry
->Flink
;
3585 /* If there is an in-use entry in a free list - that's quite a big problem */
3586 if (FreeEntry
->Flags
& HEAP_ENTRY_BUSY
)
3588 DPRINT1("HEAP: %x-dedicated list free element %x is marked in-use\n", Size
, FreeEntry
);
3592 /* Check sizes according to that specific list's size */
3593 if ((Size
== 0) && (FreeEntry
->Size
< HEAP_FREELISTS
))
3595 DPRINT1("HEAP: Non dedicated list free element %x has size %x which would fit a dedicated list\n", FreeEntry
, FreeEntry
->Size
);
3598 else if (Size
&& (FreeEntry
->Size
!= Size
))
3600 DPRINT1("HEAP: %x-dedicated list free element %x has incorrect size %x\n", Size
, FreeEntry
, FreeEntry
->Size
);
3603 else if ((Size
== 0) && (FreeEntry
->Size
< PreviousSize
))
3605 DPRINT1("HEAP: Non dedicated list free element %x is not put in order\n", FreeEntry
);
3609 /* Remember previous size*/
3610 PreviousSize
= FreeEntry
->Size
;
3612 /* Add up to the total amount of free entries */
3613 FreeListEntriesCount
++;
3616 /* Go to the head of the next free list */
3620 /* Check big allocations */
3621 ListHead
= &Heap
->VirtualAllocdBlocks
;
3622 NextEntry
= ListHead
->Flink
;
3624 while (ListHead
!= NextEntry
)
3626 VirtualAllocBlock
= CONTAINING_RECORD(NextEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, Entry
);
3628 /* We can only check the fill pattern */
3629 if (VirtualAllocBlock
->BusyBlock
.Flags
& HEAP_ENTRY_FILL_PATTERN
)
3631 if (!RtlpCheckInUsePattern(&VirtualAllocBlock
->BusyBlock
))
3635 NextEntry
= NextEntry
->Flink
;
3638 /* Check all segments */
3639 FreeBlocksCount
= 0;
3642 for (SegmentOffset
= 0; SegmentOffset
< HEAP_SEGMENTS
; SegmentOffset
++)
3644 Segment
= Heap
->Segments
[SegmentOffset
];
3646 /* Go to the next one if there is no segment */
3647 if (!Segment
) continue;
3649 if (!RtlpValidateHeapSegment(Heap
,
3661 if (FreeListEntriesCount
!= FreeBlocksCount
)
3663 DPRINT1("HEAP: Free blocks count in arena (%d) does not match free blocks number in the free lists (%d)\n", FreeBlocksCount
, FreeListEntriesCount
);
3667 if (Heap
->TotalFreeSize
!= TotalFreeSize
)
3669 DPRINT1("HEAP: Total size of free blocks in arena (%d) does not equal to the one in heap header (%d)\n", TotalFreeSize
, Heap
->TotalFreeSize
);
3676 /***********************************************************************
3678 * Validates a specified heap.
3681 * Heap [in] Handle to the heap
3682 * Flags [in] Bit flags that control access during operation
3683 * Block [in] Optional pointer to memory block to validate
3694 BOOLEAN NTAPI
RtlValidateHeap(
3700 PHEAP Heap
= (PHEAP
)HeapPtr
;
3701 BOOLEAN HeapLocked
= FALSE
;
3704 /* Check for page heap */
3705 if (Heap
->ForceFlags
& HEAP_FLAG_PAGE_ALLOCS
)
3706 return RtlpDebugPageHeapValidate(HeapPtr
, Flags
, Block
);
3708 /* Check signature */
3709 if (Heap
->Signature
!= HEAP_SIGNATURE
)
3711 DPRINT1("HEAP: Signature %x is invalid for heap %p\n", Heap
->Signature
, Heap
);
3716 Flags
= Heap
->ForceFlags
;
3718 /* Acquire the lock if necessary */
3719 if (!(Flags
& HEAP_NO_SERIALIZE
))
3721 RtlEnterHeapLock(Heap
->LockVariable
);
3725 /* Either validate whole heap or just one entry */
3727 HeapValid
= RtlpValidateHeap(Heap
, TRUE
);
3729 HeapValid
= RtlpValidateHeapEntry(Heap
, (PHEAP_ENTRY
)Block
- 1);
3731 /* Unlock if it's lockable */
3734 RtlLeaveHeapLock(Heap
->LockVariable
);
3741 RtlInitializeHeapManager(VOID
)
3746 Peb
= RtlGetCurrentPeb();
3748 /* Initialize heap-related fields of PEB */
3749 Peb
->NumberOfHeaps
= 0;
3751 /* Initialize the process heaps list protecting lock */
3752 RtlInitializeHeapLock(&RtlpProcessHeapsListLock
);
3760 RtlEnumProcessHeaps(PHEAP_ENUMERATION_ROUTINE HeapEnumerationRoutine
,
3764 return STATUS_NOT_IMPLEMENTED
;
3772 RtlGetProcessHeaps(ULONG count
,
3784 RtlValidateProcessHeaps(VOID
)
3796 IN PVOID HeapHandle
,
3809 RtlSetUserValueHeap(IN PVOID HeapHandle
,
3811 IN PVOID BaseAddress
,
3814 PHEAP Heap
= (PHEAP
)HeapHandle
;
3815 PHEAP_ENTRY HeapEntry
;
3816 PHEAP_ENTRY_EXTRA Extra
;
3817 BOOLEAN HeapLocked
= FALSE
;
3820 Flags
|= Heap
->Flags
;
3822 /* Call special heap */
3823 if (RtlpHeapIsSpecial(Flags
))
3824 return RtlDebugSetUserValueHeap(Heap
, Flags
, BaseAddress
, UserValue
);
3826 /* Lock if it's lockable */
3827 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
3829 RtlEnterHeapLock(Heap
->LockVariable
);
3833 /* Get a pointer to the entry */
3834 HeapEntry
= (PHEAP_ENTRY
)BaseAddress
- 1;
3836 /* If it's a free entry - return error */
3837 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
))
3839 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
3841 /* Release the heap lock if it was acquired */
3843 RtlLeaveHeapLock(Heap
->LockVariable
);
3848 /* Check if this entry has an extra stuff associated with it */
3849 if (HeapEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
3851 /* Use extra to store the value */
3852 Extra
= RtlpGetExtraStuffPointer(HeapEntry
);
3853 Extra
->Settable
= (ULONG_PTR
)UserValue
;
3856 /* Release the heap lock if it was acquired */
3858 RtlLeaveHeapLock(Heap
->LockVariable
);
3868 RtlSetUserFlagsHeap(IN PVOID HeapHandle
,
3870 IN PVOID BaseAddress
,
3871 IN ULONG UserFlagsReset
,
3872 IN ULONG UserFlagsSet
)
3874 PHEAP Heap
= (PHEAP
)HeapHandle
;
3875 PHEAP_ENTRY HeapEntry
;
3876 BOOLEAN HeapLocked
= FALSE
;
3879 Flags
|= Heap
->Flags
;
3881 /* Call special heap */
3882 if (RtlpHeapIsSpecial(Flags
))
3883 return RtlDebugSetUserFlagsHeap(Heap
, Flags
, BaseAddress
, UserFlagsReset
, UserFlagsSet
);
3885 /* Lock if it's lockable */
3886 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
3888 RtlEnterHeapLock(Heap
->LockVariable
);
3892 /* Get a pointer to the entry */
3893 HeapEntry
= (PHEAP_ENTRY
)BaseAddress
- 1;
3895 /* If it's a free entry - return error */
3896 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
))
3898 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
3900 /* Release the heap lock if it was acquired */
3902 RtlLeaveHeapLock(Heap
->LockVariable
);
3907 /* Set / reset flags */
3908 HeapEntry
->Flags
&= ~(UserFlagsReset
>> 4);
3909 HeapEntry
->Flags
|= (UserFlagsSet
>> 4);
3911 /* Release the heap lock if it was acquired */
3913 RtlLeaveHeapLock(Heap
->LockVariable
);
3923 RtlGetUserInfoHeap(IN PVOID HeapHandle
,
3925 IN PVOID BaseAddress
,
3926 OUT PVOID
*UserValue
,
3927 OUT PULONG UserFlags
)
3929 PHEAP Heap
= (PHEAP
)HeapHandle
;
3930 PHEAP_ENTRY HeapEntry
;
3931 PHEAP_ENTRY_EXTRA Extra
;
3932 BOOLEAN HeapLocked
= FALSE
;
3935 Flags
|= Heap
->Flags
;
3937 /* Call special heap */
3938 if (RtlpHeapIsSpecial(Flags
))
3939 return RtlDebugGetUserInfoHeap(Heap
, Flags
, BaseAddress
, UserValue
, UserFlags
);
3941 /* Lock if it's lockable */
3942 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
3944 RtlEnterHeapLock(Heap
->LockVariable
);
3948 /* Get a pointer to the entry */
3949 HeapEntry
= (PHEAP_ENTRY
)BaseAddress
- 1;
3951 /* If it's a free entry - return error */
3952 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
))
3954 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
3956 /* Release the heap lock if it was acquired */
3958 RtlLeaveHeapLock(Heap
->LockVariable
);
3963 /* Check if this entry has an extra stuff associated with it */
3964 if (HeapEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
3966 /* Get pointer to extra data */
3967 Extra
= RtlpGetExtraStuffPointer(HeapEntry
);
3969 /* Pass user value */
3971 *UserValue
= (PVOID
)Extra
->Settable
;
3973 /* Decode and return user flags */
3975 *UserFlags
= (HeapEntry
->Flags
& HEAP_ENTRY_SETTABLE_FLAGS
) << 4;
3978 /* Release the heap lock if it was acquired */
3980 RtlLeaveHeapLock(Heap
->LockVariable
);
3990 RtlUsageHeap(IN HANDLE Heap
,
3992 OUT PRTL_HEAP_USAGE Usage
)
3996 return STATUS_NOT_IMPLEMENTED
;
4001 RtlQueryTagHeap(IN PVOID HeapHandle
,
4004 IN BOOLEAN ResetCounters
,
4005 OUT PRTL_HEAP_TAG_INFO HeapTagInfo
)
4014 RtlExtendHeap(IN HANDLE Heap
,
4026 RtlCreateTagHeap(IN HANDLE HeapHandle
,
4029 IN PWSTR TagSubName
)
4038 RtlWalkHeap(IN HANDLE HeapHandle
,
4042 return STATUS_NOT_IMPLEMENTED
;
4047 RtlProtectHeap(IN PVOID HeapHandle
,
4048 IN BOOLEAN ReadOnly
)
4056 RtlSetHeapInformation(IN HANDLE HeapHandle OPTIONAL
,
4057 IN HEAP_INFORMATION_CLASS HeapInformationClass
,
4058 IN PVOID HeapInformation
,
4059 IN SIZE_T HeapInformationLength
)
4061 /* Setting heap information is not really supported except for enabling LFH */
4062 if (HeapInformationClass
== 0) return STATUS_SUCCESS
;
4064 /* Check buffer length */
4065 if (HeapInformationLength
< sizeof(ULONG
))
4067 /* The provided buffer is too small */
4068 return STATUS_BUFFER_TOO_SMALL
;
4071 /* Check for a special magic value for enabling LFH */
4072 if (*(PULONG
)HeapInformation
== 2)
4074 DPRINT1("RtlSetHeapInformation() needs to enable LFH\n");
4075 return STATUS_SUCCESS
;
4078 return STATUS_UNSUCCESSFUL
;
4083 RtlQueryHeapInformation(HANDLE HeapHandle
,
4084 HEAP_INFORMATION_CLASS HeapInformationClass
,
4085 PVOID HeapInformation OPTIONAL
,
4086 SIZE_T HeapInformationLength OPTIONAL
,
4087 PSIZE_T ReturnLength OPTIONAL
)
4089 PHEAP Heap
= (PHEAP
)HeapHandle
;
4091 /* Only HeapCompatibilityInformation is supported */
4092 if (HeapInformationClass
!= HeapCompatibilityInformation
)
4093 return STATUS_UNSUCCESSFUL
;
4095 /* Set result length */
4096 if (ReturnLength
) *ReturnLength
= sizeof(ULONG
);
4098 /* Check buffer length */
4099 if (HeapInformationLength
< sizeof(ULONG
))
4101 /* It's too small, return needed length */
4102 return STATUS_BUFFER_TOO_SMALL
;
4105 /* Return front end heap type */
4106 *(PULONG
)HeapInformation
= Heap
->FrontEndHeapType
;
4108 return STATUS_SUCCESS
;
4113 RtlMultipleAllocateHeap(IN PVOID HeapHandle
,
4125 RtlMultipleFreeHeap(IN PVOID HeapHandle
,