2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS system libraries
5 * PURPOSE: RTL Heap backend allocator
6 * PROGRAMMERS: Copyright 2010 Aleksey Bragin
10 http://msdn.microsoft.com/en-us/library/ms810466.aspx
11 http://msdn.microsoft.com/en-us/library/ms810603.aspx
12 http://www.securitylab.ru/analytics/216376.php
13 http://binglongx.spaces.live.com/blog/cns!142CBF6D49079DE8!596.entry
14 http://www.phreedom.org/research/exploits/asn1-bitstring/
15 http://illmatics.com/Understanding_the_LFH.pdf
16 http://www.alex-ionescu.com/?p=18
19 /* INCLUDES *****************************************************************/
29 /* How many least significant bits are clear */
30 UCHAR RtlpBitsClearLow
[] =
32 8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
33 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
34 5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
35 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
36 6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
37 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
38 5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
39 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
40 7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
41 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
42 5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
43 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
44 6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
45 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
46 5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,
47 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
] =
83 /* FUNCTIONS *****************************************************************/
86 RtlpInitializeHeap(OUT PHEAP Heap
,
88 IN PHEAP_LOCK Lock OPTIONAL
,
89 IN PRTL_HEAP_PARAMETERS Parameters
)
95 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
99 ASSERT(Parameters
!= NULL
);
100 ASSERT(!(Flags
& HEAP_LOCK_USER_ALLOCATED
));
101 ASSERT(!(Flags
& HEAP_NO_SERIALIZE
) || (Lock
== NULL
)); /* HEAP_NO_SERIALIZE => no lock */
103 /* Start out with the size of a plain Heap header */
104 HeaderSize
= ROUND_UP(sizeof(HEAP
), sizeof(HEAP_ENTRY
));
106 /* Check if space needs to be added for the Heap Lock */
107 if (!(Flags
& HEAP_NO_SERIALIZE
))
110 /* The user manages the Heap Lock */
111 Flags
|= HEAP_LOCK_USER_ALLOCATED
;
113 if (RtlpGetMode() == UserMode
)
115 /* In user mode, the Heap Lock trails the Heap header */
116 Lock
= (PHEAP_LOCK
) ((ULONG_PTR
) (Heap
) + HeaderSize
);
117 HeaderSize
+= ROUND_UP(sizeof(HEAP_LOCK
), sizeof(HEAP_ENTRY
));
121 /* Add space for the initial Heap UnCommitted Range Descriptor list */
122 UcrDescriptor
= (PHEAP_UCR_DESCRIPTOR
) ((ULONG_PTR
) (Heap
) + HeaderSize
);
123 HeaderSize
+= ROUND_UP(NumUCRs
* sizeof(HEAP_UCR_DESCRIPTOR
), sizeof(HEAP_ENTRY
));
126 ASSERT(HeaderSize
<= PAGE_SIZE
);
128 /* Initialise the Heap Entry header containing the Heap header */
129 Heap
->Entry
.Size
= (USHORT
)(HeaderSize
>> HEAP_ENTRY_SHIFT
);
130 Heap
->Entry
.Flags
= HEAP_ENTRY_BUSY
;
131 Heap
->Entry
.SmallTagIndex
= LOBYTE(Heap
->Entry
.Size
) ^ HIBYTE(Heap
->Entry
.Size
) ^ Heap
->Entry
.Flags
;
132 Heap
->Entry
.PreviousSize
= 0;
133 Heap
->Entry
.SegmentOffset
= 0;
134 Heap
->Entry
.UnusedBytes
= 0;
136 /* Initialise the Heap header */
137 Heap
->Signature
= HEAP_SIGNATURE
;
139 Heap
->ForceFlags
= (Flags
& (HEAP_NO_SERIALIZE
|
140 HEAP_GENERATE_EXCEPTIONS
|
142 HEAP_REALLOC_IN_PLACE_ONLY
|
143 HEAP_VALIDATE_PARAMETERS_ENABLED
|
144 HEAP_VALIDATE_ALL_ENABLED
|
145 HEAP_TAIL_CHECKING_ENABLED
|
146 HEAP_CREATE_ALIGN_16
|
147 HEAP_FREE_CHECKING_ENABLED
));
149 /* Initialise the Heap parameters */
150 Heap
->VirtualMemoryThreshold
= ROUND_UP(Parameters
->VirtualMemoryThreshold
, sizeof(HEAP_ENTRY
)) >> HEAP_ENTRY_SHIFT
;
151 Heap
->SegmentReserve
= Parameters
->SegmentReserve
;
152 Heap
->SegmentCommit
= Parameters
->SegmentCommit
;
153 Heap
->DeCommitFreeBlockThreshold
= Parameters
->DeCommitFreeBlockThreshold
>> HEAP_ENTRY_SHIFT
;
154 Heap
->DeCommitTotalFreeThreshold
= Parameters
->DeCommitTotalFreeThreshold
>> HEAP_ENTRY_SHIFT
;
155 Heap
->MaximumAllocationSize
= Parameters
->MaximumAllocationSize
;
156 Heap
->CommitRoutine
= Parameters
->CommitRoutine
;
158 /* Initialise the Heap validation info */
159 Heap
->HeaderValidateCopy
= NULL
;
160 Heap
->HeaderValidateLength
= (USHORT
)HeaderSize
;
162 /* Initialise the Heap Lock */
163 if (!(Flags
& HEAP_NO_SERIALIZE
) && !(Flags
& HEAP_LOCK_USER_ALLOCATED
))
165 Status
= RtlInitializeHeapLock(&Lock
);
166 if (!NT_SUCCESS(Status
))
169 Heap
->LockVariable
= Lock
;
171 /* Initialise the Heap alignment info */
172 if (Flags
& HEAP_CREATE_ALIGN_16
)
174 Heap
->AlignMask
= (ULONG
) ~15;
175 Heap
->AlignRound
= 15 + sizeof(HEAP_ENTRY
);
179 Heap
->AlignMask
= (ULONG
) ~(sizeof(HEAP_ENTRY
) - 1);
180 Heap
->AlignRound
= 2 * sizeof(HEAP_ENTRY
) - 1;
183 if (Flags
& HEAP_TAIL_CHECKING_ENABLED
)
184 Heap
->AlignRound
+= sizeof(HEAP_ENTRY
);
186 /* Initialise the Heap Segment list */
187 for (Index
= 0; Index
< HEAP_SEGMENTS
; ++Index
)
188 Heap
->Segments
[Index
] = NULL
;
190 /* Initialise the Heap Free Heap Entry lists */
191 for (Index
= 0; Index
< HEAP_FREELISTS
; ++Index
)
192 InitializeListHead(&Heap
->FreeLists
[Index
]);
194 /* Initialise the Heap Virtual Allocated Blocks list */
195 InitializeListHead(&Heap
->VirtualAllocdBlocks
);
197 /* Initialise the Heap UnCommitted Region lists */
198 InitializeListHead(&Heap
->UCRSegments
);
199 InitializeListHead(&Heap
->UCRList
);
201 /* Register the initial Heap UnCommitted Region Descriptors */
202 for (Index
= 0; Index
< NumUCRs
; ++Index
)
203 InsertTailList(&Heap
->UCRList
, &UcrDescriptor
[Index
].ListEntry
);
205 return STATUS_SUCCESS
;
210 RtlpSetFreeListsBit(PHEAP Heap
,
211 PHEAP_FREE_ENTRY FreeEntry
)
215 ASSERT(FreeEntry
->Size
< HEAP_FREELISTS
);
217 /* Calculate offset in the free list bitmap */
218 Index
= FreeEntry
->Size
>> 3; /* = FreeEntry->Size / (sizeof(UCHAR) * 8)*/
219 Bit
= 1 << (FreeEntry
->Size
& 7);
221 /* Assure it's not already set */
222 ASSERT((Heap
->u
.FreeListsInUseBytes
[Index
] & Bit
) == 0);
225 Heap
->u
.FreeListsInUseBytes
[Index
] |= Bit
;
230 RtlpClearFreeListsBit(PHEAP Heap
,
231 PHEAP_FREE_ENTRY FreeEntry
)
235 ASSERT(FreeEntry
->Size
< HEAP_FREELISTS
);
237 /* Calculate offset in the free list bitmap */
238 Index
= FreeEntry
->Size
>> 3; /* = FreeEntry->Size / (sizeof(UCHAR) * 8)*/
239 Bit
= 1 << (FreeEntry
->Size
& 7);
241 /* Assure it was set and the corresponding free list is empty */
242 ASSERT(Heap
->u
.FreeListsInUseBytes
[Index
] & Bit
);
243 ASSERT(IsListEmpty(&Heap
->FreeLists
[FreeEntry
->Size
]));
246 Heap
->u
.FreeListsInUseBytes
[Index
] ^= Bit
;
250 RtlpInsertFreeBlockHelper(PHEAP Heap
,
251 PHEAP_FREE_ENTRY FreeEntry
,
255 PLIST_ENTRY FreeListHead
, Current
;
256 PHEAP_FREE_ENTRY CurrentEntry
;
258 ASSERT(FreeEntry
->Size
== BlockSize
);
260 /* Fill if it's not denied */
263 FreeEntry
->Flags
&= ~(HEAP_ENTRY_FILL_PATTERN
|
264 HEAP_ENTRY_EXTRA_PRESENT
|
267 if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
269 RtlFillMemoryUlong((PCHAR
)(FreeEntry
+ 1),
270 (BlockSize
<< HEAP_ENTRY_SHIFT
) - sizeof(*FreeEntry
),
273 FreeEntry
->Flags
|= HEAP_ENTRY_FILL_PATTERN
;
278 /* Clear out all flags except the last entry one */
279 FreeEntry
->Flags
&= HEAP_ENTRY_LAST_ENTRY
;
282 /* Insert it either into dedicated or non-dedicated list */
283 if (BlockSize
< HEAP_FREELISTS
)
286 FreeListHead
= &Heap
->FreeLists
[BlockSize
];
288 if (IsListEmpty(FreeListHead
))
290 RtlpSetFreeListsBit(Heap
, FreeEntry
);
295 /* Non-dedicated one */
296 FreeListHead
= &Heap
->FreeLists
[0];
297 Current
= FreeListHead
->Flink
;
299 /* Find a position where to insert it to (the list must be sorted) */
300 while (FreeListHead
!= Current
)
302 CurrentEntry
= CONTAINING_RECORD(Current
, HEAP_FREE_ENTRY
, FreeList
);
304 if (BlockSize
<= CurrentEntry
->Size
)
307 Current
= Current
->Flink
;
310 FreeListHead
= Current
;
313 /* Actually insert it into the list */
314 InsertTailList(FreeListHead
, &FreeEntry
->FreeList
);
318 RtlpInsertFreeBlock(PHEAP Heap
,
319 PHEAP_FREE_ENTRY FreeEntry
,
322 USHORT Size
, PreviousSize
;
323 UCHAR SegmentOffset
, Flags
;
324 PHEAP_SEGMENT Segment
;
326 DPRINT("RtlpInsertFreeBlock(%p %p %x)\n", Heap
, FreeEntry
, BlockSize
);
328 /* Increase the free size counter */
329 Heap
->TotalFreeSize
+= BlockSize
;
331 /* Remember certain values */
332 Flags
= FreeEntry
->Flags
;
333 PreviousSize
= FreeEntry
->PreviousSize
;
334 SegmentOffset
= FreeEntry
->SegmentOffset
;
335 Segment
= Heap
->Segments
[SegmentOffset
];
340 /* Check for the max size */
341 if (BlockSize
> HEAP_MAX_BLOCK_SIZE
)
343 Size
= HEAP_MAX_BLOCK_SIZE
;
345 /* Special compensation if it goes above limit just by 1 */
346 if (BlockSize
== (HEAP_MAX_BLOCK_SIZE
+ 1))
349 FreeEntry
->Flags
= 0;
353 Size
= (USHORT
)BlockSize
;
354 FreeEntry
->Flags
= Flags
;
357 /* Change its size and insert it into a free list */
358 FreeEntry
->Size
= Size
;
359 FreeEntry
->PreviousSize
= PreviousSize
;
360 FreeEntry
->SegmentOffset
= SegmentOffset
;
362 /* Call a helper to actually insert the block */
363 RtlpInsertFreeBlockHelper(Heap
, FreeEntry
, Size
, FALSE
);
369 /* Go to the next entry */
370 FreeEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)FreeEntry
+ Size
);
372 /* Check if that's all */
373 if ((PHEAP_ENTRY
)FreeEntry
>= Segment
->LastValidEntry
) return;
376 /* Update previous size if needed */
377 if (!(Flags
& HEAP_ENTRY_LAST_ENTRY
))
378 FreeEntry
->PreviousSize
= PreviousSize
;
382 RtlpRemoveFreeBlock(PHEAP Heap
,
383 PHEAP_FREE_ENTRY FreeEntry
,
387 SIZE_T Result
, RealSize
;
389 /* Remove the free block and update the freelists bitmap */
390 if (RemoveEntryList(&FreeEntry
->FreeList
) &&
391 (Dedicated
|| (!Dedicated
&& FreeEntry
->Size
< HEAP_FREELISTS
)))
393 RtlpClearFreeListsBit(Heap
, FreeEntry
);
396 /* Fill with pattern if necessary */
398 (FreeEntry
->Flags
& HEAP_ENTRY_FILL_PATTERN
))
400 RealSize
= (FreeEntry
->Size
<< HEAP_ENTRY_SHIFT
) - sizeof(*FreeEntry
);
402 /* Deduct extra stuff from block's real size */
403 if (FreeEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
&&
404 RealSize
> sizeof(HEAP_FREE_ENTRY_EXTRA
))
406 RealSize
-= sizeof(HEAP_FREE_ENTRY_EXTRA
);
409 /* Check if the free filler is intact */
410 Result
= RtlCompareMemoryUlong((PCHAR
)(FreeEntry
+ 1),
414 if (Result
!= RealSize
)
416 DPRINT1("Free heap block %p modified at %p after it was freed\n",
418 (PCHAR
)(FreeEntry
+ 1) + Result
);
424 RtlpGetSizeOfBigBlock(PHEAP_ENTRY HeapEntry
)
426 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry
;
428 /* Get pointer to the containing record */
429 VirtualEntry
= CONTAINING_RECORD(HeapEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
430 ASSERT(VirtualEntry
->BusyBlock
.Size
>= sizeof(HEAP_VIRTUAL_ALLOC_ENTRY
));
432 /* Restore the real size */
433 return VirtualEntry
->CommitSize
- HeapEntry
->Size
;
436 PHEAP_UCR_DESCRIPTOR NTAPI
437 RtlpCreateUnCommittedRange(PHEAP_SEGMENT Segment
)
440 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
441 PHEAP_UCR_SEGMENT UcrSegment
;
442 PHEAP Heap
= Segment
->Heap
;
443 SIZE_T ReserveSize
= 16 * PAGE_SIZE
;
444 SIZE_T CommitSize
= 1 * PAGE_SIZE
;
447 DPRINT("RtlpCreateUnCommittedRange(%p)\n", Segment
);
449 /* Check if we have unused UCRs */
450 if (IsListEmpty(&Heap
->UCRList
))
452 /* Get a pointer to the first UCR segment */
453 UcrSegment
= CONTAINING_RECORD(Heap
->UCRSegments
.Flink
, HEAP_UCR_SEGMENT
, ListEntry
);
455 /* Check the list of UCR segments */
456 if (IsListEmpty(&Heap
->UCRSegments
) ||
457 UcrSegment
->ReservedSize
== UcrSegment
->CommittedSize
)
459 /* We need to create a new one. Reserve 16 pages for it */
461 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
462 (PVOID
*)&UcrSegment
,
468 if (!NT_SUCCESS(Status
)) return NULL
;
470 /* Commit one page */
471 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
472 (PVOID
*)&UcrSegment
,
478 if (!NT_SUCCESS(Status
))
480 /* Release reserved memory */
481 ZwFreeVirtualMemory(NtCurrentProcess(),
482 (PVOID
*)&UcrSegment
,
489 UcrSegment
->ReservedSize
= ReserveSize
;
490 UcrSegment
->CommittedSize
= CommitSize
;
492 /* Add it to the head of the list */
493 InsertHeadList(&Heap
->UCRSegments
, &UcrSegment
->ListEntry
);
495 /* Get a pointer to the first available UCR descriptor */
496 UcrDescriptor
= (PHEAP_UCR_DESCRIPTOR
)(UcrSegment
+ 1);
500 /* It's possible to use existing UCR segment. Commit one more page */
501 UcrDescriptor
= (PHEAP_UCR_DESCRIPTOR
)((PCHAR
)UcrSegment
+ UcrSegment
->CommittedSize
);
502 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
503 (PVOID
*)&UcrDescriptor
,
509 if (!NT_SUCCESS(Status
)) return NULL
;
512 UcrSegment
->CommittedSize
+= CommitSize
;
515 /* There is a whole bunch of new UCR descriptors. Put them into the unused list */
516 while ((PCHAR
)(UcrDescriptor
+ 1) <= (PCHAR
)UcrSegment
+ UcrSegment
->CommittedSize
)
518 InsertTailList(&Heap
->UCRList
, &UcrDescriptor
->ListEntry
);
523 /* There are unused UCRs, just get the first one */
524 Entry
= RemoveHeadList(&Heap
->UCRList
);
525 UcrDescriptor
= CONTAINING_RECORD(Entry
, HEAP_UCR_DESCRIPTOR
, ListEntry
);
526 return UcrDescriptor
;
530 RtlpDestroyUnCommittedRange(PHEAP_SEGMENT Segment
,
531 PHEAP_UCR_DESCRIPTOR UcrDescriptor
)
534 UcrDescriptor
->Address
= NULL
;
535 UcrDescriptor
->Size
= 0;
537 /* Put it into the heap's list of unused UCRs */
538 InsertHeadList(&Segment
->Heap
->UCRList
, &UcrDescriptor
->ListEntry
);
542 RtlpInsertUnCommittedPages(PHEAP_SEGMENT Segment
,
547 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
549 DPRINT("RtlpInsertUnCommittedPages(%p %08Ix %Ix)\n", Segment
, Address
, Size
);
551 /* Go through the list of UCR descriptors, they are sorted from lowest address
553 Current
= Segment
->UCRSegmentList
.Flink
;
554 while (Current
!= &Segment
->UCRSegmentList
)
556 UcrDescriptor
= CONTAINING_RECORD(Current
, HEAP_UCR_DESCRIPTOR
, SegmentEntry
);
558 if ((ULONG_PTR
)UcrDescriptor
->Address
> Address
)
560 /* Check for a really lucky case */
561 if ((Address
+ Size
) == (ULONG_PTR
)UcrDescriptor
->Address
)
564 UcrDescriptor
->Address
= (PVOID
)Address
;
565 UcrDescriptor
->Size
+= Size
;
569 /* We found the block before which the new one should go */
572 else if (((ULONG_PTR
)UcrDescriptor
->Address
+ UcrDescriptor
->Size
) == Address
)
574 /* Modify this entry */
575 Address
= (ULONG_PTR
)UcrDescriptor
->Address
;
576 Size
+= UcrDescriptor
->Size
;
578 /* Advance to the next descriptor */
579 Current
= Current
->Flink
;
581 /* Remove the current descriptor from the list and destroy it */
582 RemoveEntryList(&UcrDescriptor
->SegmentEntry
);
583 RtlpDestroyUnCommittedRange(Segment
, UcrDescriptor
);
585 Segment
->NumberOfUnCommittedRanges
--;
589 /* Advance to the next descriptor */
590 Current
= Current
->Flink
;
594 /* Create a new UCR descriptor */
595 UcrDescriptor
= RtlpCreateUnCommittedRange(Segment
);
596 if (!UcrDescriptor
) return;
598 UcrDescriptor
->Address
= (PVOID
)Address
;
599 UcrDescriptor
->Size
= Size
;
601 /* "Current" is the descriptor before which our one should go */
602 InsertTailList(Current
, &UcrDescriptor
->SegmentEntry
);
604 DPRINT("Added segment UCR with base %08Ix, size 0x%x\n", Address
, Size
);
606 /* Increase counters */
607 Segment
->NumberOfUnCommittedRanges
++;
610 PHEAP_FREE_ENTRY NTAPI
611 RtlpFindAndCommitPages(PHEAP Heap
,
612 PHEAP_SEGMENT Segment
,
614 PVOID AddressRequested
)
617 ULONG_PTR Address
= 0;
618 PHEAP_UCR_DESCRIPTOR UcrDescriptor
, PreviousUcr
= NULL
;
619 PHEAP_ENTRY FirstEntry
, LastEntry
;
622 DPRINT("RtlpFindAndCommitPages(%p %p %Ix %08Ix)\n", Heap
, Segment
, *Size
, Address
);
624 /* Go through UCRs in a segment */
625 Current
= Segment
->UCRSegmentList
.Flink
;
626 while (Current
!= &Segment
->UCRSegmentList
)
628 UcrDescriptor
= CONTAINING_RECORD(Current
, HEAP_UCR_DESCRIPTOR
, SegmentEntry
);
630 /* Check if we can use that one right away */
631 if (UcrDescriptor
->Size
>= *Size
&&
632 (UcrDescriptor
->Address
== AddressRequested
|| !AddressRequested
))
634 /* Get the address */
635 Address
= (ULONG_PTR
)UcrDescriptor
->Address
;
638 if (Heap
->CommitRoutine
)
640 Status
= Heap
->CommitRoutine(Heap
, (PVOID
*)&Address
, Size
);
644 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
652 DPRINT("Committed %Iu bytes at base %08Ix, UCR size is %lu\n", *Size
, Address
, UcrDescriptor
->Size
);
654 /* Fail in unsuccessful case */
655 if (!NT_SUCCESS(Status
))
657 DPRINT1("Committing page failed with status 0x%08X\n", Status
);
661 /* Update tracking numbers */
662 Segment
->NumberOfUnCommittedPages
-= (ULONG
)(*Size
/ PAGE_SIZE
);
664 /* Calculate first and last entries */
665 FirstEntry
= (PHEAP_ENTRY
)Address
;
667 /* Go through the entries to find the last one */
669 LastEntry
= (PHEAP_ENTRY
)((ULONG_PTR
)PreviousUcr
->Address
+ PreviousUcr
->Size
);
671 LastEntry
= &Segment
->Entry
;
673 while (!(LastEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
675 ASSERT(LastEntry
->Size
!= 0);
676 LastEntry
+= LastEntry
->Size
;
678 ASSERT((LastEntry
+ LastEntry
->Size
) == FirstEntry
);
680 /* Unmark it as a last entry */
681 LastEntry
->Flags
&= ~HEAP_ENTRY_LAST_ENTRY
;
683 /* Update UCR descriptor */
684 UcrDescriptor
->Address
= (PVOID
)((ULONG_PTR
)UcrDescriptor
->Address
+ *Size
);
685 UcrDescriptor
->Size
-= *Size
;
687 DPRINT("Updating UcrDescriptor %p, new Address %p, size %lu\n",
688 UcrDescriptor
, UcrDescriptor
->Address
, UcrDescriptor
->Size
);
690 /* Set various first entry fields */
691 FirstEntry
->SegmentOffset
= LastEntry
->SegmentOffset
;
692 FirstEntry
->Size
= (USHORT
)(*Size
>> HEAP_ENTRY_SHIFT
);
693 FirstEntry
->PreviousSize
= LastEntry
->Size
;
695 /* Check if anything left in this UCR */
696 if (UcrDescriptor
->Size
== 0)
698 /* It's fully exhausted */
700 /* Check if this is the end of the segment */
701 if(UcrDescriptor
->Address
== Segment
->LastValidEntry
)
703 FirstEntry
->Flags
= HEAP_ENTRY_LAST_ENTRY
;
707 FirstEntry
->Flags
= 0;
708 /* Update field of next entry */
709 ASSERT((FirstEntry
+ FirstEntry
->Size
)->PreviousSize
== 0);
710 (FirstEntry
+ FirstEntry
->Size
)->PreviousSize
= FirstEntry
->Size
;
713 /* This UCR needs to be removed because it became useless */
714 RemoveEntryList(&UcrDescriptor
->SegmentEntry
);
716 RtlpDestroyUnCommittedRange(Segment
, UcrDescriptor
);
717 Segment
->NumberOfUnCommittedRanges
--;
721 FirstEntry
->Flags
= HEAP_ENTRY_LAST_ENTRY
;
725 return (PHEAP_FREE_ENTRY
)FirstEntry
;
728 /* Advance to the next descriptor */
729 PreviousUcr
= UcrDescriptor
;
730 Current
= Current
->Flink
;
737 RtlpDeCommitFreeBlock(PHEAP Heap
,
738 PHEAP_FREE_ENTRY FreeEntry
,
741 PHEAP_SEGMENT Segment
;
742 PHEAP_ENTRY PrecedingInUseEntry
= NULL
, NextInUseEntry
= NULL
;
743 PHEAP_FREE_ENTRY NextFreeEntry
;
744 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
745 SIZE_T PrecedingSize
, NextSize
, DecommitSize
;
746 ULONG_PTR DecommitBase
;
749 DPRINT("Decommitting %p %p %x\n", Heap
, FreeEntry
, Size
);
751 /* We can't decommit if there is a commit routine! */
752 if (Heap
->CommitRoutine
)
754 /* Just add it back the usual way */
755 RtlpInsertFreeBlock(Heap
, FreeEntry
, Size
);
759 /* Get the segment */
760 Segment
= Heap
->Segments
[FreeEntry
->SegmentOffset
];
762 /* Get the preceding entry */
763 DecommitBase
= ROUND_UP(FreeEntry
, PAGE_SIZE
);
764 PrecedingSize
= (PHEAP_ENTRY
)DecommitBase
- (PHEAP_ENTRY
)FreeEntry
;
766 if (PrecedingSize
== 1)
768 /* Just 1 heap entry, increase the base/size */
769 DecommitBase
+= PAGE_SIZE
;
770 PrecedingSize
+= PAGE_SIZE
>> HEAP_ENTRY_SHIFT
;
772 else if (FreeEntry
->PreviousSize
&&
773 (DecommitBase
== (ULONG_PTR
)FreeEntry
))
775 PrecedingInUseEntry
= (PHEAP_ENTRY
)FreeEntry
- FreeEntry
->PreviousSize
;
778 /* Get the next entry */
779 NextFreeEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)FreeEntry
+ Size
);
780 DecommitSize
= ROUND_DOWN(NextFreeEntry
, PAGE_SIZE
);
781 NextSize
= (PHEAP_ENTRY
)NextFreeEntry
- (PHEAP_ENTRY
)DecommitSize
;
785 /* Just 1 heap entry, increase the size */
786 DecommitSize
-= PAGE_SIZE
;
787 NextSize
+= PAGE_SIZE
>> HEAP_ENTRY_SHIFT
;
789 else if (NextSize
== 0 &&
790 !(FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
792 NextInUseEntry
= (PHEAP_ENTRY
)NextFreeEntry
;
795 NextFreeEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)NextFreeEntry
- NextSize
);
797 /* Calculate real decommit size */
798 if (DecommitSize
> DecommitBase
)
800 DecommitSize
-= DecommitBase
;
804 /* Nothing to decommit */
805 RtlpInsertFreeBlock(Heap
, FreeEntry
, Size
);
809 /* A decommit is necessary. Create a UCR descriptor */
810 UcrDescriptor
= RtlpCreateUnCommittedRange(Segment
);
813 DPRINT1("HEAP: Failed to create UCR descriptor\n");
814 RtlpInsertFreeBlock(Heap
, FreeEntry
, PrecedingSize
);
818 /* Decommit the memory */
819 Status
= ZwFreeVirtualMemory(NtCurrentProcess(),
820 (PVOID
*)&DecommitBase
,
824 /* Delete that UCR. This is needed to assure there is an unused UCR entry in the list */
825 RtlpDestroyUnCommittedRange(Segment
, UcrDescriptor
);
827 if (!NT_SUCCESS(Status
))
829 RtlpInsertFreeBlock(Heap
, FreeEntry
, Size
);
833 /* Insert uncommitted pages */
834 RtlpInsertUnCommittedPages(Segment
, DecommitBase
, DecommitSize
);
835 Segment
->NumberOfUnCommittedPages
+= (ULONG
)(DecommitSize
/ PAGE_SIZE
);
839 /* Adjust size of this free entry and insert it */
840 FreeEntry
->Flags
= HEAP_ENTRY_LAST_ENTRY
;
841 FreeEntry
->Size
= (USHORT
)PrecedingSize
;
842 Heap
->TotalFreeSize
+= PrecedingSize
;
844 /* Insert it into the free list */
845 RtlpInsertFreeBlockHelper(Heap
, FreeEntry
, PrecedingSize
, FALSE
);
847 else if (PrecedingInUseEntry
)
849 /* Adjust preceding in use entry */
850 PrecedingInUseEntry
->Flags
|= HEAP_ENTRY_LAST_ENTRY
;
853 /* Now the next one */
856 /* Adjust size of this free entry and insert it */
857 NextFreeEntry
->Flags
= 0;
858 NextFreeEntry
->PreviousSize
= 0;
859 NextFreeEntry
->SegmentOffset
= Segment
->Entry
.SegmentOffset
;
860 NextFreeEntry
->Size
= (USHORT
)NextSize
;
862 ((PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)NextFreeEntry
+ NextSize
))->PreviousSize
= (USHORT
)NextSize
;
864 Heap
->TotalFreeSize
+= NextSize
;
865 RtlpInsertFreeBlockHelper(Heap
, NextFreeEntry
, NextSize
, FALSE
);
867 else if (NextInUseEntry
)
869 NextInUseEntry
->PreviousSize
= 0;
875 RtlpInitializeHeapSegment(IN OUT PHEAP Heap
,
876 OUT PHEAP_SEGMENT Segment
,
877 IN UCHAR SegmentIndex
,
878 IN ULONG SegmentFlags
,
879 IN SIZE_T SegmentReserve
,
880 IN SIZE_T SegmentCommit
)
882 PHEAP_ENTRY HeapEntry
;
885 ASSERT(Heap
!= NULL
);
886 ASSERT(Segment
!= NULL
);
887 ASSERT(SegmentCommit
>= PAGE_SIZE
);
888 ASSERT(ROUND_DOWN(SegmentCommit
, PAGE_SIZE
) == SegmentCommit
);
889 ASSERT(SegmentReserve
>= SegmentCommit
);
890 ASSERT(ROUND_DOWN(SegmentReserve
, PAGE_SIZE
) == SegmentReserve
);
892 DPRINT("RtlpInitializeHeapSegment(%p %p %x %x %lx %lx)\n", Heap
, Segment
, SegmentIndex
, SegmentFlags
, SegmentReserve
, SegmentCommit
);
894 /* Initialise the Heap Entry header if this is not the first Heap Segment */
895 if ((PHEAP_SEGMENT
) (Heap
) != Segment
)
897 Segment
->Entry
.Size
= ROUND_UP(sizeof(HEAP_SEGMENT
), sizeof(HEAP_ENTRY
)) >> HEAP_ENTRY_SHIFT
;
898 Segment
->Entry
.Flags
= HEAP_ENTRY_BUSY
;
899 Segment
->Entry
.SmallTagIndex
= LOBYTE(Segment
->Entry
.Size
) ^ HIBYTE(Segment
->Entry
.Size
) ^ Segment
->Entry
.Flags
;
900 Segment
->Entry
.PreviousSize
= 0;
901 Segment
->Entry
.SegmentOffset
= SegmentIndex
;
902 Segment
->Entry
.UnusedBytes
= 0;
906 ASSERT((Segment
->Entry
.Size
<< HEAP_ENTRY_SHIFT
) <= PAGE_SIZE
);
908 /* Initialise the Heap Segment header */
909 Segment
->SegmentSignature
= HEAP_SEGMENT_SIGNATURE
;
910 Segment
->SegmentFlags
= SegmentFlags
;
911 Segment
->Heap
= Heap
;
912 Heap
->Segments
[SegmentIndex
] = Segment
;
914 /* Initialise the Heap Segment location information */
915 Segment
->BaseAddress
= Segment
;
916 Segment
->NumberOfPages
= (ULONG
)(SegmentReserve
>> PAGE_SHIFT
);
918 /* Initialise the Heap Entries contained within the Heap Segment */
919 Segment
->FirstEntry
= &Segment
->Entry
+ Segment
->Entry
.Size
;
920 Segment
->LastValidEntry
= (PHEAP_ENTRY
)((ULONG_PTR
)Segment
+ SegmentReserve
);
922 if (((SIZE_T
)Segment
->Entry
.Size
<< HEAP_ENTRY_SHIFT
) < SegmentCommit
)
924 HeapEntry
= Segment
->FirstEntry
;
926 /* Prepare a Free Heap Entry header */
927 HeapEntry
->Flags
= HEAP_ENTRY_LAST_ENTRY
;
928 HeapEntry
->PreviousSize
= Segment
->Entry
.Size
;
929 HeapEntry
->SegmentOffset
= SegmentIndex
;
931 /* Register the Free Heap Entry */
932 RtlpInsertFreeBlock(Heap
, (PHEAP_FREE_ENTRY
) HeapEntry
, (SegmentCommit
>> HEAP_ENTRY_SHIFT
) - Segment
->Entry
.Size
);
935 /* Initialise the Heap Segment UnCommitted Range information */
936 Segment
->NumberOfUnCommittedPages
= (ULONG
)((SegmentReserve
- SegmentCommit
) >> PAGE_SHIFT
);
937 Segment
->NumberOfUnCommittedRanges
= 0;
938 InitializeListHead(&Segment
->UCRSegmentList
);
940 /* Register the UnCommitted Range of the Heap Segment */
941 if (Segment
->NumberOfUnCommittedPages
!= 0)
942 RtlpInsertUnCommittedPages(Segment
, (ULONG_PTR
) (Segment
) + SegmentCommit
, SegmentReserve
- SegmentCommit
);
944 return STATUS_SUCCESS
;
948 RtlpDestroyHeapSegment(PHEAP_SEGMENT Segment
)
954 /* Make sure it's not user allocated */
955 if (Segment
->SegmentFlags
& HEAP_USER_ALLOCATED
) return;
957 BaseAddress
= Segment
->BaseAddress
;
958 DPRINT("Destroying segment %p, BA %p\n", Segment
, BaseAddress
);
960 /* Release virtual memory */
961 Status
= ZwFreeVirtualMemory(NtCurrentProcess(),
966 if (!NT_SUCCESS(Status
))
968 DPRINT1("HEAP: Failed to release segment's memory with status 0x%08X\n", Status
);
972 PHEAP_FREE_ENTRY NTAPI
973 RtlpCoalesceHeap(PHEAP Heap
)
979 PHEAP_FREE_ENTRY NTAPI
980 RtlpCoalesceFreeBlocks (PHEAP Heap
,
981 PHEAP_FREE_ENTRY FreeEntry
,
985 PHEAP_FREE_ENTRY CurrentEntry
, NextEntry
;
987 /* Get the previous entry */
988 CurrentEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)FreeEntry
- FreeEntry
->PreviousSize
);
991 if (CurrentEntry
!= FreeEntry
&&
992 !(CurrentEntry
->Flags
& HEAP_ENTRY_BUSY
) &&
993 (*FreeSize
+ CurrentEntry
->Size
) <= HEAP_MAX_BLOCK_SIZE
)
995 ASSERT(FreeEntry
->PreviousSize
== CurrentEntry
->Size
);
997 /* Remove it if asked for */
1000 RtlpRemoveFreeBlock(Heap
, FreeEntry
, FALSE
, FALSE
);
1001 Heap
->TotalFreeSize
-= FreeEntry
->Size
;
1003 /* Remove it only once! */
1007 /* Remove previous entry too */
1008 RtlpRemoveFreeBlock(Heap
, CurrentEntry
, FALSE
, FALSE
);
1011 CurrentEntry
->Flags
= FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
;
1013 /* Advance FreeEntry and update sizes */
1014 FreeEntry
= CurrentEntry
;
1015 *FreeSize
= *FreeSize
+ CurrentEntry
->Size
;
1016 Heap
->TotalFreeSize
-= CurrentEntry
->Size
;
1017 FreeEntry
->Size
= (USHORT
)(*FreeSize
);
1019 /* Also update previous size if needed */
1020 if (!(FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
1022 ((PHEAP_ENTRY
)FreeEntry
+ *FreeSize
)->PreviousSize
= (USHORT
)(*FreeSize
);
1026 /* Check the next block if it exists */
1027 if (!(FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
1029 NextEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)FreeEntry
+ *FreeSize
);
1031 if (!(NextEntry
->Flags
& HEAP_ENTRY_BUSY
) &&
1032 NextEntry
->Size
+ *FreeSize
<= HEAP_MAX_BLOCK_SIZE
)
1034 ASSERT(*FreeSize
== NextEntry
->PreviousSize
);
1036 /* Remove it if asked for */
1039 RtlpRemoveFreeBlock(Heap
, FreeEntry
, FALSE
, FALSE
);
1040 Heap
->TotalFreeSize
-= FreeEntry
->Size
;
1044 FreeEntry
->Flags
= NextEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
;
1046 /* Remove next entry now */
1047 RtlpRemoveFreeBlock(Heap
, NextEntry
, FALSE
, FALSE
);
1050 *FreeSize
= *FreeSize
+ NextEntry
->Size
;
1051 Heap
->TotalFreeSize
-= NextEntry
->Size
;
1052 FreeEntry
->Size
= (USHORT
)(*FreeSize
);
1054 /* Also update previous size if needed */
1055 if (!(FreeEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
1057 ((PHEAP_ENTRY
)FreeEntry
+ *FreeSize
)->PreviousSize
= (USHORT
)(*FreeSize
);
1064 PHEAP_FREE_ENTRY NTAPI
1065 RtlpExtendHeap(PHEAP Heap
,
1069 UCHAR Index
, EmptyIndex
;
1070 SIZE_T FreeSize
, CommitSize
, ReserveSize
;
1071 PHEAP_SEGMENT Segment
;
1072 PHEAP_FREE_ENTRY FreeEntry
;
1075 DPRINT("RtlpExtendHeap(%p %x)\n", Heap
, Size
);
1077 /* Calculate amount in pages */
1078 Pages
= (ULONG
)((Size
+ PAGE_SIZE
- 1) / PAGE_SIZE
);
1079 FreeSize
= Pages
* PAGE_SIZE
;
1080 DPRINT("Pages %x, FreeSize %x. Going through segments...\n", Pages
, FreeSize
);
1082 /* Find an empty segment */
1083 EmptyIndex
= HEAP_SEGMENTS
;
1084 for (Index
= 0; Index
< HEAP_SEGMENTS
; Index
++)
1086 Segment
= Heap
->Segments
[Index
];
1088 if (Segment
) DPRINT("Segment[%u] %p with NOUCP %x\n", Index
, Segment
, Segment
->NumberOfUnCommittedPages
);
1090 /* Check if its size suits us */
1092 Pages
<= Segment
->NumberOfUnCommittedPages
)
1094 DPRINT("This segment is suitable\n");
1096 /* Commit needed amount */
1097 FreeEntry
= RtlpFindAndCommitPages(Heap
, Segment
, &FreeSize
, NULL
);
1099 /* Coalesce it with adjacent entries */
1102 FreeSize
= FreeSize
>> HEAP_ENTRY_SHIFT
;
1103 FreeEntry
= RtlpCoalesceFreeBlocks(Heap
, FreeEntry
, &FreeSize
, FALSE
);
1104 RtlpInsertFreeBlock(Heap
, FreeEntry
, FreeSize
);
1108 else if (!Segment
&&
1109 EmptyIndex
== HEAP_SEGMENTS
)
1111 /* Remember the first unused segment index */
1116 /* No luck, need to grow the heap */
1117 if ((Heap
->Flags
& HEAP_GROWABLE
) &&
1118 (EmptyIndex
!= HEAP_SEGMENTS
))
1122 /* Reserve the memory */
1123 if ((Size
+ PAGE_SIZE
) <= Heap
->SegmentReserve
)
1124 ReserveSize
= Heap
->SegmentReserve
;
1126 ReserveSize
= Size
+ PAGE_SIZE
;
1128 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1135 /* If it failed, retry again with a half division algorithm */
1136 while (!NT_SUCCESS(Status
) &&
1137 ReserveSize
!= Size
+ PAGE_SIZE
)
1141 if (ReserveSize
< (Size
+ PAGE_SIZE
))
1142 ReserveSize
= Size
+ PAGE_SIZE
;
1144 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1152 /* Proceed only if it's success */
1153 if (NT_SUCCESS(Status
))
1155 Heap
->SegmentReserve
+= ReserveSize
;
1157 /* Now commit the memory */
1158 if ((Size
+ PAGE_SIZE
) <= Heap
->SegmentCommit
)
1159 CommitSize
= Heap
->SegmentCommit
;
1161 CommitSize
= Size
+ PAGE_SIZE
;
1163 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1170 DPRINT("Committed %lu bytes at base %p\n", CommitSize
, Segment
);
1172 /* Initialize heap segment if commit was successful */
1173 if (NT_SUCCESS(Status
))
1174 Status
= RtlpInitializeHeapSegment(Heap
, Segment
, EmptyIndex
, 0, ReserveSize
, CommitSize
);
1176 /* If everything worked - cool */
1177 if (NT_SUCCESS(Status
)) return (PHEAP_FREE_ENTRY
)Segment
->FirstEntry
;
1179 DPRINT1("Committing failed with status 0x%08X\n", Status
);
1181 /* Nope, we failed. Free memory */
1182 ZwFreeVirtualMemory(NtCurrentProcess(),
1189 DPRINT1("Reserving failed with status 0x%08X\n", Status
);
1193 if (RtlpGetMode() == UserMode
)
1195 /* If coalescing on free is disabled in usermode, then do it here */
1196 if (Heap
->Flags
& HEAP_DISABLE_COALESCE_ON_FREE
)
1198 FreeEntry
= RtlpCoalesceHeap(Heap
);
1200 /* If it's a suitable one - return it */
1202 FreeEntry
->Size
>= Size
)
1212 /***********************************************************************
1215 * Handle of heap: Success
1221 RtlCreateHeap(ULONG Flags
,
1226 PRTL_HEAP_PARAMETERS Parameters
)
1228 PVOID CommittedAddress
= NULL
, UncommittedAddress
= NULL
;
1230 RTL_HEAP_PARAMETERS SafeParams
= {0};
1231 ULONG_PTR MaximumUserModeAddress
;
1232 SYSTEM_BASIC_INFORMATION SystemInformation
;
1233 MEMORY_BASIC_INFORMATION MemoryInfo
;
1234 ULONG NtGlobalFlags
= RtlGetNtGlobalFlags();
1235 ULONG HeapSegmentFlags
= 0;
1239 /* Check for a special heap */
1240 if (RtlpPageHeapEnabled
&& !Addr
&& !Lock
)
1242 Heap
= RtlpPageHeapCreate(Flags
, Addr
, TotalSize
, CommitSize
, Lock
, Parameters
);
1243 if (Heap
) return Heap
;
1245 /* Reset a special Parameters == -1 hack */
1246 if ((ULONG_PTR
)Parameters
== (ULONG_PTR
)-1)
1249 DPRINT1("Enabling page heap failed\n");
1252 /* Check validation flags */
1253 if (!(Flags
& HEAP_SKIP_VALIDATION_CHECKS
) && (Flags
& ~HEAP_CREATE_VALID_MASK
))
1255 DPRINT1("Invalid flags 0x%08x, fixing...\n", Flags
);
1256 Flags
&= HEAP_CREATE_VALID_MASK
;
1259 /* TODO: Capture parameters, once we decide to use SEH */
1260 if (!Parameters
) Parameters
= &SafeParams
;
1262 /* Check global flags */
1263 if (NtGlobalFlags
& FLG_HEAP_DISABLE_COALESCING
)
1264 Flags
|= HEAP_DISABLE_COALESCE_ON_FREE
;
1266 if (NtGlobalFlags
& FLG_HEAP_ENABLE_FREE_CHECK
)
1267 Flags
|= HEAP_FREE_CHECKING_ENABLED
;
1269 if (NtGlobalFlags
& FLG_HEAP_ENABLE_TAIL_CHECK
)
1270 Flags
|= HEAP_TAIL_CHECKING_ENABLED
;
1272 if (RtlpGetMode() == UserMode
)
1274 /* Also check these flags if in usermode */
1275 if (NtGlobalFlags
& FLG_HEAP_VALIDATE_ALL
)
1276 Flags
|= HEAP_VALIDATE_ALL_ENABLED
;
1278 if (NtGlobalFlags
& FLG_HEAP_VALIDATE_PARAMETERS
)
1279 Flags
|= HEAP_VALIDATE_PARAMETERS_ENABLED
;
1281 if (NtGlobalFlags
& FLG_USER_STACK_TRACE_DB
)
1282 Flags
|= HEAP_CAPTURE_STACK_BACKTRACES
;
1285 /* Set tunable parameters */
1286 RtlpSetHeapParameters(Parameters
);
1288 /* Get the max um address */
1289 Status
= ZwQuerySystemInformation(SystemBasicInformation
,
1291 sizeof(SystemInformation
),
1294 if (!NT_SUCCESS(Status
))
1296 DPRINT1("Getting max usermode address failed with status 0x%08x\n", Status
);
1300 MaximumUserModeAddress
= SystemInformation
.MaximumUserModeAddress
;
1302 /* Calculate max alloc size */
1303 if (!Parameters
->MaximumAllocationSize
)
1304 Parameters
->MaximumAllocationSize
= MaximumUserModeAddress
- (ULONG_PTR
)0x10000 - PAGE_SIZE
;
1306 MaxBlockSize
= 0x80000 - PAGE_SIZE
;
1308 if (!Parameters
->VirtualMemoryThreshold
||
1309 Parameters
->VirtualMemoryThreshold
> MaxBlockSize
)
1311 Parameters
->VirtualMemoryThreshold
= MaxBlockSize
;
1314 /* Check reserve/commit sizes and set default values */
1317 CommitSize
= PAGE_SIZE
;
1319 TotalSize
= ROUND_UP(TotalSize
, PAGE_SIZE
);
1321 TotalSize
= 64 * PAGE_SIZE
;
1325 /* Round up the commit size to be at least the page size */
1326 CommitSize
= ROUND_UP(CommitSize
, PAGE_SIZE
);
1329 TotalSize
= ROUND_UP(TotalSize
, PAGE_SIZE
);
1331 TotalSize
= ROUND_UP(CommitSize
, 16 * PAGE_SIZE
);
1334 /* Call special heap */
1335 if (RtlpHeapIsSpecial(Flags
))
1336 return RtlDebugCreateHeap(Flags
, Addr
, TotalSize
, CommitSize
, Lock
, Parameters
);
1338 /* Without serialization, a lock makes no sense */
1339 if ((Flags
& HEAP_NO_SERIALIZE
) && (Lock
!= NULL
))
1342 /* See if we are already provided with an address for the heap */
1345 if (Parameters
->CommitRoutine
)
1347 /* There is a commit routine, so no problem here, check params */
1348 if ((Flags
& HEAP_GROWABLE
) ||
1349 !Parameters
->InitialCommit
||
1350 !Parameters
->InitialReserve
||
1351 (Parameters
->InitialCommit
> Parameters
->InitialReserve
))
1357 /* Calculate committed and uncommitted addresses */
1358 CommittedAddress
= Addr
;
1359 UncommittedAddress
= (PCHAR
)Addr
+ Parameters
->InitialCommit
;
1360 TotalSize
= Parameters
->InitialReserve
;
1362 /* Zero the initial page ourselves */
1363 RtlZeroMemory(CommittedAddress
, PAGE_SIZE
);
1367 /* Commit routine is absent, so query how much memory caller reserved */
1368 Status
= ZwQueryVirtualMemory(NtCurrentProcess(),
1370 MemoryBasicInformation
,
1375 if (!NT_SUCCESS(Status
))
1377 DPRINT1("Querying amount of user supplied memory failed with status 0x%08X\n", Status
);
1382 if (MemoryInfo
.BaseAddress
!= Addr
||
1383 MemoryInfo
.State
== MEM_FREE
)
1388 /* Validation checks passed, set committed/uncommitted addresses */
1389 CommittedAddress
= Addr
;
1391 /* Check if it's committed or not */
1392 if (MemoryInfo
.State
== MEM_COMMIT
)
1394 /* Zero it out because it's already committed */
1395 RtlZeroMemory(CommittedAddress
, PAGE_SIZE
);
1397 /* Calculate uncommitted address value */
1398 CommitSize
= MemoryInfo
.RegionSize
;
1399 TotalSize
= CommitSize
;
1400 UncommittedAddress
= (PCHAR
)Addr
+ CommitSize
;
1402 /* Check if uncommitted address is reserved */
1403 Status
= ZwQueryVirtualMemory(NtCurrentProcess(),
1405 MemoryBasicInformation
,
1410 if (NT_SUCCESS(Status
) &&
1411 MemoryInfo
.State
== MEM_RESERVE
)
1413 /* It is, so add it up to the reserve size */
1414 TotalSize
+= MemoryInfo
.RegionSize
;
1419 /* It's not committed, inform following code that a commit is necessary */
1420 CommitSize
= PAGE_SIZE
;
1421 UncommittedAddress
= Addr
;
1425 /* Mark this as a user-committed mem */
1426 HeapSegmentFlags
= HEAP_USER_ALLOCATED
;
1431 /* Check commit routine */
1432 if (Parameters
->CommitRoutine
) return NULL
;
1434 /* Reserve memory */
1435 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1442 if (!NT_SUCCESS(Status
))
1444 DPRINT1("Failed to reserve memory with status 0x%08x\n", Status
);
1448 /* Set base addresses */
1449 CommittedAddress
= Heap
;
1450 UncommittedAddress
= Heap
;
1453 /* Check if we need to commit something */
1454 if (CommittedAddress
== UncommittedAddress
)
1456 /* Commit the required size */
1457 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
1464 DPRINT("Committed %Iu bytes at base %p\n", CommitSize
, CommittedAddress
);
1466 if (!NT_SUCCESS(Status
))
1468 DPRINT1("Failure, Status 0x%08X\n", Status
);
1470 /* Release memory if it was reserved */
1471 if (!Addr
) ZwFreeVirtualMemory(NtCurrentProcess(),
1479 /* Calculate new uncommitted address */
1480 UncommittedAddress
= (PCHAR
)UncommittedAddress
+ CommitSize
;
1483 /* Initialize the heap */
1484 Status
= RtlpInitializeHeap(Heap
, Flags
, Lock
, Parameters
);
1485 if (!NT_SUCCESS(Status
))
1487 DPRINT1("Failed to initialize heap (%x)\n", Status
);
1491 /* Initialize heap's first segment */
1492 Status
= RtlpInitializeHeapSegment(Heap
, (PHEAP_SEGMENT
) (Heap
), 0, HeapSegmentFlags
, TotalSize
, CommitSize
);
1493 if (!NT_SUCCESS(Status
))
1495 DPRINT1("Failed to initialize heap segment (%x)\n", Status
);
1499 DPRINT("Created heap %p, CommitSize %x, ReserveSize %x\n", Heap
, CommitSize
, TotalSize
);
1501 /* Add heap to process list in case of usermode heap */
1502 if (RtlpGetMode() == UserMode
)
1504 RtlpAddHeapToProcessList(Heap
);
1506 // FIXME: What about lookasides?
1512 /***********************************************************************
1521 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1522 * Failure: The Heap handle, if heap is the process heap.
1525 RtlDestroyHeap(HANDLE HeapPtr
) /* [in] Handle of heap */
1527 PHEAP Heap
= (PHEAP
)HeapPtr
;
1528 PLIST_ENTRY Current
;
1529 PHEAP_UCR_SEGMENT UcrSegment
;
1530 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry
;
1534 PHEAP_SEGMENT Segment
;
1536 if (!HeapPtr
) return NULL
;
1538 /* Call page heap routine if required */
1539 if (Heap
->ForceFlags
& HEAP_FLAG_PAGE_ALLOCS
) return RtlpPageHeapDestroy(HeapPtr
);
1541 /* Call special heap */
1542 if (RtlpHeapIsSpecial(Heap
->Flags
))
1544 if (!RtlDebugDestroyHeap(Heap
)) return HeapPtr
;
1547 /* Check for a process heap */
1548 if (RtlpGetMode() == UserMode
&&
1549 HeapPtr
== NtCurrentPeb()->ProcessHeap
) return HeapPtr
;
1551 /* Free up all big allocations */
1552 Current
= Heap
->VirtualAllocdBlocks
.Flink
;
1553 while (Current
!= &Heap
->VirtualAllocdBlocks
)
1555 VirtualEntry
= CONTAINING_RECORD(Current
, HEAP_VIRTUAL_ALLOC_ENTRY
, Entry
);
1556 BaseAddress
= (PVOID
)VirtualEntry
;
1557 Current
= Current
->Flink
;
1559 ZwFreeVirtualMemory(NtCurrentProcess(),
1565 /* Delete tags and remove heap from the process heaps list in user mode */
1566 if (RtlpGetMode() == UserMode
)
1568 // FIXME DestroyTags
1569 RtlpRemoveHeapFromProcessList(Heap
);
1572 /* Delete the heap lock */
1573 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
1575 /* Delete it if it wasn't user allocated */
1576 if (!(Heap
->Flags
& HEAP_LOCK_USER_ALLOCATED
))
1577 RtlDeleteHeapLock(Heap
->LockVariable
);
1579 /* Clear out the lock variable */
1580 Heap
->LockVariable
= NULL
;
1583 /* Free UCR segments if any were created */
1584 Current
= Heap
->UCRSegments
.Flink
;
1585 while (Current
!= &Heap
->UCRSegments
)
1587 UcrSegment
= CONTAINING_RECORD(Current
, HEAP_UCR_SEGMENT
, ListEntry
);
1589 /* Advance to the next descriptor */
1590 Current
= Current
->Flink
;
1592 BaseAddress
= (PVOID
)UcrSegment
;
1595 /* Release that memory */
1596 ZwFreeVirtualMemory(NtCurrentProcess(),
1602 /* Go through segments and destroy them */
1603 for (i
= HEAP_SEGMENTS
- 1; i
>= 0; i
--)
1605 Segment
= Heap
->Segments
[i
];
1606 if (Segment
) RtlpDestroyHeapSegment(Segment
);
1613 RtlpSplitEntry(PHEAP Heap
,
1615 PHEAP_FREE_ENTRY FreeBlock
,
1616 SIZE_T AllocationSize
,
1620 PHEAP_FREE_ENTRY SplitBlock
, SplitBlock2
;
1621 UCHAR FreeFlags
, EntryFlags
= HEAP_ENTRY_BUSY
;
1622 PHEAP_ENTRY InUseEntry
;
1625 /* Add extra flags in case of settable user value feature is requested,
1626 or there is a tag (small or normal) or there is a request to
1627 capture stack backtraces */
1628 if ((Flags
& HEAP_EXTRA_FLAGS_MASK
) ||
1629 Heap
->PseudoTagEntries
)
1631 /* Add flag which means that the entry will have extra stuff attached */
1632 EntryFlags
|= HEAP_ENTRY_EXTRA_PRESENT
;
1634 /* NB! AllocationSize is already adjusted by RtlAllocateHeap */
1637 /* Add settable user flags, if any */
1638 EntryFlags
|= (Flags
& HEAP_SETTABLE_USER_FLAGS
) >> 4;
1640 /* Save flags, update total free size */
1641 FreeFlags
= FreeBlock
->Flags
;
1642 Heap
->TotalFreeSize
-= FreeBlock
->Size
;
1644 /* Make this block an in-use one */
1645 InUseEntry
= (PHEAP_ENTRY
)FreeBlock
;
1646 InUseEntry
->Flags
= EntryFlags
;
1647 InUseEntry
->SmallTagIndex
= 0;
1649 /* Calculate the extra amount */
1650 FreeSize
= InUseEntry
->Size
- Index
;
1652 /* Update it's size fields (we don't need their data anymore) */
1653 InUseEntry
->Size
= (USHORT
)Index
;
1654 InUseEntry
->UnusedBytes
= (UCHAR
)(AllocationSize
- Size
);
1656 /* If there is something to split - do the split */
1659 /* Don't split if resulting entry can't contain any payload data
1660 (i.e. being just HEAP_ENTRY_SIZE) */
1663 /* Increase sizes of the in-use entry */
1665 InUseEntry
->UnusedBytes
+= sizeof(HEAP_ENTRY
);
1669 /* Calculate a pointer to the new entry */
1670 SplitBlock
= (PHEAP_FREE_ENTRY
)(InUseEntry
+ Index
);
1673 SplitBlock
->Flags
= FreeFlags
;
1674 SplitBlock
->SegmentOffset
= InUseEntry
->SegmentOffset
;
1675 SplitBlock
->Size
= (USHORT
)FreeSize
;
1676 SplitBlock
->PreviousSize
= (USHORT
)Index
;
1678 /* Check if it's the last entry */
1679 if (FreeFlags
& HEAP_ENTRY_LAST_ENTRY
)
1681 /* Insert it to the free list if it's the last entry */
1682 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
1683 Heap
->TotalFreeSize
+= FreeSize
;
1687 /* Not so easy - need to update next's previous size too */
1688 SplitBlock2
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
);
1690 if (SplitBlock2
->Flags
& HEAP_ENTRY_BUSY
)
1692 SplitBlock2
->PreviousSize
= (USHORT
)FreeSize
;
1693 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
1694 Heap
->TotalFreeSize
+= FreeSize
;
1698 /* Even more complex - the next entry is free, so we can merge them into one! */
1699 SplitBlock
->Flags
= SplitBlock2
->Flags
;
1701 /* Remove that next entry */
1702 RtlpRemoveFreeBlock(Heap
, SplitBlock2
, FALSE
, FALSE
);
1705 FreeSize
+= SplitBlock2
->Size
;
1706 Heap
->TotalFreeSize
-= SplitBlock2
->Size
;
1708 if (FreeSize
<= HEAP_MAX_BLOCK_SIZE
)
1710 /* Insert it back */
1711 SplitBlock
->Size
= (USHORT
)FreeSize
;
1713 /* Don't forget to update previous size of the next entry! */
1714 if (!(SplitBlock
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
1716 ((PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
))->PreviousSize
= (USHORT
)FreeSize
;
1719 /* Actually insert it */
1720 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, (USHORT
)FreeSize
, FALSE
);
1722 /* Update total size */
1723 Heap
->TotalFreeSize
+= FreeSize
;
1727 /* Resulting block is quite big */
1728 RtlpInsertFreeBlock(Heap
, SplitBlock
, FreeSize
);
1733 /* Reset flags of the free entry */
1738 /* Set last entry flag */
1739 if (FreeFlags
& HEAP_ENTRY_LAST_ENTRY
)
1740 InUseEntry
->Flags
|= HEAP_ENTRY_LAST_ENTRY
;
1746 RtlpAllocateNonDedicated(PHEAP Heap
,
1749 SIZE_T AllocationSize
,
1753 PLIST_ENTRY FreeListHead
, Next
;
1754 PHEAP_FREE_ENTRY FreeBlock
;
1755 PHEAP_ENTRY InUseEntry
;
1756 PHEAP_ENTRY_EXTRA Extra
;
1757 EXCEPTION_RECORD ExceptionRecord
;
1759 /* Go through the zero list to find a place where to insert the new entry */
1760 FreeListHead
= &Heap
->FreeLists
[0];
1762 /* Start from the largest block to reduce time */
1763 Next
= FreeListHead
->Blink
;
1764 if (FreeListHead
!= Next
)
1766 FreeBlock
= CONTAINING_RECORD(Next
, HEAP_FREE_ENTRY
, FreeList
);
1768 if (FreeBlock
->Size
>= Index
)
1770 /* Our request is smaller than the largest entry in the zero list */
1772 /* Go through the list to find insertion place */
1773 Next
= FreeListHead
->Flink
;
1774 while (FreeListHead
!= Next
)
1776 FreeBlock
= CONTAINING_RECORD(Next
, HEAP_FREE_ENTRY
, FreeList
);
1778 if (FreeBlock
->Size
>= Index
)
1780 /* Found minimally fitting entry. Proceed to either using it as it is
1781 or splitting it to two entries */
1782 RemoveEntryList(&FreeBlock
->FreeList
);
1785 InUseEntry
= RtlpSplitEntry(Heap
, Flags
, FreeBlock
, AllocationSize
, Index
, Size
);
1787 /* Release the lock */
1788 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
1790 /* Zero memory if that was requested */
1791 if (Flags
& HEAP_ZERO_MEMORY
)
1792 RtlZeroMemory(InUseEntry
+ 1, Size
);
1793 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
1795 /* Fill this block with a special pattern */
1796 RtlFillMemoryUlong(InUseEntry
+ 1, Size
& ~0x3, ARENA_INUSE_FILLER
);
1799 /* Fill tail of the block with a special pattern too if requested */
1800 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
1802 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
, sizeof(HEAP_ENTRY
), HEAP_TAIL_FILL
);
1803 InUseEntry
->Flags
|= HEAP_ENTRY_FILL_PATTERN
;
1806 /* Prepare extra if it's present */
1807 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
1809 Extra
= RtlpGetExtraStuffPointer(InUseEntry
);
1810 RtlZeroMemory(Extra
, sizeof(HEAP_ENTRY_EXTRA
));
1815 /* Return pointer to the */
1816 return InUseEntry
+ 1;
1819 /* Advance to the next entry */
1825 /* Extend the heap, 0 list didn't have anything suitable */
1826 FreeBlock
= RtlpExtendHeap(Heap
, AllocationSize
);
1828 /* Use the new biggest entry we've got */
1831 RemoveEntryList(&FreeBlock
->FreeList
);
1834 InUseEntry
= RtlpSplitEntry(Heap
, Flags
, FreeBlock
, AllocationSize
, Index
, Size
);
1836 /* Release the lock */
1837 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
1839 /* Zero memory if that was requested */
1840 if (Flags
& HEAP_ZERO_MEMORY
)
1841 RtlZeroMemory(InUseEntry
+ 1, Size
);
1842 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
1844 /* Fill this block with a special pattern */
1845 RtlFillMemoryUlong(InUseEntry
+ 1, Size
& ~0x3, ARENA_INUSE_FILLER
);
1848 /* Fill tail of the block with a special pattern too if requested */
1849 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
1851 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
, sizeof(HEAP_ENTRY
), HEAP_TAIL_FILL
);
1852 InUseEntry
->Flags
|= HEAP_ENTRY_FILL_PATTERN
;
1855 /* Prepare extra if it's present */
1856 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
1858 Extra
= RtlpGetExtraStuffPointer(InUseEntry
);
1859 RtlZeroMemory(Extra
, sizeof(HEAP_ENTRY_EXTRA
));
1864 /* Return pointer to the */
1865 return InUseEntry
+ 1;
1868 /* Really unfortunate, out of memory condition */
1869 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_NO_MEMORY
);
1871 /* Generate an exception */
1872 if (Flags
& HEAP_GENERATE_EXCEPTIONS
)
1874 ExceptionRecord
.ExceptionCode
= STATUS_NO_MEMORY
;
1875 ExceptionRecord
.ExceptionRecord
= NULL
;
1876 ExceptionRecord
.NumberParameters
= 1;
1877 ExceptionRecord
.ExceptionFlags
= 0;
1878 ExceptionRecord
.ExceptionInformation
[0] = AllocationSize
;
1880 RtlRaiseException(&ExceptionRecord
);
1883 /* Release the lock */
1884 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
1885 DPRINT1("HEAP: Allocation failed!\n");
1886 DPRINT1("Flags %x\n", Heap
->Flags
);
1890 /***********************************************************************
1891 * HeapAlloc (KERNEL32.334)
1893 * Pointer to allocated memory block
1895 * 0x7d030f60--invalid flags in RtlHeapAllocate
1899 RtlAllocateHeap(IN PVOID HeapPtr
,
1903 PHEAP Heap
= (PHEAP
)HeapPtr
;
1904 PULONG FreeListsInUse
;
1905 ULONG FreeListsInUseUlong
;
1906 SIZE_T AllocationSize
;
1907 SIZE_T Index
, InUseIndex
, i
;
1908 PLIST_ENTRY FreeListHead
;
1909 PHEAP_ENTRY InUseEntry
;
1910 PHEAP_FREE_ENTRY FreeBlock
;
1911 UCHAR FreeFlags
, EntryFlags
= HEAP_ENTRY_BUSY
;
1912 EXCEPTION_RECORD ExceptionRecord
;
1913 BOOLEAN HeapLocked
= FALSE
;
1914 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualBlock
= NULL
;
1915 PHEAP_ENTRY_EXTRA Extra
;
1919 Flags
|= Heap
->ForceFlags
;
1921 /* Call special heap */
1922 if (RtlpHeapIsSpecial(Flags
))
1923 return RtlDebugAllocateHeap(Heap
, Flags
, Size
);
1925 /* Check for the maximum size */
1926 if (Size
>= 0x80000000)
1928 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_NO_MEMORY
);
1929 DPRINT1("HEAP: Allocation failed!\n");
1933 if (Flags
& (HEAP_CREATE_ENABLE_TRACING
))
1935 DPRINT1("HEAP: RtlAllocateHeap is called with unsupported flags %x, ignoring\n", Flags
);
1938 //DPRINT("RtlAllocateHeap(%p %x %x)\n", Heap, Flags, Size);
1940 /* Calculate allocation size and index */
1942 AllocationSize
= Size
;
1945 AllocationSize
= (AllocationSize
+ Heap
->AlignRound
) & Heap
->AlignMask
;
1947 /* Add extra flags in case of settable user value feature is requested,
1948 or there is a tag (small or normal) or there is a request to
1949 capture stack backtraces */
1950 if ((Flags
& HEAP_EXTRA_FLAGS_MASK
) ||
1951 Heap
->PseudoTagEntries
)
1953 /* Add flag which means that the entry will have extra stuff attached */
1954 EntryFlags
|= HEAP_ENTRY_EXTRA_PRESENT
;
1956 /* Account for extra stuff size */
1957 AllocationSize
+= sizeof(HEAP_ENTRY_EXTRA
);
1960 /* Add settable user flags, if any */
1961 EntryFlags
|= (Flags
& HEAP_SETTABLE_USER_FLAGS
) >> 4;
1963 Index
= AllocationSize
>> HEAP_ENTRY_SHIFT
;
1965 /* Acquire the lock if necessary */
1966 if (!(Flags
& HEAP_NO_SERIALIZE
))
1968 RtlEnterHeapLock(Heap
->LockVariable
, TRUE
);
1972 /* Depending on the size, the allocation is going to be done from dedicated,
1973 non-dedicated lists or a virtual block of memory */
1974 if (Index
< HEAP_FREELISTS
)
1976 FreeListHead
= &Heap
->FreeLists
[Index
];
1978 if (!IsListEmpty(FreeListHead
))
1980 /* There is a free entry in this list */
1981 FreeBlock
= CONTAINING_RECORD(FreeListHead
->Blink
,
1985 /* Save flags and remove the free entry */
1986 FreeFlags
= FreeBlock
->Flags
;
1987 RtlpRemoveFreeBlock(Heap
, FreeBlock
, TRUE
, FALSE
);
1989 /* Update the total free size of the heap */
1990 Heap
->TotalFreeSize
-= Index
;
1992 /* Initialize this block */
1993 InUseEntry
= (PHEAP_ENTRY
)FreeBlock
;
1994 InUseEntry
->Flags
= EntryFlags
| (FreeFlags
& HEAP_ENTRY_LAST_ENTRY
);
1995 InUseEntry
->UnusedBytes
= (UCHAR
)(AllocationSize
- Size
);
1996 InUseEntry
->SmallTagIndex
= 0;
2000 /* Find smallest free block which this request could fit in */
2001 InUseIndex
= Index
>> 5;
2002 FreeListsInUse
= &Heap
->u
.FreeListsInUseUlong
[InUseIndex
];
2004 /* This bit magic disables all sizes which are less than the requested allocation size */
2005 FreeListsInUseUlong
= *FreeListsInUse
++ & ~((1 << ((ULONG
)Index
& 0x1f)) - 1);
2007 /* If size is definitily more than our lists - go directly to the non-dedicated one */
2009 return RtlpAllocateNonDedicated(Heap
, Flags
, Size
, AllocationSize
, Index
, HeapLocked
);
2011 /* Go through the list */
2012 for (i
= InUseIndex
; i
< 4; i
++)
2014 if (FreeListsInUseUlong
)
2016 FreeListHead
= &Heap
->FreeLists
[i
* 32];
2020 if (i
< 3) FreeListsInUseUlong
= *FreeListsInUse
++;
2023 /* Nothing found, search in the non-dedicated list */
2025 return RtlpAllocateNonDedicated(Heap
, Flags
, Size
, AllocationSize
, Index
, HeapLocked
);
2027 /* That list is found, now calculate exact block */
2028 FreeListHead
+= RtlpFindLeastSetBit(FreeListsInUseUlong
);
2030 /* Take this entry and remove it from the list of free blocks */
2031 FreeBlock
= CONTAINING_RECORD(FreeListHead
->Blink
,
2034 RtlpRemoveFreeBlock(Heap
, FreeBlock
, TRUE
, FALSE
);
2037 InUseEntry
= RtlpSplitEntry(Heap
, Flags
, FreeBlock
, AllocationSize
, Index
, Size
);
2040 /* Release the lock */
2041 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2043 /* Zero memory if that was requested */
2044 if (Flags
& HEAP_ZERO_MEMORY
)
2045 RtlZeroMemory(InUseEntry
+ 1, Size
);
2046 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
2048 /* Fill this block with a special pattern */
2049 RtlFillMemoryUlong(InUseEntry
+ 1, Size
& ~0x3, ARENA_INUSE_FILLER
);
2052 /* Fill tail of the block with a special pattern too if requested */
2053 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
2055 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
, sizeof(HEAP_ENTRY
), HEAP_TAIL_FILL
);
2056 InUseEntry
->Flags
|= HEAP_ENTRY_FILL_PATTERN
;
2059 /* Prepare extra if it's present */
2060 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
2062 Extra
= RtlpGetExtraStuffPointer(InUseEntry
);
2063 RtlZeroMemory(Extra
, sizeof(HEAP_ENTRY_EXTRA
));
2068 /* User data starts right after the entry's header */
2069 return InUseEntry
+ 1;
2071 else if (Index
<= Heap
->VirtualMemoryThreshold
)
2073 /* The block is too large for dedicated lists, but fine for a non-dedicated one */
2074 return RtlpAllocateNonDedicated(Heap
, Flags
, Size
, AllocationSize
, Index
, HeapLocked
);
2076 else if (Heap
->Flags
& HEAP_GROWABLE
)
2078 /* We've got a very big allocation request, satisfy it by directly allocating virtual memory */
2079 AllocationSize
+= sizeof(HEAP_VIRTUAL_ALLOC_ENTRY
) - sizeof(HEAP_ENTRY
);
2081 Status
= ZwAllocateVirtualMemory(NtCurrentProcess(),
2082 (PVOID
*)&VirtualBlock
,
2088 if (!NT_SUCCESS(Status
))
2091 /* Release the lock */
2092 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2093 DPRINT1("HEAP: Allocation failed!\n");
2097 /* Initialize the newly allocated block */
2098 VirtualBlock
->BusyBlock
.Size
= (USHORT
)(AllocationSize
- Size
);
2099 ASSERT(VirtualBlock
->BusyBlock
.Size
>= sizeof(HEAP_VIRTUAL_ALLOC_ENTRY
));
2100 VirtualBlock
->BusyBlock
.Flags
= EntryFlags
| HEAP_ENTRY_VIRTUAL_ALLOC
| HEAP_ENTRY_EXTRA_PRESENT
;
2101 VirtualBlock
->CommitSize
= AllocationSize
;
2102 VirtualBlock
->ReserveSize
= AllocationSize
;
2104 /* Insert it into the list of virtual allocations */
2105 InsertTailList(&Heap
->VirtualAllocdBlocks
, &VirtualBlock
->Entry
);
2107 /* Release the lock */
2108 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2110 /* Return pointer to user data */
2111 return VirtualBlock
+ 1;
2114 /* Generate an exception */
2115 if (Flags
& HEAP_GENERATE_EXCEPTIONS
)
2117 ExceptionRecord
.ExceptionCode
= STATUS_NO_MEMORY
;
2118 ExceptionRecord
.ExceptionRecord
= NULL
;
2119 ExceptionRecord
.NumberParameters
= 1;
2120 ExceptionRecord
.ExceptionFlags
= 0;
2121 ExceptionRecord
.ExceptionInformation
[0] = AllocationSize
;
2123 RtlRaiseException(&ExceptionRecord
);
2126 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_BUFFER_TOO_SMALL
);
2128 /* Release the lock */
2129 if (HeapLocked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2130 DPRINT1("HEAP: Allocation failed!\n");
2135 /***********************************************************************
2136 * HeapFree (KERNEL32.338)
2143 BOOLEAN NTAPI
RtlFreeHeap(
2144 HANDLE HeapPtr
, /* [in] Handle of heap */
2145 ULONG Flags
, /* [in] Heap freeing flags */
2146 PVOID Ptr
/* [in] Address of memory to free */
2150 PHEAP_ENTRY HeapEntry
;
2151 USHORT TagIndex
= 0;
2153 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry
;
2154 BOOLEAN Locked
= FALSE
;
2157 /* Freeing NULL pointer is a legal operation */
2158 if (!Ptr
) return TRUE
;
2160 /* Get pointer to the heap and force flags */
2161 Heap
= (PHEAP
)HeapPtr
;
2162 Flags
|= Heap
->ForceFlags
;
2164 /* Call special heap */
2165 if (RtlpHeapIsSpecial(Flags
))
2166 return RtlDebugFreeHeap(Heap
, Flags
, Ptr
);
2168 /* Lock if necessary */
2169 if (!(Flags
& HEAP_NO_SERIALIZE
))
2171 RtlEnterHeapLock(Heap
->LockVariable
, TRUE
);
2175 /* Get pointer to the heap entry */
2176 HeapEntry
= (PHEAP_ENTRY
)Ptr
- 1;
2178 /* Check this entry, fail if it's invalid */
2179 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
) ||
2180 (((ULONG_PTR
)Ptr
& 0x7) != 0) ||
2181 (HeapEntry
->SegmentOffset
>= HEAP_SEGMENTS
))
2183 /* This is an invalid block */
2184 DPRINT1("HEAP: Trying to free an invalid address %p!\n", Ptr
);
2185 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
2187 /* Release the heap lock */
2188 if (Locked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2192 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2194 /* Big allocation */
2195 VirtualEntry
= CONTAINING_RECORD(HeapEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
2197 /* Remove it from the list */
2198 RemoveEntryList(&VirtualEntry
->Entry
);
2203 Status
= ZwFreeVirtualMemory(NtCurrentProcess(),
2204 (PVOID
*)&VirtualEntry
,
2208 if (!NT_SUCCESS(Status
))
2210 DPRINT1("HEAP: Failed releasing memory with Status 0x%08X. Heap %p, ptr %p, base address %p\n",
2211 Status
, Heap
, Ptr
, VirtualEntry
);
2212 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(Status
);
2217 /* Normal allocation */
2218 BlockSize
= HeapEntry
->Size
;
2222 /* Coalesce in kernel mode, and in usermode if it's not disabled */
2223 if (RtlpGetMode() == KernelMode
||
2224 (RtlpGetMode() == UserMode
&& !(Heap
->Flags
& HEAP_DISABLE_COALESCE_ON_FREE
)))
2226 HeapEntry
= (PHEAP_ENTRY
)RtlpCoalesceFreeBlocks(Heap
,
2227 (PHEAP_FREE_ENTRY
)HeapEntry
,
2232 /* If there is no need to decommit the block - put it into a free list */
2233 if (BlockSize
< Heap
->DeCommitFreeBlockThreshold
||
2234 (Heap
->TotalFreeSize
+ BlockSize
< Heap
->DeCommitTotalFreeThreshold
))
2236 /* Check if it needs to go to a 0 list */
2237 if (BlockSize
> HEAP_MAX_BLOCK_SIZE
)
2239 /* General-purpose 0 list */
2240 RtlpInsertFreeBlock(Heap
, (PHEAP_FREE_ENTRY
)HeapEntry
, BlockSize
);
2244 /* Usual free list */
2245 RtlpInsertFreeBlockHelper(Heap
, (PHEAP_FREE_ENTRY
)HeapEntry
, BlockSize
, FALSE
);
2247 /* Assert sizes are consistent */
2248 if (!(HeapEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
2250 ASSERT((HeapEntry
+ BlockSize
)->PreviousSize
== BlockSize
);
2253 /* Increase the free size */
2254 Heap
->TotalFreeSize
+= BlockSize
;
2258 if (RtlpGetMode() == UserMode
&&
2267 /* Decommit this block */
2268 RtlpDeCommitFreeBlock(Heap
, (PHEAP_FREE_ENTRY
)HeapEntry
, BlockSize
);
2272 /* Release the heap lock */
2273 if (Locked
) RtlLeaveHeapLock(Heap
->LockVariable
);
2279 RtlpGrowBlockInPlace (IN PHEAP Heap
,
2281 IN PHEAP_ENTRY InUseEntry
,
2285 UCHAR EntryFlags
, RememberFlags
;
2286 PHEAP_FREE_ENTRY FreeEntry
, UnusedEntry
, FollowingEntry
;
2287 SIZE_T FreeSize
, PrevSize
, TailPart
, AddedSize
= 0;
2288 PHEAP_ENTRY_EXTRA OldExtra
, NewExtra
;
2290 /* We can't grow beyond specified threshold */
2291 if (Index
> Heap
->VirtualMemoryThreshold
)
2294 /* Get entry flags */
2295 EntryFlags
= InUseEntry
->Flags
;
2297 /* Get the next free entry */
2298 FreeEntry
= (PHEAP_FREE_ENTRY
)(InUseEntry
+ InUseEntry
->Size
);
2300 if (EntryFlags
& HEAP_ENTRY_LAST_ENTRY
)
2302 /* There is no next block, just uncommitted space. Calculate how much is needed */
2303 FreeSize
= (Index
- InUseEntry
->Size
) << HEAP_ENTRY_SHIFT
;
2304 FreeSize
= ROUND_UP(FreeSize
, PAGE_SIZE
);
2306 /* Find and commit those pages */
2307 FreeEntry
= RtlpFindAndCommitPages(Heap
,
2308 Heap
->Segments
[InUseEntry
->SegmentOffset
],
2312 /* Fail if it failed... */
2313 if (!FreeEntry
) return FALSE
;
2315 /* It was successful, perform coalescing */
2316 FreeSize
= FreeSize
>> HEAP_ENTRY_SHIFT
;
2317 FreeEntry
= RtlpCoalesceFreeBlocks(Heap
, FreeEntry
, &FreeSize
, FALSE
);
2319 /* Check if it's enough */
2320 if (FreeSize
+ InUseEntry
->Size
< Index
)
2322 /* Still not enough */
2323 RtlpInsertFreeBlock(Heap
, FreeEntry
, FreeSize
);
2324 Heap
->TotalFreeSize
+= FreeSize
;
2328 /* Remember flags of this free entry */
2329 RememberFlags
= FreeEntry
->Flags
;
2332 FreeSize
+= InUseEntry
->Size
;
2336 /* The next block indeed exists. Check if it's free or in use */
2337 if (FreeEntry
->Flags
& HEAP_ENTRY_BUSY
) return FALSE
;
2339 /* Next entry is free, check if it can fit the block we need */
2340 FreeSize
= InUseEntry
->Size
+ FreeEntry
->Size
;
2341 if (FreeSize
< Index
) return FALSE
;
2343 /* Remember flags of this free entry */
2344 RememberFlags
= FreeEntry
->Flags
;
2346 /* Remove this block from the free list */
2347 RtlpRemoveFreeBlock(Heap
, FreeEntry
, FALSE
, FALSE
);
2348 Heap
->TotalFreeSize
-= FreeEntry
->Size
;
2351 PrevSize
= (InUseEntry
->Size
<< HEAP_ENTRY_SHIFT
) - InUseEntry
->UnusedBytes
;
2354 /* Don't produce too small blocks */
2361 /* Process extra stuff */
2362 if (EntryFlags
& HEAP_ENTRY_EXTRA_PRESENT
)
2364 /* Calculate pointers */
2365 OldExtra
= (PHEAP_ENTRY_EXTRA
)(InUseEntry
+ InUseEntry
->Size
- 1);
2366 NewExtra
= (PHEAP_ENTRY_EXTRA
)(InUseEntry
+ Index
- 1);
2369 *NewExtra
= *OldExtra
;
2375 InUseEntry
->Size
= (USHORT
)Index
;
2376 InUseEntry
->UnusedBytes
= (UCHAR
)((Index
<< HEAP_ENTRY_SHIFT
) - Size
);
2378 /* Check if there is a free space remaining after merging those blocks */
2381 /* Update flags and sizes */
2382 InUseEntry
->Flags
|= RememberFlags
& HEAP_ENTRY_LAST_ENTRY
;
2384 /* Either update previous size of the next entry or mark it as a last
2385 entry in the segment*/
2386 if (!(RememberFlags
& HEAP_ENTRY_LAST_ENTRY
))
2387 (InUseEntry
+ InUseEntry
->Size
)->PreviousSize
= InUseEntry
->Size
;
2391 /* Complex case, we need to split the block to give unused free space
2393 UnusedEntry
= (PHEAP_FREE_ENTRY
)(InUseEntry
+ Index
);
2394 UnusedEntry
->PreviousSize
= (USHORT
)Index
;
2395 UnusedEntry
->SegmentOffset
= InUseEntry
->SegmentOffset
;
2397 /* Update the following block or set the last entry in the segment */
2398 if (RememberFlags
& HEAP_ENTRY_LAST_ENTRY
)
2400 /* Set flags and size */
2401 UnusedEntry
->Flags
= RememberFlags
;
2402 UnusedEntry
->Size
= (USHORT
)FreeSize
;
2404 /* Insert it to the heap and update total size */
2405 RtlpInsertFreeBlockHelper(Heap
, UnusedEntry
, FreeSize
, FALSE
);
2406 Heap
->TotalFreeSize
+= FreeSize
;
2410 /* There is a block after this one */
2411 FollowingEntry
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)UnusedEntry
+ FreeSize
);
2413 if (FollowingEntry
->Flags
& HEAP_ENTRY_BUSY
)
2415 /* Update flags and set size of the unused space entry */
2416 UnusedEntry
->Flags
= RememberFlags
& (~HEAP_ENTRY_LAST_ENTRY
);
2417 UnusedEntry
->Size
= (USHORT
)FreeSize
;
2419 /* Update previous size of the following entry */
2420 FollowingEntry
->PreviousSize
= (USHORT
)FreeSize
;
2422 /* Insert it to the heap and update total free size */
2423 RtlpInsertFreeBlockHelper(Heap
, UnusedEntry
, FreeSize
, FALSE
);
2424 Heap
->TotalFreeSize
+= FreeSize
;
2428 /* That following entry is also free, what a fortune! */
2429 RememberFlags
= FollowingEntry
->Flags
;
2432 RtlpRemoveFreeBlock(Heap
, FollowingEntry
, FALSE
, FALSE
);
2433 Heap
->TotalFreeSize
-= FollowingEntry
->Size
;
2435 /* And make up a new combined block */
2436 FreeSize
+= FollowingEntry
->Size
;
2437 UnusedEntry
->Flags
= RememberFlags
;
2439 /* Check where to put it */
2440 if (FreeSize
<= HEAP_MAX_BLOCK_SIZE
)
2442 /* Fine for a dedicated list */
2443 UnusedEntry
->Size
= (USHORT
)FreeSize
;
2445 if (!(RememberFlags
& HEAP_ENTRY_LAST_ENTRY
))
2446 ((PHEAP_ENTRY
)UnusedEntry
+ FreeSize
)->PreviousSize
= (USHORT
)FreeSize
;
2448 /* Insert it back and update total size */
2449 RtlpInsertFreeBlockHelper(Heap
, UnusedEntry
, FreeSize
, FALSE
);
2450 Heap
->TotalFreeSize
+= FreeSize
;
2454 /* The block is very large, leave all the hassle to the insertion routine */
2455 RtlpInsertFreeBlock(Heap
, UnusedEntry
, FreeSize
);
2461 /* Properly "zero out" (and fill!) the space */
2462 if (Flags
& HEAP_ZERO_MEMORY
)
2464 RtlZeroMemory((PCHAR
)(InUseEntry
+ 1) + PrevSize
, Size
- PrevSize
);
2466 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
2468 /* Calculate tail part which we need to fill */
2469 TailPart
= PrevSize
& (sizeof(ULONG
) - 1);
2471 /* "Invert" it as usual */
2472 if (TailPart
) TailPart
= 4 - TailPart
;
2474 if (Size
> (PrevSize
+ TailPart
))
2475 AddedSize
= (Size
- (PrevSize
+ TailPart
)) & ~(sizeof(ULONG
) - 1);
2479 RtlFillMemoryUlong((PCHAR
)(InUseEntry
+ 1) + PrevSize
+ TailPart
,
2481 ARENA_INUSE_FILLER
);
2485 /* Fill the new tail */
2486 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
2488 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
,
2493 /* Copy user settable flags */
2494 InUseEntry
->Flags
&= ~HEAP_ENTRY_SETTABLE_FLAGS
;
2495 InUseEntry
->Flags
|= ((Flags
& HEAP_SETTABLE_USER_FLAGS
) >> 4);
2497 /* Return success */
2501 PHEAP_ENTRY_EXTRA NTAPI
2502 RtlpGetExtraStuffPointer(PHEAP_ENTRY HeapEntry
)
2504 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry
;
2506 /* Check if it's a big block */
2507 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2509 VirtualEntry
= CONTAINING_RECORD(HeapEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
2511 /* Return a pointer to the extra stuff*/
2512 return &VirtualEntry
->ExtraStuff
;
2516 /* This is a usual entry, which means extra stuff follows this block */
2517 return (PHEAP_ENTRY_EXTRA
)(HeapEntry
+ HeapEntry
->Size
- 1);
2522 /***********************************************************************
2525 * Heap [in] Handle of heap block
2526 * Flags [in] Heap reallocation flags
2527 * Ptr, [in] Address of memory to reallocate
2528 * Size [in] Number of bytes to reallocate
2531 * Pointer to reallocated memory block
2533 * 0x7d030f60--invalid flags in RtlHeapAllocate
2537 RtlReAllocateHeap(HANDLE HeapPtr
,
2542 PHEAP Heap
= (PHEAP
)HeapPtr
;
2543 PHEAP_ENTRY InUseEntry
, NewInUseEntry
;
2544 PHEAP_ENTRY_EXTRA OldExtra
, NewExtra
;
2545 SIZE_T AllocationSize
, FreeSize
, DecommitSize
;
2546 BOOLEAN HeapLocked
= FALSE
;
2547 PVOID NewBaseAddress
;
2548 PHEAP_FREE_ENTRY SplitBlock
, SplitBlock2
;
2549 SIZE_T OldSize
, Index
, OldIndex
;
2553 SIZE_T RemainderBytes
, ExtraSize
;
2554 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualAllocBlock
;
2555 EXCEPTION_RECORD ExceptionRecord
;
2557 /* Return success in case of a null pointer */
2560 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_SUCCESS
);
2564 /* Force heap flags */
2565 Flags
|= Heap
->ForceFlags
;
2567 /* Call special heap */
2568 if (RtlpHeapIsSpecial(Flags
))
2569 return RtlDebugReAllocateHeap(Heap
, Flags
, Ptr
, Size
);
2571 /* Make sure size is valid */
2572 if (Size
>= 0x80000000)
2574 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_NO_MEMORY
);
2578 /* Calculate allocation size and index */
2580 AllocationSize
= Size
;
2583 AllocationSize
= (AllocationSize
+ Heap
->AlignRound
) & Heap
->AlignMask
;
2585 /* Add up extra stuff, if it is present anywhere */
2586 if (((((PHEAP_ENTRY
)Ptr
)-1)->Flags
& HEAP_ENTRY_EXTRA_PRESENT
) ||
2587 (Flags
& HEAP_EXTRA_FLAGS_MASK
) ||
2588 Heap
->PseudoTagEntries
)
2590 AllocationSize
+= sizeof(HEAP_ENTRY_EXTRA
);
2593 /* Acquire the lock if necessary */
2594 if (!(Flags
& HEAP_NO_SERIALIZE
))
2596 RtlEnterHeapLock(Heap
->LockVariable
, TRUE
);
2598 Flags
&= ~HEAP_NO_SERIALIZE
;
2601 /* Get the pointer to the in-use entry */
2602 InUseEntry
= (PHEAP_ENTRY
)Ptr
- 1;
2604 /* If that entry is not really in-use, we have a problem */
2605 if (!(InUseEntry
->Flags
& HEAP_ENTRY_BUSY
))
2607 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
2609 /* Release the lock and return */
2611 RtlLeaveHeapLock(Heap
->LockVariable
);
2615 if (InUseEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2617 /* This is a virtually allocated block. Get its size */
2618 OldSize
= RtlpGetSizeOfBigBlock(InUseEntry
);
2620 /* Convert it to an index */
2621 OldIndex
= (OldSize
+ InUseEntry
->Size
) >> HEAP_ENTRY_SHIFT
;
2623 /* Calculate new allocation size and round it to the page size */
2624 AllocationSize
+= FIELD_OFFSET(HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
2625 AllocationSize
= ROUND_UP(AllocationSize
, PAGE_SIZE
);
2630 OldIndex
= InUseEntry
->Size
;
2632 OldSize
= (OldIndex
<< HEAP_ENTRY_SHIFT
) - InUseEntry
->UnusedBytes
;
2635 /* Calculate new index */
2636 Index
= AllocationSize
>> HEAP_ENTRY_SHIFT
;
2638 /* Check for 4 different scenarios (old size, new size, old index, new index) */
2639 if (Index
<= OldIndex
)
2641 /* Difference must be greater than 1, adjust if it's not so */
2642 if (Index
+ 1 == OldIndex
)
2645 AllocationSize
+= sizeof(HEAP_ENTRY
);
2648 /* Calculate new size */
2649 if (InUseEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2651 /* Simple in case of a virtual alloc - just an unused size */
2652 InUseEntry
->Size
= (USHORT
)(AllocationSize
- Size
);
2653 ASSERT(InUseEntry
->Size
>= sizeof(HEAP_VIRTUAL_ALLOC_ENTRY
));
2655 else if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
2657 /* There is extra stuff, take it into account */
2658 OldExtra
= (PHEAP_ENTRY_EXTRA
)(InUseEntry
+ InUseEntry
->Size
- 1);
2659 NewExtra
= (PHEAP_ENTRY_EXTRA
)(InUseEntry
+ Index
- 1);
2660 *NewExtra
= *OldExtra
;
2662 // FIXME Tagging, TagIndex
2664 /* Update unused bytes count */
2665 InUseEntry
->UnusedBytes
= (UCHAR
)(AllocationSize
- Size
);
2669 // FIXME Tagging, SmallTagIndex
2670 InUseEntry
->UnusedBytes
= (UCHAR
)(AllocationSize
- Size
);
2673 /* If new size is bigger than the old size */
2676 /* Zero out that additional space if required */
2677 if (Flags
& HEAP_ZERO_MEMORY
)
2679 RtlZeroMemory((PCHAR
)Ptr
+ OldSize
, Size
- OldSize
);
2681 else if (Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
)
2683 /* Fill it on free if required */
2684 RemainderBytes
= OldSize
& (sizeof(ULONG
) - 1);
2687 RemainderBytes
= 4 - RemainderBytes
;
2689 if (Size
> (OldSize
+ RemainderBytes
))
2691 /* Calculate actual amount of extra bytes to fill */
2692 ExtraSize
= (Size
- (OldSize
+ RemainderBytes
)) & ~(sizeof(ULONG
) - 1);
2694 /* Fill them if there are any */
2697 RtlFillMemoryUlong((PCHAR
)(InUseEntry
+ 1) + OldSize
+ RemainderBytes
,
2699 ARENA_INUSE_FILLER
);
2705 /* Fill tail of the heap entry if required */
2706 if (Heap
->Flags
& HEAP_TAIL_CHECKING_ENABLED
)
2708 RtlFillMemory((PCHAR
)(InUseEntry
+ 1) + Size
,
2713 /* Check if the difference is significant or not */
2714 if (Index
!= OldIndex
)
2717 FreeFlags
= InUseEntry
->Flags
& ~HEAP_ENTRY_BUSY
;
2719 if (FreeFlags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
2721 /* This is a virtual block allocation */
2722 VirtualAllocBlock
= CONTAINING_RECORD(InUseEntry
, HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
);
2726 DecommitBase
= (PCHAR
)VirtualAllocBlock
+ AllocationSize
;
2727 DecommitSize
= (OldIndex
<< HEAP_ENTRY_SHIFT
) - AllocationSize
;
2729 /* Release the memory */
2730 Status
= ZwFreeVirtualMemory(NtCurrentProcess(),
2731 (PVOID
*)&DecommitBase
,
2735 if (!NT_SUCCESS(Status
))
2737 DPRINT1("HEAP: Unable to release memory (pointer %p, size 0x%x), Status %08x\n", DecommitBase
, DecommitSize
, Status
);
2741 /* Otherwise reduce the commit size */
2742 VirtualAllocBlock
->CommitSize
-= DecommitSize
;
2747 /* Reduce size of the block and possibly split it */
2748 SplitBlock
= (PHEAP_FREE_ENTRY
)(InUseEntry
+ Index
);
2750 /* Initialize this entry */
2751 SplitBlock
->Flags
= FreeFlags
;
2752 SplitBlock
->PreviousSize
= (USHORT
)Index
;
2753 SplitBlock
->SegmentOffset
= InUseEntry
->SegmentOffset
;
2755 /* Remember free size */
2756 FreeSize
= InUseEntry
->Size
- Index
;
2759 InUseEntry
->Size
= (USHORT
)Index
;
2760 InUseEntry
->Flags
&= ~HEAP_ENTRY_LAST_ENTRY
;
2762 /* Is that the last entry */
2763 if (FreeFlags
& HEAP_ENTRY_LAST_ENTRY
)
2765 /* Set its size and insert it to the list */
2766 SplitBlock
->Size
= (USHORT
)FreeSize
;
2767 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
2769 /* Update total free size */
2770 Heap
->TotalFreeSize
+= FreeSize
;
2774 /* Get the block after that one */
2775 SplitBlock2
= (PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
);
2777 if (SplitBlock2
->Flags
& HEAP_ENTRY_BUSY
)
2779 /* It's in use, add it here*/
2780 SplitBlock
->Size
= (USHORT
)FreeSize
;
2782 /* Update previous size of the next entry */
2783 ((PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
))->PreviousSize
= (USHORT
)FreeSize
;
2785 /* Insert it to the list */
2786 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
2788 /* Update total size */
2789 Heap
->TotalFreeSize
+= FreeSize
;
2793 /* Next entry is free, so merge with it */
2794 SplitBlock
->Flags
= SplitBlock2
->Flags
;
2796 /* Remove it, update total size */
2797 RtlpRemoveFreeBlock(Heap
, SplitBlock2
, FALSE
, FALSE
);
2798 Heap
->TotalFreeSize
-= SplitBlock2
->Size
;
2800 /* Calculate total free size */
2801 FreeSize
+= SplitBlock2
->Size
;
2803 if (FreeSize
<= HEAP_MAX_BLOCK_SIZE
)
2805 SplitBlock
->Size
= (USHORT
)FreeSize
;
2807 if (!(SplitBlock
->Flags
& HEAP_ENTRY_LAST_ENTRY
))
2809 /* Update previous size of the next entry */
2810 ((PHEAP_FREE_ENTRY
)((PHEAP_ENTRY
)SplitBlock
+ FreeSize
))->PreviousSize
= (USHORT
)FreeSize
;
2813 /* Insert the new one back and update total size */
2814 RtlpInsertFreeBlockHelper(Heap
, SplitBlock
, FreeSize
, FALSE
);
2815 Heap
->TotalFreeSize
+= FreeSize
;
2820 RtlpInsertFreeBlock(Heap
, SplitBlock
, FreeSize
);
2829 /* We're growing the block */
2830 if ((InUseEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
) ||
2831 !RtlpGrowBlockInPlace(Heap
, Flags
, InUseEntry
, Size
, Index
))
2833 /* Growing in place failed, so growing out of place */
2834 if (Flags
& HEAP_REALLOC_IN_PLACE_ONLY
)
2836 DPRINT1("Realloc in place failed, but it was the only option\n");
2841 /* Clear tag bits */
2842 Flags
&= ~HEAP_TAG_MASK
;
2844 /* Process extra stuff */
2845 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
2847 /* Preserve user settable flags */
2848 Flags
&= ~HEAP_SETTABLE_USER_FLAGS
;
2850 Flags
|= HEAP_SETTABLE_USER_VALUE
| ((InUseEntry
->Flags
& HEAP_ENTRY_SETTABLE_FLAGS
) << 4);
2852 /* Get pointer to the old extra data */
2853 OldExtra
= RtlpGetExtraStuffPointer(InUseEntry
);
2855 /* Save tag index if it was set */
2856 if (OldExtra
->TagIndex
&&
2857 !(OldExtra
->TagIndex
& HEAP_PSEUDO_TAG_FLAG
))
2859 Flags
|= OldExtra
->TagIndex
<< HEAP_TAG_SHIFT
;
2862 else if (InUseEntry
->SmallTagIndex
)
2864 /* Take small tag index into account */
2865 Flags
|= InUseEntry
->SmallTagIndex
<< HEAP_TAG_SHIFT
;
2868 /* Allocate new block from the heap */
2869 NewBaseAddress
= RtlAllocateHeap(HeapPtr
,
2870 Flags
& ~HEAP_ZERO_MEMORY
,
2873 /* Proceed if it didn't fail */
2876 /* Get new entry pointer */
2877 NewInUseEntry
= (PHEAP_ENTRY
)NewBaseAddress
- 1;
2879 /* Process extra stuff if it exists */
2880 if (NewInUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
2882 NewExtra
= RtlpGetExtraStuffPointer(NewInUseEntry
);
2884 if (InUseEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
)
2886 OldExtra
= RtlpGetExtraStuffPointer(InUseEntry
);
2887 NewExtra
->Settable
= OldExtra
->Settable
;
2891 RtlZeroMemory(NewExtra
, sizeof(*NewExtra
));
2895 /* Copy actual user bits */
2897 RtlMoveMemory(NewBaseAddress
, Ptr
, Size
);
2899 RtlMoveMemory(NewBaseAddress
, Ptr
, OldSize
);
2901 /* Zero remaining part if required */
2902 if (Size
> OldSize
&&
2903 (Flags
& HEAP_ZERO_MEMORY
))
2905 RtlZeroMemory((PCHAR
)NewBaseAddress
+ OldSize
, Size
- OldSize
);
2908 /* Free the old block */
2909 RtlFreeHeap(HeapPtr
, Flags
, Ptr
);
2912 Ptr
= NewBaseAddress
;
2917 /* Did resizing fail? */
2918 if (!Ptr
&& (Flags
& HEAP_GENERATE_EXCEPTIONS
))
2920 /* Generate an exception if required */
2921 ExceptionRecord
.ExceptionCode
= STATUS_NO_MEMORY
;
2922 ExceptionRecord
.ExceptionRecord
= NULL
;
2923 ExceptionRecord
.NumberParameters
= 1;
2924 ExceptionRecord
.ExceptionFlags
= 0;
2925 ExceptionRecord
.ExceptionInformation
[0] = AllocationSize
;
2927 RtlRaiseException(&ExceptionRecord
);
2930 /* Release the heap lock if it was acquired */
2932 RtlLeaveHeapLock(Heap
->LockVariable
);
2938 /***********************************************************************
2944 RtlCompactHeap(HANDLE Heap
,
2952 /***********************************************************************
2954 * Attempts to acquire the critical section object for a specified heap.
2957 * Heap [in] Handle of heap to lock for exclusive access
2966 RtlLockHeap(IN HANDLE HeapPtr
)
2968 PHEAP Heap
= (PHEAP
)HeapPtr
;
2970 // FIXME Check for special heap
2972 /* Check if it's really a heap */
2973 if (Heap
->Signature
!= HEAP_SIGNATURE
) return FALSE
;
2975 /* Lock if it's lockable */
2976 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
2978 RtlEnterHeapLock(Heap
->LockVariable
, TRUE
);
2985 /***********************************************************************
2987 * Releases ownership of the critical section object.
2990 * Heap [in] Handle to the heap to unlock
2999 RtlUnlockHeap(HANDLE HeapPtr
)
3001 PHEAP Heap
= (PHEAP
)HeapPtr
;
3003 // FIXME Check for special heap
3005 /* Check if it's really a heap */
3006 if (Heap
->Signature
!= HEAP_SIGNATURE
) return FALSE
;
3008 /* Unlock if it's lockable */
3009 if (!(Heap
->Flags
& HEAP_NO_SERIALIZE
))
3011 RtlLeaveHeapLock(Heap
->LockVariable
);
3018 /***********************************************************************
3021 * Heap [in] Handle of heap
3022 * Flags [in] Heap size control flags
3023 * Ptr [in] Address of memory to return size for
3026 * Size in bytes of allocated memory
3027 * 0xffffffff: Failure
3038 PHEAP Heap
= (PHEAP
)HeapPtr
;
3039 PHEAP_ENTRY HeapEntry
;
3042 // FIXME This is a hack around missing SEH support!
3045 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_HANDLE
);
3050 Flags
|= Heap
->ForceFlags
;
3052 /* Call special heap */
3053 if (RtlpHeapIsSpecial(Flags
))
3054 return RtlDebugSizeHeap(Heap
, Flags
, Ptr
);
3056 /* Get the heap entry pointer */
3057 HeapEntry
= (PHEAP_ENTRY
)Ptr
- 1;
3059 /* Return -1 if that entry is free */
3060 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
))
3062 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER
);
3066 /* Get size of this block depending if it's a usual or a big one */
3067 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
3069 EntrySize
= RtlpGetSizeOfBigBlock(HeapEntry
);
3074 EntrySize
= (HeapEntry
->Size
<< HEAP_ENTRY_SHIFT
) - HeapEntry
->UnusedBytes
;
3077 /* Return calculated size */
3082 RtlpCheckInUsePattern(PHEAP_ENTRY HeapEntry
)
3084 SIZE_T Size
, Result
;
3087 /* Calculate size */
3088 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
)
3089 Size
= RtlpGetSizeOfBigBlock(HeapEntry
);
3091 Size
= (HeapEntry
->Size
<< HEAP_ENTRY_SHIFT
) - HeapEntry
->UnusedBytes
;
3093 /* Calculate pointer to the tail part of the block */
3094 TailPart
= (PCHAR
)(HeapEntry
+ 1) + Size
;
3096 /* Compare tail pattern */
3097 Result
= RtlCompareMemory(TailPart
,
3101 if (Result
!= HEAP_ENTRY_SIZE
)
3103 DPRINT1("HEAP: Heap entry (size %x) %p tail is modified at %p\n", Size
, HeapEntry
, TailPart
+ Result
);
3112 RtlpValidateHeapHeaders(
3114 BOOLEAN Recalculate
)
3116 // We skip header validation for now
3121 RtlpValidateHeapEntry(
3123 PHEAP_ENTRY HeapEntry
)
3125 BOOLEAN BigAllocation
, EntryFound
= FALSE
;
3126 PHEAP_SEGMENT Segment
;
3127 ULONG SegmentOffset
;
3129 /* Perform various consistency checks of this entry */
3130 if (!HeapEntry
) goto invalid_entry
;
3131 if ((ULONG_PTR
)HeapEntry
& (HEAP_ENTRY_SIZE
- 1)) goto invalid_entry
;
3132 if (!(HeapEntry
->Flags
& HEAP_ENTRY_BUSY
)) goto invalid_entry
;
3134 BigAllocation
= HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
;
3135 Segment
= Heap
->Segments
[HeapEntry
->SegmentOffset
];
3137 if (BigAllocation
&&
3138 (((ULONG_PTR
)HeapEntry
& (PAGE_SIZE
- 1)) != FIELD_OFFSET(HEAP_VIRTUAL_ALLOC_ENTRY
, BusyBlock
)))
3141 if (!BigAllocation
&& (HeapEntry
->SegmentOffset
>= HEAP_SEGMENTS
||
3143 HeapEntry
< Segment
->FirstEntry
||
3144 HeapEntry
>= Segment
->LastValidEntry
))
3147 if ((HeapEntry
->Flags
& HEAP_ENTRY_FILL_PATTERN
) &&
3148 !RtlpCheckInUsePattern(HeapEntry
))
3151 /* Checks are done, if this is a virtual entry, that's all */
3152 if (HeapEntry
->Flags
& HEAP_ENTRY_VIRTUAL_ALLOC
) return TRUE
;
3154 /* Go through segments and check if this entry fits into any of them */
3155 for (SegmentOffset
= 0; SegmentOffset
< HEAP_SEGMENTS
; SegmentOffset
++)
3157 Segment
= Heap
->Segments
[SegmentOffset
];
3158 if (!Segment
) continue;
3160 if ((HeapEntry
>= Segment
->FirstEntry
) &&
3161 (HeapEntry
< Segment
->LastValidEntry
))
3169 /* Return our result of finding entry in the segments */
3173 DPRINT1("HEAP: Invalid heap entry %p in heap %p\n", HeapEntry
, Heap
);
3178 RtlpValidateHeapSegment(
3180 PHEAP_SEGMENT Segment
,
3181 UCHAR SegmentOffset
,
3182 PULONG FreeEntriesCount
,
3183 PSIZE_T TotalFreeSize
,
3185 PSIZE_T PseudoTagEntries
)
3187 PHEAP_UCR_DESCRIPTOR UcrDescriptor
;
3188 PLIST_ENTRY UcrEntry
;
3189 SIZE_T ByteSize
, Size
, Result
;
3190 PHEAP_ENTRY CurrentEntry
;
3191 ULONG UnCommittedPages
;
3192 ULONG UnCommittedRanges
;
3195 UnCommittedPages
= 0;
3196 UnCommittedRanges
= 0;
3198 if (IsListEmpty(&Segment
->UCRSegmentList
))
3201 UcrDescriptor
= NULL
;
3205 UcrEntry
= Segment
->UCRSegmentList
.Flink
;
3206 UcrDescriptor
= CONTAINING_RECORD(UcrEntry
, HEAP_UCR_DESCRIPTOR
, SegmentEntry
);
3209 if (Segment
->BaseAddress
== Heap
)
3210 CurrentEntry
= &Heap
->Entry
;
3212 CurrentEntry
= &Segment
->Entry
;
3214 while (CurrentEntry
< Segment
->LastValidEntry
)
3216 if (UcrDescriptor
&&
3217 ((PVOID
)CurrentEntry
>= UcrDescriptor
->Address
))
3219 DPRINT1("HEAP: Entry %p is not inside uncommited range [%p .. %p)\n",
3220 CurrentEntry
, UcrDescriptor
->Address
,
3221 (PCHAR
)UcrDescriptor
->Address
+ UcrDescriptor
->Size
);
3228 while (CurrentEntry
< Segment
->LastValidEntry
)
3230 if (PreviousSize
!= CurrentEntry
->PreviousSize
)
3232 DPRINT1("HEAP: Entry %p has incorrect PreviousSize %x instead of %x\n",
3233 CurrentEntry
, CurrentEntry
->PreviousSize
, PreviousSize
);
3238 PreviousSize
= CurrentEntry
->Size
;
3239 Size
= CurrentEntry
->Size
<< HEAP_ENTRY_SHIFT
;
3241 if (CurrentEntry
->Flags
& HEAP_ENTRY_BUSY
)
3248 /* Check fill pattern */
3249 if (CurrentEntry
->Flags
& HEAP_ENTRY_FILL_PATTERN
)
3251 if (!RtlpCheckInUsePattern(CurrentEntry
))
3257 /* The entry is free, increase free entries count and total free size */
3258 *FreeEntriesCount
= *FreeEntriesCount
+ 1;
3259 *TotalFreeSize
+= CurrentEntry
->Size
;
3261 if ((Heap
->Flags
& HEAP_FREE_CHECKING_ENABLED
) &&
3262 (CurrentEntry
->Flags
& HEAP_ENTRY_FILL_PATTERN
))
3264 ByteSize
= Size
- sizeof(HEAP_FREE_ENTRY
);
3266 if ((CurrentEntry
->Flags
& HEAP_ENTRY_EXTRA_PRESENT
) &&
3267 (ByteSize
> sizeof(HEAP_FREE_ENTRY_EXTRA
)))
3269 ByteSize
-= sizeof(HEAP_FREE_ENTRY_EXTRA
);
3272 Result
= RtlCompareMemoryUlong((PCHAR
)((PHEAP_FREE_ENTRY
)CurrentEntry
+ 1),
3276 if (Result
!= ByteSize
)
3278 DPRINT1("HEAP: Free heap block %p modified at %p after it was freed\n",
3280 (PCHAR
)(CurrentEntry
+ 1) + Result
);
3287 if (CurrentEntry
->SegmentOffset
!= SegmentOffset
)
3289 DPRINT1("HEAP: Heap entry %p SegmentOffset is incorrect %x (should be %x)\n",
3290 CurrentEntry
, SegmentOffset
, CurrentEntry
->SegmentOffset
);
3294 /* Check if it's the last entry */
3295 if (CurrentEntry
->Flags
& HEAP_ENTRY_LAST_ENTRY
)
3297 CurrentEntry
= (PHEAP_ENTRY
)((PCHAR
)CurrentEntry
+ Size
);
3301 /* Check if it's not really the last one */
3302 if (CurrentEntry
!= Segment
->LastValidEntry
)
3304 DPRINT1("HEAP: Heap entry %p is not last block in segment (%p)\n",
3305 CurrentEntry
, Segment
->LastValidEntry
);
3309 else if (CurrentEntry
!= UcrDescriptor
->Address
)
3311 DPRINT1("HEAP: Heap entry %p does not match next uncommitted address (%p)\n",
3312 CurrentEntry
, UcrDescriptor
->Address
);
3318 UnCommittedPages
+= (ULONG
)(UcrDescriptor
->Size
/ PAGE_SIZE
);
3319 UnCommittedRanges
++;
3321 CurrentEntry
= (PHEAP_ENTRY
)((PCHAR
)UcrDescriptor
->Address
+ UcrDescriptor
->Size
);
3323 /* Go to the next UCR descriptor */
3324 UcrEntry
= UcrEntry
->Flink
;
3325 if (UcrEntry
== &Segment
->UCRSegmentList
)
3328 UcrDescriptor
= NULL
;
3332 UcrDescriptor
= CONTAINING_RECORD(UcrEntry
, HEAP_UCR_DESCRIPTOR
, SegmentEntry
);
3339 /* Advance to the next entry */
3340 CurrentEntry
= (PHEAP_ENTRY
)((PCHAR
)CurrentEntry
+ Size
);
3344 /* Check total numbers of UCP and UCR */
3345 if (Segment
->NumberOfUnCommittedPages
!= UnCommittedPages
)
3347 DPRINT1("HEAP: Segment %p NumberOfUnCommittedPages is invalid (%x != %x)\n",
3348 Segment
, Segment
->NumberOfUnCommittedPages
, UnCommittedPages
);
3353 if (Segment
->NumberOfUnCommittedRanges
!= UnCommittedRanges
)
3355 DPRINT1("HEAP: Segment %p NumberOfUnCommittedRanges is invalid (%x != %x)\n",
3356 Segment
, Segment
->NumberOfUnCommittedRanges
, UnCommittedRanges
);
<