80be5bd3c58aadd11a898b4d23edc2607d4ec537
[reactos.git] / reactos / lib / rtl / heap.c
1 /*
2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS system libraries
4 * FILE: lib/rtl/heap.c
5 * PURPOSE: RTL Heap backend allocator
6 * PROGRAMMERS: Copyright 2010 Aleksey Bragin
7 */
8
9 /* Useful references:
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
17 */
18
19 /* INCLUDES *****************************************************************/
20
21 #include <rtl.h>
22 #include <heap.h>
23
24 #define NDEBUG
25 #include <debug.h>
26
27 /* Bitmaps stuff */
28
29 /* How many least significant bits are clear */
30 UCHAR RtlpBitsClearLow[] =
31 {
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
48 };
49
50 FORCEINLINE
51 UCHAR
52 RtlpFindLeastSetBit(ULONG Bits)
53 {
54 if (Bits & 0xFFFF)
55 {
56 if (Bits & 0xFF)
57 return RtlpBitsClearLow[Bits & 0xFF]; /* Lowest byte */
58 else
59 return RtlpBitsClearLow[(Bits >> 8) & 0xFF] + 8; /* 2nd byte */
60 }
61 else
62 {
63 if ((Bits >> 16) & 0xFF)
64 return RtlpBitsClearLow[(Bits >> 16) & 0xFF] + 16; /* 3rd byte */
65 else
66 return RtlpBitsClearLow[(Bits >> 24) & 0xFF] + 24; /* Highest byte */
67 }
68 }
69
70 /* Maximum size of a tail-filling pattern used for compare operation */
71 UCHAR FillPattern[HEAP_ENTRY_SIZE] =
72 {
73 HEAP_TAIL_FILL,
74 HEAP_TAIL_FILL,
75 HEAP_TAIL_FILL,
76 HEAP_TAIL_FILL,
77 HEAP_TAIL_FILL,
78 HEAP_TAIL_FILL,
79 HEAP_TAIL_FILL,
80 HEAP_TAIL_FILL
81 };
82
83 /* FUNCTIONS *****************************************************************/
84
85 NTSTATUS NTAPI
86 RtlpInitializeHeap(OUT PHEAP Heap,
87 IN ULONG Flags,
88 IN PHEAP_LOCK Lock OPTIONAL,
89 IN PRTL_HEAP_PARAMETERS Parameters)
90 {
91 ULONG NumUCRs = 8;
92 ULONG Index;
93 SIZE_T HeaderSize;
94 NTSTATUS Status;
95 PHEAP_UCR_DESCRIPTOR UcrDescriptor;
96
97 /* Preconditions */
98 ASSERT(Heap != NULL);
99 ASSERT(Parameters != NULL);
100 ASSERT(!(Flags & HEAP_LOCK_USER_ALLOCATED));
101 ASSERT(!(Flags & HEAP_NO_SERIALIZE) || (Lock == NULL)); /* HEAP_NO_SERIALIZE => no lock */
102
103 /* Start out with the size of a plain Heap header */
104 HeaderSize = ROUND_UP(sizeof(HEAP), sizeof(HEAP_ENTRY));
105
106 /* Check if space needs to be added for the Heap Lock */
107 if (!(Flags & HEAP_NO_SERIALIZE))
108 {
109 if (Lock != NULL)
110 /* The user manages the Heap Lock */
111 Flags |= HEAP_LOCK_USER_ALLOCATED;
112 else
113 if (RtlpGetMode() == UserMode)
114 {
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));
118 }
119 }
120
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));
124
125 /* Sanity check */
126 ASSERT(HeaderSize <= PAGE_SIZE);
127
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;
135
136 /* Initialise the Heap header */
137 Heap->Signature = HEAP_SIGNATURE;
138 Heap->Flags = Flags;
139 Heap->ForceFlags = (Flags & (HEAP_NO_SERIALIZE |
140 HEAP_GENERATE_EXCEPTIONS |
141 HEAP_ZERO_MEMORY |
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));
148
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;
157
158 /* Initialise the Heap validation info */
159 Heap->HeaderValidateCopy = NULL;
160 Heap->HeaderValidateLength = (USHORT)HeaderSize;
161
162 /* Initialise the Heap Lock */
163 if (!(Flags & HEAP_NO_SERIALIZE) && !(Flags & HEAP_LOCK_USER_ALLOCATED))
164 {
165 Status = RtlInitializeHeapLock(&Lock);
166 if (!NT_SUCCESS(Status))
167 return Status;
168 }
169 Heap->LockVariable = Lock;
170
171 /* Initialise the Heap alignment info */
172 if (Flags & HEAP_CREATE_ALIGN_16)
173 {
174 Heap->AlignMask = (ULONG) ~15;
175 Heap->AlignRound = 15 + sizeof(HEAP_ENTRY);
176 }
177 else
178 {
179 Heap->AlignMask = (ULONG) ~(sizeof(HEAP_ENTRY) - 1);
180 Heap->AlignRound = 2 * sizeof(HEAP_ENTRY) - 1;
181 }
182
183 if (Flags & HEAP_TAIL_CHECKING_ENABLED)
184 Heap->AlignRound += sizeof(HEAP_ENTRY);
185
186 /* Initialise the Heap Segment list */
187 for (Index = 0; Index < HEAP_SEGMENTS; ++Index)
188 Heap->Segments[Index] = NULL;
189
190 /* Initialise the Heap Free Heap Entry lists */
191 for (Index = 0; Index < HEAP_FREELISTS; ++Index)
192 InitializeListHead(&Heap->FreeLists[Index]);
193
194 /* Initialise the Heap Virtual Allocated Blocks list */
195 InitializeListHead(&Heap->VirtualAllocdBlocks);
196
197 /* Initialise the Heap UnCommitted Region lists */
198 InitializeListHead(&Heap->UCRSegments);
199 InitializeListHead(&Heap->UCRList);
200
201 /* Register the initial Heap UnCommitted Region Descriptors */
202 for (Index = 0; Index < NumUCRs; ++Index)
203 InsertTailList(&Heap->UCRList, &UcrDescriptor[Index].ListEntry);
204
205 return STATUS_SUCCESS;
206 }
207
208 FORCEINLINE
209 VOID
210 RtlpSetFreeListsBit(PHEAP Heap,
211 PHEAP_FREE_ENTRY FreeEntry)
212 {
213 ULONG Index, Bit;
214
215 ASSERT(FreeEntry->Size < HEAP_FREELISTS);
216
217 /* Calculate offset in the free list bitmap */
218 Index = FreeEntry->Size >> 3; /* = FreeEntry->Size / (sizeof(UCHAR) * 8)*/
219 Bit = 1 << (FreeEntry->Size & 7);
220
221 /* Assure it's not already set */
222 ASSERT((Heap->u.FreeListsInUseBytes[Index] & Bit) == 0);
223
224 /* Set it */
225 Heap->u.FreeListsInUseBytes[Index] |= Bit;
226 }
227
228 FORCEINLINE
229 VOID
230 RtlpClearFreeListsBit(PHEAP Heap,
231 PHEAP_FREE_ENTRY FreeEntry)
232 {
233 ULONG Index, Bit;
234
235 ASSERT(FreeEntry->Size < HEAP_FREELISTS);
236
237 /* Calculate offset in the free list bitmap */
238 Index = FreeEntry->Size >> 3; /* = FreeEntry->Size / (sizeof(UCHAR) * 8)*/
239 Bit = 1 << (FreeEntry->Size & 7);
240
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]));
244
245 /* Clear it */
246 Heap->u.FreeListsInUseBytes[Index] ^= Bit;
247 }
248
249 VOID NTAPI
250 RtlpInsertFreeBlockHelper(PHEAP Heap,
251 PHEAP_FREE_ENTRY FreeEntry,
252 SIZE_T BlockSize,
253 BOOLEAN NoFill)
254 {
255 PLIST_ENTRY FreeListHead, Current;
256 PHEAP_FREE_ENTRY CurrentEntry;
257
258 ASSERT(FreeEntry->Size == BlockSize);
259
260 /* Fill if it's not denied */
261 if (!NoFill)
262 {
263 FreeEntry->Flags &= ~(HEAP_ENTRY_FILL_PATTERN |
264 HEAP_ENTRY_EXTRA_PRESENT |
265 HEAP_ENTRY_BUSY);
266
267 if (Heap->Flags & HEAP_FREE_CHECKING_ENABLED)
268 {
269 RtlFillMemoryUlong((PCHAR)(FreeEntry + 1),
270 (BlockSize << HEAP_ENTRY_SHIFT) - sizeof(*FreeEntry),
271 ARENA_FREE_FILLER);
272
273 FreeEntry->Flags |= HEAP_ENTRY_FILL_PATTERN;
274 }
275 }
276 else
277 {
278 /* Clear out all flags except the last entry one */
279 FreeEntry->Flags &= HEAP_ENTRY_LAST_ENTRY;
280 }
281
282 /* Insert it either into dedicated or non-dedicated list */
283 if (BlockSize < HEAP_FREELISTS)
284 {
285 /* Dedicated list */
286 FreeListHead = &Heap->FreeLists[BlockSize];
287
288 if (IsListEmpty(FreeListHead))
289 {
290 RtlpSetFreeListsBit(Heap, FreeEntry);
291 }
292 }
293 else
294 {
295 /* Non-dedicated one */
296 FreeListHead = &Heap->FreeLists[0];
297 Current = FreeListHead->Flink;
298
299 /* Find a position where to insert it to (the list must be sorted) */
300 while (FreeListHead != Current)
301 {
302 CurrentEntry = CONTAINING_RECORD(Current, HEAP_FREE_ENTRY, FreeList);
303
304 if (BlockSize <= CurrentEntry->Size)
305 break;
306
307 Current = Current->Flink;
308 }
309
310 FreeListHead = Current;
311 }
312
313 /* Actually insert it into the list */
314 InsertTailList(FreeListHead, &FreeEntry->FreeList);
315 }
316
317 VOID NTAPI
318 RtlpInsertFreeBlock(PHEAP Heap,
319 PHEAP_FREE_ENTRY FreeEntry,
320 SIZE_T BlockSize)
321 {
322 USHORT Size, PreviousSize;
323 UCHAR SegmentOffset, Flags;
324 PHEAP_SEGMENT Segment;
325
326 DPRINT("RtlpInsertFreeBlock(%p %p %x)\n", Heap, FreeEntry, BlockSize);
327
328 /* Increase the free size counter */
329 Heap->TotalFreeSize += BlockSize;
330
331 /* Remember certain values */
332 Flags = FreeEntry->Flags;
333 PreviousSize = FreeEntry->PreviousSize;
334 SegmentOffset = FreeEntry->SegmentOffset;
335 Segment = Heap->Segments[SegmentOffset];
336
337 /* Process it */
338 while (BlockSize)
339 {
340 /* Check for the max size */
341 if (BlockSize > HEAP_MAX_BLOCK_SIZE)
342 {
343 Size = HEAP_MAX_BLOCK_SIZE;
344
345 /* Special compensation if it goes above limit just by 1 */
346 if (BlockSize == (HEAP_MAX_BLOCK_SIZE + 1))
347 Size -= 16;
348
349 FreeEntry->Flags = 0;
350 }
351 else
352 {
353 Size = (USHORT)BlockSize;
354 FreeEntry->Flags = Flags;
355 }
356
357 /* Change its size and insert it into a free list */
358 FreeEntry->Size = Size;
359 FreeEntry->PreviousSize = PreviousSize;
360 FreeEntry->SegmentOffset = SegmentOffset;
361
362 /* Call a helper to actually insert the block */
363 RtlpInsertFreeBlockHelper(Heap, FreeEntry, Size, FALSE);
364
365 /* Update sizes */
366 PreviousSize = Size;
367 BlockSize -= Size;
368
369 /* Go to the next entry */
370 FreeEntry = (PHEAP_FREE_ENTRY)((PHEAP_ENTRY)FreeEntry + Size);
371
372 /* Check if that's all */
373 if ((PHEAP_ENTRY)FreeEntry >= Segment->LastValidEntry) return;
374 }
375
376 /* Update previous size if needed */
377 if (!(Flags & HEAP_ENTRY_LAST_ENTRY))
378 FreeEntry->PreviousSize = PreviousSize;
379 }
380
381 VOID NTAPI
382 RtlpRemoveFreeBlock(PHEAP Heap,
383 PHEAP_FREE_ENTRY FreeEntry,
384 BOOLEAN Dedicated,
385 BOOLEAN NoFill)
386 {
387 SIZE_T Result, RealSize;
388
389 /* Remove the free block and update the freelists bitmap */
390 if (RemoveEntryList(&FreeEntry->FreeList) &&
391 (Dedicated || (!Dedicated && FreeEntry->Size < HEAP_FREELISTS)))
392 {
393 RtlpClearFreeListsBit(Heap, FreeEntry);
394 }
395
396 /* Fill with pattern if necessary */
397 if (!NoFill &&
398 (FreeEntry->Flags & HEAP_ENTRY_FILL_PATTERN))
399 {
400 RealSize = (FreeEntry->Size << HEAP_ENTRY_SHIFT) - sizeof(*FreeEntry);
401
402 /* Deduct extra stuff from block's real size */
403 if (FreeEntry->Flags & HEAP_ENTRY_EXTRA_PRESENT &&
404 RealSize > sizeof(HEAP_FREE_ENTRY_EXTRA))
405 {
406 RealSize -= sizeof(HEAP_FREE_ENTRY_EXTRA);
407 }
408
409 /* Check if the free filler is intact */
410 Result = RtlCompareMemoryUlong((PCHAR)(FreeEntry + 1),
411 RealSize,
412 ARENA_FREE_FILLER);
413
414 if (Result != RealSize)
415 {
416 DPRINT1("Free heap block %p modified at %p after it was freed\n",
417 FreeEntry,
418 (PCHAR)(FreeEntry + 1) + Result);
419 }
420 }
421 }
422
423 SIZE_T NTAPI
424 RtlpGetSizeOfBigBlock(PHEAP_ENTRY HeapEntry)
425 {
426 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry;
427
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));
431
432 /* Restore the real size */
433 return VirtualEntry->CommitSize - HeapEntry->Size;
434 }
435
436 PHEAP_UCR_DESCRIPTOR NTAPI
437 RtlpCreateUnCommittedRange(PHEAP_SEGMENT Segment)
438 {
439 PLIST_ENTRY Entry;
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;
445 NTSTATUS Status;
446
447 DPRINT("RtlpCreateUnCommittedRange(%p)\n", Segment);
448
449 /* Check if we have unused UCRs */
450 if (IsListEmpty(&Heap->UCRList))
451 {
452 /* Get a pointer to the first UCR segment */
453 UcrSegment = CONTAINING_RECORD(Heap->UCRSegments.Flink, HEAP_UCR_SEGMENT, ListEntry);
454
455 /* Check the list of UCR segments */
456 if (IsListEmpty(&Heap->UCRSegments) ||
457 UcrSegment->ReservedSize == UcrSegment->CommittedSize)
458 {
459 /* We need to create a new one. Reserve 16 pages for it */
460 UcrSegment = NULL;
461 Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
462 (PVOID *)&UcrSegment,
463 0,
464 &ReserveSize,
465 MEM_RESERVE,
466 PAGE_READWRITE);
467
468 if (!NT_SUCCESS(Status)) return NULL;
469
470 /* Commit one page */
471 Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
472 (PVOID *)&UcrSegment,
473 0,
474 &CommitSize,
475 MEM_COMMIT,
476 PAGE_READWRITE);
477
478 if (!NT_SUCCESS(Status))
479 {
480 /* Release reserved memory */
481 ZwFreeVirtualMemory(NtCurrentProcess(),
482 (PVOID *)&UcrSegment,
483 &ReserveSize,
484 MEM_RELEASE);
485 return NULL;
486 }
487
488 /* Set it's data */
489 UcrSegment->ReservedSize = ReserveSize;
490 UcrSegment->CommittedSize = CommitSize;
491
492 /* Add it to the head of the list */
493 InsertHeadList(&Heap->UCRSegments, &UcrSegment->ListEntry);
494
495 /* Get a pointer to the first available UCR descriptor */
496 UcrDescriptor = (PHEAP_UCR_DESCRIPTOR)(UcrSegment + 1);
497 }
498 else
499 {
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,
504 0,
505 &CommitSize,
506 MEM_COMMIT,
507 PAGE_READWRITE);
508
509 if (!NT_SUCCESS(Status)) return NULL;
510
511 /* Update sizes */
512 UcrSegment->CommittedSize += CommitSize;
513 }
514
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)
517 {
518 InsertTailList(&Heap->UCRList, &UcrDescriptor->ListEntry);
519 UcrDescriptor++;
520 }
521 }
522
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;
527 }
528
529 VOID NTAPI
530 RtlpDestroyUnCommittedRange(PHEAP_SEGMENT Segment,
531 PHEAP_UCR_DESCRIPTOR UcrDescriptor)
532 {
533 /* Zero it out */
534 UcrDescriptor->Address = NULL;
535 UcrDescriptor->Size = 0;
536
537 /* Put it into the heap's list of unused UCRs */
538 InsertHeadList(&Segment->Heap->UCRList, &UcrDescriptor->ListEntry);
539 }
540
541 VOID NTAPI
542 RtlpInsertUnCommittedPages(PHEAP_SEGMENT Segment,
543 ULONG_PTR Address,
544 SIZE_T Size)
545 {
546 PLIST_ENTRY Current;
547 PHEAP_UCR_DESCRIPTOR UcrDescriptor;
548
549 DPRINT("RtlpInsertUnCommittedPages(%p %08Ix %Ix)\n", Segment, Address, Size);
550
551 /* Go through the list of UCR descriptors, they are sorted from lowest address
552 to the highest */
553 Current = Segment->UCRSegmentList.Flink;
554 while (Current != &Segment->UCRSegmentList)
555 {
556 UcrDescriptor = CONTAINING_RECORD(Current, HEAP_UCR_DESCRIPTOR, SegmentEntry);
557
558 if ((ULONG_PTR)UcrDescriptor->Address > Address)
559 {
560 /* Check for a really lucky case */
561 if ((Address + Size) == (ULONG_PTR)UcrDescriptor->Address)
562 {
563 /* Exact match */
564 UcrDescriptor->Address = (PVOID)Address;
565 UcrDescriptor->Size += Size;
566 return;
567 }
568
569 /* We found the block before which the new one should go */
570 break;
571 }
572 else if (((ULONG_PTR)UcrDescriptor->Address + UcrDescriptor->Size) == Address)
573 {
574 /* Modify this entry */
575 Address = (ULONG_PTR)UcrDescriptor->Address;
576 Size += UcrDescriptor->Size;
577
578 /* Advance to the next descriptor */
579 Current = Current->Flink;
580
581 /* Remove the current descriptor from the list and destroy it */
582 RemoveEntryList(&UcrDescriptor->SegmentEntry);
583 RtlpDestroyUnCommittedRange(Segment, UcrDescriptor);
584
585 Segment->NumberOfUnCommittedRanges--;
586 }
587 else
588 {
589 /* Advance to the next descriptor */
590 Current = Current->Flink;
591 }
592 }
593
594 /* Create a new UCR descriptor */
595 UcrDescriptor = RtlpCreateUnCommittedRange(Segment);
596 if (!UcrDescriptor) return;
597
598 UcrDescriptor->Address = (PVOID)Address;
599 UcrDescriptor->Size = Size;
600
601 /* "Current" is the descriptor before which our one should go */
602 InsertTailList(Current, &UcrDescriptor->SegmentEntry);
603
604 DPRINT("Added segment UCR with base %08Ix, size 0x%x\n", Address, Size);
605
606 /* Increase counters */
607 Segment->NumberOfUnCommittedRanges++;
608 }
609
610 PHEAP_FREE_ENTRY NTAPI
611 RtlpFindAndCommitPages(PHEAP Heap,
612 PHEAP_SEGMENT Segment,
613 PSIZE_T Size,
614 PVOID AddressRequested)
615 {
616 PLIST_ENTRY Current;
617 ULONG_PTR Address = 0;
618 PHEAP_UCR_DESCRIPTOR UcrDescriptor, PreviousUcr = NULL;
619 PHEAP_ENTRY FirstEntry, LastEntry;
620 NTSTATUS Status;
621
622 DPRINT("RtlpFindAndCommitPages(%p %p %Ix %08Ix)\n", Heap, Segment, *Size, Address);
623
624 /* Go through UCRs in a segment */
625 Current = Segment->UCRSegmentList.Flink;
626 while (Current != &Segment->UCRSegmentList)
627 {
628 UcrDescriptor = CONTAINING_RECORD(Current, HEAP_UCR_DESCRIPTOR, SegmentEntry);
629
630 /* Check if we can use that one right away */
631 if (UcrDescriptor->Size >= *Size &&
632 (UcrDescriptor->Address == AddressRequested || !AddressRequested))
633 {
634 /* Get the address */
635 Address = (ULONG_PTR)UcrDescriptor->Address;
636
637 /* Commit it */
638 if (Heap->CommitRoutine)
639 {
640 Status = Heap->CommitRoutine(Heap, (PVOID *)&Address, Size);
641 }
642 else
643 {
644 Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
645 (PVOID *)&Address,
646 0,
647 Size,
648 MEM_COMMIT,
649 PAGE_READWRITE);
650 }
651
652 DPRINT("Committed %Iu bytes at base %08Ix, UCR size is %lu\n", *Size, Address, UcrDescriptor->Size);
653
654 /* Fail in unsuccessful case */
655 if (!NT_SUCCESS(Status))
656 {
657 DPRINT1("Committing page failed with status 0x%08X\n", Status);
658 return NULL;
659 }
660
661 /* Update tracking numbers */
662 Segment->NumberOfUnCommittedPages -= (ULONG)(*Size / PAGE_SIZE);
663
664 /* Calculate first and last entries */
665 FirstEntry = (PHEAP_ENTRY)Address;
666
667 /* Go through the entries to find the last one */
668 if (PreviousUcr)
669 LastEntry = (PHEAP_ENTRY)((ULONG_PTR)PreviousUcr->Address + PreviousUcr->Size);
670 else
671 LastEntry = &Segment->Entry;
672
673 while (!(LastEntry->Flags & HEAP_ENTRY_LAST_ENTRY))
674 {
675 ASSERT(LastEntry->Size != 0);
676 LastEntry += LastEntry->Size;
677 }
678 ASSERT((LastEntry + LastEntry->Size) == FirstEntry);
679
680 /* Unmark it as a last entry */
681 LastEntry->Flags &= ~HEAP_ENTRY_LAST_ENTRY;
682
683 /* Update UCR descriptor */
684 UcrDescriptor->Address = (PVOID)((ULONG_PTR)UcrDescriptor->Address + *Size);
685 UcrDescriptor->Size -= *Size;
686
687 DPRINT("Updating UcrDescriptor %p, new Address %p, size %lu\n",
688 UcrDescriptor, UcrDescriptor->Address, UcrDescriptor->Size);
689
690 /* Set various first entry fields */
691 FirstEntry->SegmentOffset = LastEntry->SegmentOffset;
692 FirstEntry->Size = (USHORT)(*Size >> HEAP_ENTRY_SHIFT);
693 FirstEntry->PreviousSize = LastEntry->Size;
694
695 /* Check if anything left in this UCR */
696 if (UcrDescriptor->Size == 0)
697 {
698 /* It's fully exhausted */
699
700 /* Check if this is the end of the segment */
701 if(UcrDescriptor->Address == Segment->LastValidEntry)
702 {
703 FirstEntry->Flags = HEAP_ENTRY_LAST_ENTRY;
704 }
705 else
706 {
707 FirstEntry->Flags = 0;
708 /* Update field of next entry */
709 ASSERT((FirstEntry + FirstEntry->Size)->PreviousSize == 0);
710 (FirstEntry + FirstEntry->Size)->PreviousSize = FirstEntry->Size;
711 }
712
713 /* This UCR needs to be removed because it became useless */
714 RemoveEntryList(&UcrDescriptor->SegmentEntry);
715
716 RtlpDestroyUnCommittedRange(Segment, UcrDescriptor);
717 Segment->NumberOfUnCommittedRanges--;
718 }
719 else
720 {
721 FirstEntry->Flags = HEAP_ENTRY_LAST_ENTRY;
722 }
723
724 /* We're done */
725 return (PHEAP_FREE_ENTRY)FirstEntry;
726 }
727
728 /* Advance to the next descriptor */
729 PreviousUcr = UcrDescriptor;
730 Current = Current->Flink;
731 }
732
733 return NULL;
734 }
735
736 VOID NTAPI
737 RtlpDeCommitFreeBlock(PHEAP Heap,
738 PHEAP_FREE_ENTRY FreeEntry,
739 SIZE_T Size)
740 {
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;
747 NTSTATUS Status;
748
749 DPRINT("Decommitting %p %p %x\n", Heap, FreeEntry, Size);
750
751 /* We can't decommit if there is a commit routine! */
752 if (Heap->CommitRoutine)
753 {
754 /* Just add it back the usual way */
755 RtlpInsertFreeBlock(Heap, FreeEntry, Size);
756 return;
757 }
758
759 /* Get the segment */
760 Segment = Heap->Segments[FreeEntry->SegmentOffset];
761
762 /* Get the preceding entry */
763 DecommitBase = ROUND_UP(FreeEntry, PAGE_SIZE);
764 PrecedingSize = (PHEAP_ENTRY)DecommitBase - (PHEAP_ENTRY)FreeEntry;
765
766 if (PrecedingSize == 1)
767 {
768 /* Just 1 heap entry, increase the base/size */
769 DecommitBase += PAGE_SIZE;
770 PrecedingSize += PAGE_SIZE >> HEAP_ENTRY_SHIFT;
771 }
772 else if (FreeEntry->PreviousSize &&
773 (DecommitBase == (ULONG_PTR)FreeEntry))
774 {
775 PrecedingInUseEntry = (PHEAP_ENTRY)FreeEntry - FreeEntry->PreviousSize;
776 }
777
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;
782
783 if (NextSize == 1)
784 {
785 /* Just 1 heap entry, increase the size */
786 DecommitSize -= PAGE_SIZE;
787 NextSize += PAGE_SIZE >> HEAP_ENTRY_SHIFT;
788 }
789 else if (NextSize == 0 &&
790 !(FreeEntry->Flags & HEAP_ENTRY_LAST_ENTRY))
791 {
792 NextInUseEntry = (PHEAP_ENTRY)NextFreeEntry;
793 }
794
795 NextFreeEntry = (PHEAP_FREE_ENTRY)((PHEAP_ENTRY)NextFreeEntry - NextSize);
796
797 /* Calculate real decommit size */
798 if (DecommitSize > DecommitBase)
799 {
800 DecommitSize -= DecommitBase;
801 }
802 else
803 {
804 /* Nothing to decommit */
805 RtlpInsertFreeBlock(Heap, FreeEntry, Size);
806 return;
807 }
808
809 /* A decommit is necessary. Create a UCR descriptor */
810 UcrDescriptor = RtlpCreateUnCommittedRange(Segment);
811 if (!UcrDescriptor)
812 {
813 DPRINT1("HEAP: Failed to create UCR descriptor\n");
814 RtlpInsertFreeBlock(Heap, FreeEntry, PrecedingSize);
815 return;
816 }
817
818 /* Decommit the memory */
819 Status = ZwFreeVirtualMemory(NtCurrentProcess(),
820 (PVOID *)&DecommitBase,
821 &DecommitSize,
822 MEM_DECOMMIT);
823
824 /* Delete that UCR. This is needed to assure there is an unused UCR entry in the list */
825 RtlpDestroyUnCommittedRange(Segment, UcrDescriptor);
826
827 if (!NT_SUCCESS(Status))
828 {
829 RtlpInsertFreeBlock(Heap, FreeEntry, Size);
830 return;
831 }
832
833 /* Insert uncommitted pages */
834 RtlpInsertUnCommittedPages(Segment, DecommitBase, DecommitSize);
835 Segment->NumberOfUnCommittedPages += (ULONG)(DecommitSize / PAGE_SIZE);
836
837 if (PrecedingSize)
838 {
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;
843
844 /* Insert it into the free list */
845 RtlpInsertFreeBlockHelper(Heap, FreeEntry, PrecedingSize, FALSE);
846 }
847 else if (PrecedingInUseEntry)
848 {
849 /* Adjust preceding in use entry */
850 PrecedingInUseEntry->Flags |= HEAP_ENTRY_LAST_ENTRY;
851 }
852
853 /* Now the next one */
854 if (NextSize)
855 {
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;
861
862 ((PHEAP_FREE_ENTRY)((PHEAP_ENTRY)NextFreeEntry + NextSize))->PreviousSize = (USHORT)NextSize;
863
864 Heap->TotalFreeSize += NextSize;
865 RtlpInsertFreeBlockHelper(Heap, NextFreeEntry, NextSize, FALSE);
866 }
867 else if (NextInUseEntry)
868 {
869 NextInUseEntry->PreviousSize = 0;
870 }
871 }
872
873 NTSTATUS
874 NTAPI
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)
881 {
882 PHEAP_ENTRY HeapEntry;
883
884 /* Preconditions */
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);
891
892 DPRINT("RtlpInitializeHeapSegment(%p %p %x %x %lx %lx)\n", Heap, Segment, SegmentIndex, SegmentFlags, SegmentReserve, SegmentCommit);
893
894 /* Initialise the Heap Entry header if this is not the first Heap Segment */
895 if ((PHEAP_SEGMENT) (Heap) != Segment)
896 {
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;
903 }
904
905 /* Sanity check */
906 ASSERT((Segment->Entry.Size << HEAP_ENTRY_SHIFT) <= PAGE_SIZE);
907
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;
913
914 /* Initialise the Heap Segment location information */
915 Segment->BaseAddress = Segment;
916 Segment->NumberOfPages = (ULONG)(SegmentReserve >> PAGE_SHIFT);
917
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);
921
922 if (((SIZE_T)Segment->Entry.Size << HEAP_ENTRY_SHIFT) < SegmentCommit)
923 {
924 HeapEntry = Segment->FirstEntry;
925
926 /* Prepare a Free Heap Entry header */
927 HeapEntry->Flags = HEAP_ENTRY_LAST_ENTRY;
928 HeapEntry->PreviousSize = Segment->Entry.Size;
929 HeapEntry->SegmentOffset = SegmentIndex;
930
931 /* Register the Free Heap Entry */
932 RtlpInsertFreeBlock(Heap, (PHEAP_FREE_ENTRY) HeapEntry, (SegmentCommit >> HEAP_ENTRY_SHIFT) - Segment->Entry.Size);
933 }
934
935 /* Initialise the Heap Segment UnCommitted Range information */
936 Segment->NumberOfUnCommittedPages = (ULONG)((SegmentReserve - SegmentCommit) >> PAGE_SHIFT);
937 Segment->NumberOfUnCommittedRanges = 0;
938 InitializeListHead(&Segment->UCRSegmentList);
939
940 /* Register the UnCommitted Range of the Heap Segment */
941 if (Segment->NumberOfUnCommittedPages != 0)
942 RtlpInsertUnCommittedPages(Segment, (ULONG_PTR) (Segment) + SegmentCommit, SegmentReserve - SegmentCommit);
943
944 return STATUS_SUCCESS;
945 }
946
947 VOID NTAPI
948 RtlpDestroyHeapSegment(PHEAP_SEGMENT Segment)
949 {
950 NTSTATUS Status;
951 PVOID BaseAddress;
952 SIZE_T Size = 0;
953
954 /* Make sure it's not user allocated */
955 if (Segment->SegmentFlags & HEAP_USER_ALLOCATED) return;
956
957 BaseAddress = Segment->BaseAddress;
958 DPRINT("Destroying segment %p, BA %p\n", Segment, BaseAddress);
959
960 /* Release virtual memory */
961 Status = ZwFreeVirtualMemory(NtCurrentProcess(),
962 &BaseAddress,
963 &Size,
964 MEM_RELEASE);
965
966 if (!NT_SUCCESS(Status))
967 {
968 DPRINT1("HEAP: Failed to release segment's memory with status 0x%08X\n", Status);
969 }
970 }
971
972 PHEAP_FREE_ENTRY NTAPI
973 RtlpCoalesceHeap(PHEAP Heap)
974 {
975 UNIMPLEMENTED;
976 return NULL;
977 }
978
979 PHEAP_FREE_ENTRY NTAPI
980 RtlpCoalesceFreeBlocks (PHEAP Heap,
981 PHEAP_FREE_ENTRY FreeEntry,
982 PSIZE_T FreeSize,
983 BOOLEAN Remove)
984 {
985 PHEAP_FREE_ENTRY CurrentEntry, NextEntry;
986
987 /* Get the previous entry */
988 CurrentEntry = (PHEAP_FREE_ENTRY)((PHEAP_ENTRY)FreeEntry - FreeEntry->PreviousSize);
989
990 /* Check it */
991 if (CurrentEntry != FreeEntry &&
992 !(CurrentEntry->Flags & HEAP_ENTRY_BUSY) &&
993 (*FreeSize + CurrentEntry->Size) <= HEAP_MAX_BLOCK_SIZE)
994 {
995 ASSERT(FreeEntry->PreviousSize == CurrentEntry->Size);
996
997 /* Remove it if asked for */
998 if (Remove)
999 {
1000 RtlpRemoveFreeBlock(Heap, FreeEntry, FALSE, FALSE);
1001 Heap->TotalFreeSize -= FreeEntry->Size;
1002
1003 /* Remove it only once! */
1004 Remove = FALSE;
1005 }
1006
1007 /* Remove previous entry too */
1008 RtlpRemoveFreeBlock(Heap, CurrentEntry, FALSE, FALSE);
1009
1010 /* Copy flags */
1011 CurrentEntry->Flags = FreeEntry->Flags & HEAP_ENTRY_LAST_ENTRY;
1012
1013 /* Advance FreeEntry and update sizes */
1014 FreeEntry = CurrentEntry;
1015 *FreeSize = *FreeSize + CurrentEntry->Size;
1016 Heap->TotalFreeSize -= CurrentEntry->Size;
1017 FreeEntry->Size = (USHORT)(*FreeSize);
1018
1019 /* Also update previous size if needed */
1020 if (!(FreeEntry->Flags & HEAP_ENTRY_LAST_ENTRY))
1021 {
1022 ((PHEAP_ENTRY)FreeEntry + *FreeSize)->PreviousSize = (USHORT)(*FreeSize);
1023 }
1024 }
1025
1026 /* Check the next block if it exists */
1027 if (!(FreeEntry->Flags & HEAP_ENTRY_LAST_ENTRY))
1028 {
1029 NextEntry = (PHEAP_FREE_ENTRY)((PHEAP_ENTRY)FreeEntry + *FreeSize);
1030
1031 if (!(NextEntry->Flags & HEAP_ENTRY_BUSY) &&
1032 NextEntry->Size + *FreeSize <= HEAP_MAX_BLOCK_SIZE)
1033 {
1034 ASSERT(*FreeSize == NextEntry->PreviousSize);
1035
1036 /* Remove it if asked for */
1037 if (Remove)
1038 {
1039 RtlpRemoveFreeBlock(Heap, FreeEntry, FALSE, FALSE);
1040 Heap->TotalFreeSize -= FreeEntry->Size;
1041 }
1042
1043 /* Copy flags */
1044 FreeEntry->Flags = NextEntry->Flags & HEAP_ENTRY_LAST_ENTRY;
1045
1046 /* Remove next entry now */
1047 RtlpRemoveFreeBlock(Heap, NextEntry, FALSE, FALSE);
1048
1049 /* Update sizes */
1050 *FreeSize = *FreeSize + NextEntry->Size;
1051 Heap->TotalFreeSize -= NextEntry->Size;
1052 FreeEntry->Size = (USHORT)(*FreeSize);
1053
1054 /* Also update previous size if needed */
1055 if (!(FreeEntry->Flags & HEAP_ENTRY_LAST_ENTRY))
1056 {
1057 ((PHEAP_ENTRY)FreeEntry + *FreeSize)->PreviousSize = (USHORT)(*FreeSize);
1058 }
1059 }
1060 }
1061 return FreeEntry;
1062 }
1063
1064 PHEAP_FREE_ENTRY NTAPI
1065 RtlpExtendHeap(PHEAP Heap,
1066 SIZE_T Size)
1067 {
1068 ULONG Pages;
1069 UCHAR Index, EmptyIndex;
1070 SIZE_T FreeSize, CommitSize, ReserveSize;
1071 PHEAP_SEGMENT Segment;
1072 PHEAP_FREE_ENTRY FreeEntry;
1073 NTSTATUS Status;
1074
1075 DPRINT("RtlpExtendHeap(%p %x)\n", Heap, Size);
1076
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);
1081
1082 /* Find an empty segment */
1083 EmptyIndex = HEAP_SEGMENTS;
1084 for (Index = 0; Index < HEAP_SEGMENTS; Index++)
1085 {
1086 Segment = Heap->Segments[Index];
1087
1088 if (Segment) DPRINT("Segment[%u] %p with NOUCP %x\n", Index, Segment, Segment->NumberOfUnCommittedPages);
1089
1090 /* Check if its size suits us */
1091 if (Segment &&
1092 Pages <= Segment->NumberOfUnCommittedPages)
1093 {
1094 DPRINT("This segment is suitable\n");
1095
1096 /* Commit needed amount */
1097 FreeEntry = RtlpFindAndCommitPages(Heap, Segment, &FreeSize, NULL);
1098
1099 /* Coalesce it with adjacent entries */
1100 if (FreeEntry)
1101 {
1102 FreeSize = FreeSize >> HEAP_ENTRY_SHIFT;
1103 FreeEntry = RtlpCoalesceFreeBlocks(Heap, FreeEntry, &FreeSize, FALSE);
1104 RtlpInsertFreeBlock(Heap, FreeEntry, FreeSize);
1105 return FreeEntry;
1106 }
1107 }
1108 else if (!Segment &&
1109 EmptyIndex == HEAP_SEGMENTS)
1110 {
1111 /* Remember the first unused segment index */
1112 EmptyIndex = Index;
1113 }
1114 }
1115
1116 /* No luck, need to grow the heap */
1117 if ((Heap->Flags & HEAP_GROWABLE) &&
1118 (EmptyIndex != HEAP_SEGMENTS))
1119 {
1120 Segment = NULL;
1121
1122 /* Reserve the memory */
1123 if ((Size + PAGE_SIZE) <= Heap->SegmentReserve)
1124 ReserveSize = Heap->SegmentReserve;
1125 else
1126 ReserveSize = Size + PAGE_SIZE;
1127
1128 Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
1129 (PVOID)&Segment,
1130 0,
1131 &ReserveSize,
1132 MEM_RESERVE,
1133 PAGE_READWRITE);
1134
1135 /* If it failed, retry again with a half division algorithm */
1136 while (!NT_SUCCESS(Status) &&
1137 ReserveSize != Size + PAGE_SIZE)
1138 {
1139 ReserveSize /= 2;
1140
1141 if (ReserveSize < (Size + PAGE_SIZE))
1142 ReserveSize = Size + PAGE_SIZE;
1143
1144 Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
1145 (PVOID)&Segment,
1146 0,
1147 &ReserveSize,
1148 MEM_RESERVE,
1149 PAGE_READWRITE);
1150 }
1151
1152 /* Proceed only if it's success */
1153 if (NT_SUCCESS(Status))
1154 {
1155 Heap->SegmentReserve += ReserveSize;
1156
1157 /* Now commit the memory */
1158 if ((Size + PAGE_SIZE) <= Heap->SegmentCommit)
1159 CommitSize = Heap->SegmentCommit;
1160 else
1161 CommitSize = Size + PAGE_SIZE;
1162
1163 Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
1164 (PVOID)&Segment,
1165 0,
1166 &CommitSize,
1167 MEM_COMMIT,
1168 PAGE_READWRITE);
1169
1170 DPRINT("Committed %lu bytes at base %p\n", CommitSize, Segment);
1171
1172 /* Initialize heap segment if commit was successful */
1173 if (NT_SUCCESS(Status))
1174 Status = RtlpInitializeHeapSegment(Heap, Segment, EmptyIndex, 0, ReserveSize, CommitSize);
1175
1176 /* If everything worked - cool */
1177 if (NT_SUCCESS(Status)) return (PHEAP_FREE_ENTRY)Segment->FirstEntry;
1178
1179 DPRINT1("Committing failed with status 0x%08X\n", Status);
1180
1181 /* Nope, we failed. Free memory */
1182 ZwFreeVirtualMemory(NtCurrentProcess(),
1183 (PVOID)&Segment,
1184 &ReserveSize,
1185 MEM_RELEASE);
1186 }
1187 else
1188 {
1189 DPRINT1("Reserving failed with status 0x%08X\n", Status);
1190 }
1191 }
1192
1193 if (RtlpGetMode() == UserMode)
1194 {
1195 /* If coalescing on free is disabled in usermode, then do it here */
1196 if (Heap->Flags & HEAP_DISABLE_COALESCE_ON_FREE)
1197 {
1198 FreeEntry = RtlpCoalesceHeap(Heap);
1199
1200 /* If it's a suitable one - return it */
1201 if (FreeEntry &&
1202 FreeEntry->Size >= Size)
1203 {
1204 return FreeEntry;
1205 }
1206 }
1207 }
1208
1209 return NULL;
1210 }
1211
1212 /***********************************************************************
1213 * RtlCreateHeap
1214 * RETURNS
1215 * Handle of heap: Success
1216 * NULL: Failure
1217 *
1218 * @implemented
1219 */
1220 HANDLE NTAPI
1221 RtlCreateHeap(ULONG Flags,
1222 PVOID Addr,
1223 SIZE_T TotalSize,
1224 SIZE_T CommitSize,
1225 PVOID Lock,
1226 PRTL_HEAP_PARAMETERS Parameters)
1227 {
1228 PVOID CommittedAddress = NULL, UncommittedAddress = NULL;
1229 PHEAP Heap = 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;
1236 NTSTATUS Status;
1237 ULONG MaxBlockSize;
1238
1239 /* Check for a special heap */
1240 if (RtlpPageHeapEnabled && !Addr && !Lock)
1241 {
1242 Heap = RtlpPageHeapCreate(Flags, Addr, TotalSize, CommitSize, Lock, Parameters);
1243 if (Heap) return Heap;
1244
1245 /* Reset a special Parameters == -1 hack */
1246 if ((ULONG_PTR)Parameters == (ULONG_PTR)-1)
1247 Parameters = NULL;
1248 else
1249 DPRINT1("Enabling page heap failed\n");
1250 }
1251
1252 /* Check validation flags */
1253 if (!(Flags & HEAP_SKIP_VALIDATION_CHECKS) && (Flags & ~HEAP_CREATE_VALID_MASK))
1254 {
1255 DPRINT1("Invalid flags 0x%08x, fixing...\n", Flags);
1256 Flags &= HEAP_CREATE_VALID_MASK;
1257 }
1258
1259 /* TODO: Capture parameters, once we decide to use SEH */
1260 if (!Parameters) Parameters = &SafeParams;
1261
1262 /* Check global flags */
1263 if (NtGlobalFlags & FLG_HEAP_DISABLE_COALESCING)
1264 Flags |= HEAP_DISABLE_COALESCE_ON_FREE;
1265
1266 if (NtGlobalFlags & FLG_HEAP_ENABLE_FREE_CHECK)
1267 Flags |= HEAP_FREE_CHECKING_ENABLED;
1268
1269 if (NtGlobalFlags & FLG_HEAP_ENABLE_TAIL_CHECK)
1270 Flags |= HEAP_TAIL_CHECKING_ENABLED;
1271
1272 if (RtlpGetMode() == UserMode)
1273 {
1274 /* Also check these flags if in usermode */
1275 if (NtGlobalFlags & FLG_HEAP_VALIDATE_ALL)
1276 Flags |= HEAP_VALIDATE_ALL_ENABLED;
1277
1278 if (NtGlobalFlags & FLG_HEAP_VALIDATE_PARAMETERS)
1279 Flags |= HEAP_VALIDATE_PARAMETERS_ENABLED;
1280
1281 if (NtGlobalFlags & FLG_USER_STACK_TRACE_DB)
1282 Flags |= HEAP_CAPTURE_STACK_BACKTRACES;
1283 }
1284
1285 /* Set tunable parameters */
1286 RtlpSetHeapParameters(Parameters);
1287
1288 /* Get the max um address */
1289 Status = ZwQuerySystemInformation(SystemBasicInformation,
1290 &SystemInformation,
1291 sizeof(SystemInformation),
1292 NULL);
1293
1294 if (!NT_SUCCESS(Status))
1295 {
1296 DPRINT1("Getting max usermode address failed with status 0x%08x\n", Status);
1297 return NULL;
1298 }
1299
1300 MaximumUserModeAddress = SystemInformation.MaximumUserModeAddress;
1301
1302 /* Calculate max alloc size */
1303 if (!Parameters->MaximumAllocationSize)
1304 Parameters->MaximumAllocationSize = MaximumUserModeAddress - (ULONG_PTR)0x10000 - PAGE_SIZE;
1305
1306 MaxBlockSize = 0x80000 - PAGE_SIZE;
1307
1308 if (!Parameters->VirtualMemoryThreshold ||
1309 Parameters->VirtualMemoryThreshold > MaxBlockSize)
1310 {
1311 Parameters->VirtualMemoryThreshold = MaxBlockSize;
1312 }
1313
1314 /* Check reserve/commit sizes and set default values */
1315 if (!CommitSize)
1316 {
1317 CommitSize = PAGE_SIZE;
1318 if (TotalSize)
1319 TotalSize = ROUND_UP(TotalSize, PAGE_SIZE);
1320 else
1321 TotalSize = 64 * PAGE_SIZE;
1322 }
1323 else
1324 {
1325 /* Round up the commit size to be at least the page size */
1326 CommitSize = ROUND_UP(CommitSize, PAGE_SIZE);
1327
1328 if (TotalSize)
1329 TotalSize = ROUND_UP(TotalSize, PAGE_SIZE);
1330 else
1331 TotalSize = ROUND_UP(CommitSize, 16 * PAGE_SIZE);
1332 }
1333
1334 /* Call special heap */
1335 if (RtlpHeapIsSpecial(Flags))
1336 return RtlDebugCreateHeap(Flags, Addr, TotalSize, CommitSize, Lock, Parameters);
1337
1338 /* Without serialization, a lock makes no sense */
1339 if ((Flags & HEAP_NO_SERIALIZE) && (Lock != NULL))
1340 return NULL;
1341
1342 /* See if we are already provided with an address for the heap */
1343 if (Addr)
1344 {
1345 if (Parameters->CommitRoutine)
1346 {
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))
1352 {
1353 /* Fail */
1354 return NULL;
1355 }
1356
1357 /* Calculate committed and uncommitted addresses */
1358 CommittedAddress = Addr;
1359 UncommittedAddress = (PCHAR)Addr + Parameters->InitialCommit;
1360 TotalSize = Parameters->InitialReserve;
1361
1362 /* Zero the initial page ourselves */
1363 RtlZeroMemory(CommittedAddress, PAGE_SIZE);
1364 }
1365 else
1366 {
1367 /* Commit routine is absent, so query how much memory caller reserved */
1368 Status = ZwQueryVirtualMemory(NtCurrentProcess(),
1369 Addr,
1370 MemoryBasicInformation,
1371 &MemoryInfo,
1372 sizeof(MemoryInfo),
1373 NULL);
1374
1375 if (!NT_SUCCESS(Status))
1376 {
1377 DPRINT1("Querying amount of user supplied memory failed with status 0x%08X\n", Status);
1378 return NULL;
1379 }
1380
1381 /* Validate it */
1382 if (MemoryInfo.BaseAddress != Addr ||
1383 MemoryInfo.State == MEM_FREE)
1384 {
1385 return NULL;
1386 }
1387
1388 /* Validation checks passed, set committed/uncommitted addresses */
1389 CommittedAddress = Addr;
1390
1391 /* Check if it's committed or not */
1392 if (MemoryInfo.State == MEM_COMMIT)
1393 {
1394 /* Zero it out because it's already committed */
1395 RtlZeroMemory(CommittedAddress, PAGE_SIZE);
1396
1397 /* Calculate uncommitted address value */
1398 CommitSize = MemoryInfo.RegionSize;
1399 TotalSize = CommitSize;
1400 UncommittedAddress = (PCHAR)Addr + CommitSize;
1401
1402 /* Check if uncommitted address is reserved */
1403 Status = ZwQueryVirtualMemory(NtCurrentProcess(),
1404 UncommittedAddress,
1405 MemoryBasicInformation,
1406 &MemoryInfo,
1407 sizeof(MemoryInfo),
1408 NULL);
1409
1410 if (NT_SUCCESS(Status) &&
1411 MemoryInfo.State == MEM_RESERVE)
1412 {
1413 /* It is, so add it up to the reserve size */
1414 TotalSize += MemoryInfo.RegionSize;
1415 }
1416 }
1417 else
1418 {
1419 /* It's not committed, inform following code that a commit is necessary */
1420 CommitSize = PAGE_SIZE;
1421 UncommittedAddress = Addr;
1422 }
1423 }
1424
1425 /* Mark this as a user-committed mem */
1426 HeapSegmentFlags = HEAP_USER_ALLOCATED;
1427 Heap = (PHEAP)Addr;
1428 }
1429 else
1430 {
1431 /* Check commit routine */
1432 if (Parameters->CommitRoutine) return NULL;
1433
1434 /* Reserve memory */
1435 Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
1436 (PVOID *)&Heap,
1437 0,
1438 &TotalSize,
1439 MEM_RESERVE,
1440 PAGE_READWRITE);
1441
1442 if (!NT_SUCCESS(Status))
1443 {
1444 DPRINT1("Failed to reserve memory with status 0x%08x\n", Status);
1445 return NULL;
1446 }
1447
1448 /* Set base addresses */
1449 CommittedAddress = Heap;
1450 UncommittedAddress = Heap;
1451 }
1452
1453 /* Check if we need to commit something */
1454 if (CommittedAddress == UncommittedAddress)
1455 {
1456 /* Commit the required size */
1457 Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
1458 &CommittedAddress,
1459 0,
1460 &CommitSize,
1461 MEM_COMMIT,
1462 PAGE_READWRITE);
1463
1464 DPRINT("Committed %Iu bytes at base %p\n", CommitSize, CommittedAddress);
1465
1466 if (!NT_SUCCESS(Status))
1467 {
1468 DPRINT1("Failure, Status 0x%08X\n", Status);
1469
1470 /* Release memory if it was reserved */
1471 if (!Addr) ZwFreeVirtualMemory(NtCurrentProcess(),
1472 (PVOID *)&Heap,
1473 &TotalSize,
1474 MEM_RELEASE);
1475
1476 return NULL;
1477 }
1478
1479 /* Calculate new uncommitted address */
1480 UncommittedAddress = (PCHAR)UncommittedAddress + CommitSize;
1481 }
1482
1483 /* Initialize the heap */
1484 Status = RtlpInitializeHeap(Heap, Flags, Lock, Parameters);
1485 if (!NT_SUCCESS(Status))
1486 {
1487 DPRINT1("Failed to initialize heap (%x)\n", Status);
1488 return NULL;
1489 }
1490
1491 /* Initialize heap's first segment */
1492 Status = RtlpInitializeHeapSegment(Heap, (PHEAP_SEGMENT) (Heap), 0, HeapSegmentFlags, TotalSize, CommitSize);
1493 if (!NT_SUCCESS(Status))
1494 {
1495 DPRINT1("Failed to initialize heap segment (%x)\n", Status);
1496 return NULL;
1497 }
1498
1499 DPRINT("Created heap %p, CommitSize %x, ReserveSize %x\n", Heap, CommitSize, TotalSize);
1500
1501 /* Add heap to process list in case of usermode heap */
1502 if (RtlpGetMode() == UserMode)
1503 {
1504 RtlpAddHeapToProcessList(Heap);
1505
1506 // FIXME: What about lookasides?
1507 }
1508
1509 return Heap;
1510 }
1511
1512 /***********************************************************************
1513 * RtlDestroyHeap
1514 * RETURNS
1515 * TRUE: Success
1516 * FALSE: Failure
1517 *
1518 * @implemented
1519 *
1520 * RETURNS
1521 * Success: A NULL HANDLE, if heap is NULL or it was destroyed
1522 * Failure: The Heap handle, if heap is the process heap.
1523 */
1524 HANDLE NTAPI
1525 RtlDestroyHeap(HANDLE HeapPtr) /* [in] Handle of heap */
1526 {
1527 PHEAP Heap = (PHEAP)HeapPtr;
1528 PLIST_ENTRY Current;
1529 PHEAP_UCR_SEGMENT UcrSegment;
1530 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry;
1531 PVOID BaseAddress;
1532 SIZE_T Size;
1533 LONG i;
1534 PHEAP_SEGMENT Segment;
1535
1536 if (!HeapPtr) return NULL;
1537
1538 /* Call page heap routine if required */
1539 if (Heap->ForceFlags & HEAP_FLAG_PAGE_ALLOCS) return RtlpPageHeapDestroy(HeapPtr);
1540
1541 /* Call special heap */
1542 if (RtlpHeapIsSpecial(Heap->Flags))
1543 {
1544 if (!RtlDebugDestroyHeap(Heap)) return HeapPtr;
1545 }
1546
1547 /* Check for a process heap */
1548 if (RtlpGetMode() == UserMode &&
1549 HeapPtr == NtCurrentPeb()->ProcessHeap) return HeapPtr;
1550
1551 /* Free up all big allocations */
1552 Current = Heap->VirtualAllocdBlocks.Flink;
1553 while (Current != &Heap->VirtualAllocdBlocks)
1554 {
1555 VirtualEntry = CONTAINING_RECORD(Current, HEAP_VIRTUAL_ALLOC_ENTRY, Entry);
1556 BaseAddress = (PVOID)VirtualEntry;
1557 Current = Current->Flink;
1558 Size = 0;
1559 ZwFreeVirtualMemory(NtCurrentProcess(),
1560 &BaseAddress,
1561 &Size,
1562 MEM_RELEASE);
1563 }
1564
1565 /* Delete tags and remove heap from the process heaps list in user mode */
1566 if (RtlpGetMode() == UserMode)
1567 {
1568 // FIXME DestroyTags
1569 RtlpRemoveHeapFromProcessList(Heap);
1570 }
1571
1572 /* Delete the heap lock */
1573 if (!(Heap->Flags & HEAP_NO_SERIALIZE))
1574 {
1575 /* Delete it if it wasn't user allocated */
1576 if (!(Heap->Flags & HEAP_LOCK_USER_ALLOCATED))
1577 RtlDeleteHeapLock(Heap->LockVariable);
1578
1579 /* Clear out the lock variable */
1580 Heap->LockVariable = NULL;
1581 }
1582
1583 /* Free UCR segments if any were created */
1584 Current = Heap->UCRSegments.Flink;
1585 while (Current != &Heap->UCRSegments)
1586 {
1587 UcrSegment = CONTAINING_RECORD(Current, HEAP_UCR_SEGMENT, ListEntry);
1588
1589 /* Advance to the next descriptor */
1590 Current = Current->Flink;
1591
1592 BaseAddress = (PVOID)UcrSegment;
1593 Size = 0;
1594
1595 /* Release that memory */
1596 ZwFreeVirtualMemory(NtCurrentProcess(),
1597 &BaseAddress,
1598 &Size,
1599 MEM_RELEASE);
1600 }
1601
1602 /* Go through segments and destroy them */
1603 for (i = HEAP_SEGMENTS - 1; i >= 0; i--)
1604 {
1605 Segment = Heap->Segments[i];
1606 if (Segment) RtlpDestroyHeapSegment(Segment);
1607 }
1608
1609 return NULL;
1610 }
1611
1612 PHEAP_ENTRY NTAPI
1613 RtlpSplitEntry(PHEAP Heap,
1614 ULONG Flags,
1615 PHEAP_FREE_ENTRY FreeBlock,
1616 SIZE_T AllocationSize,
1617 SIZE_T Index,
1618 SIZE_T Size)
1619 {
1620 PHEAP_FREE_ENTRY SplitBlock, SplitBlock2;
1621 UCHAR FreeFlags, EntryFlags = HEAP_ENTRY_BUSY;
1622 PHEAP_ENTRY InUseEntry;
1623 SIZE_T FreeSize;
1624
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)
1630 {
1631 /* Add flag which means that the entry will have extra stuff attached */
1632 EntryFlags |= HEAP_ENTRY_EXTRA_PRESENT;
1633
1634 /* NB! AllocationSize is already adjusted by RtlAllocateHeap */
1635 }
1636
1637 /* Add settable user flags, if any */
1638 EntryFlags |= (Flags & HEAP_SETTABLE_USER_FLAGS) >> 4;
1639
1640 /* Save flags, update total free size */
1641 FreeFlags = FreeBlock->Flags;
1642 Heap->TotalFreeSize -= FreeBlock->Size;
1643
1644 /* Make this block an in-use one */
1645 InUseEntry = (PHEAP_ENTRY)FreeBlock;
1646 InUseEntry->Flags = EntryFlags;
1647 InUseEntry->SmallTagIndex = 0;
1648
1649 /* Calculate the extra amount */
1650 FreeSize = InUseEntry->Size - Index;
1651
1652 /* Update it's size fields (we don't need their data anymore) */
1653 InUseEntry->Size = (USHORT)Index;
1654 InUseEntry->UnusedBytes = (UCHAR)(AllocationSize - Size);
1655
1656 /* If there is something to split - do the split */
1657 if (FreeSize != 0)
1658 {
1659 /* Don't split if resulting entry can't contain any payload data
1660 (i.e. being just HEAP_ENTRY_SIZE) */
1661 if (FreeSize == 1)
1662 {
1663 /* Increase sizes of the in-use entry */
1664 InUseEntry->Size++;
1665 InUseEntry->UnusedBytes += sizeof(HEAP_ENTRY);
1666 }
1667 else
1668 {
1669 /* Calculate a pointer to the new entry */
1670 SplitBlock = (PHEAP_FREE_ENTRY)(InUseEntry + Index);
1671
1672 /* Initialize it */
1673 SplitBlock->Flags = FreeFlags;
1674 SplitBlock->SegmentOffset = InUseEntry->SegmentOffset;
1675 SplitBlock->Size = (USHORT)FreeSize;
1676 SplitBlock->PreviousSize = (USHORT)Index;
1677
1678 /* Check if it's the last entry */
1679 if (FreeFlags & HEAP_ENTRY_LAST_ENTRY)
1680 {
1681 /* Insert it to the free list if it's the last entry */
1682 RtlpInsertFreeBlockHelper(Heap, SplitBlock, FreeSize, FALSE);
1683 Heap->TotalFreeSize += FreeSize;
1684 }
1685 else
1686 {
1687 /* Not so easy - need to update next's previous size too */
1688 SplitBlock2 = (PHEAP_FREE_ENTRY)((PHEAP_ENTRY)SplitBlock + FreeSize);
1689
1690 if (SplitBlock2->Flags & HEAP_ENTRY_BUSY)
1691 {
1692 SplitBlock2->PreviousSize = (USHORT)FreeSize;
1693 RtlpInsertFreeBlockHelper(Heap, SplitBlock, FreeSize, FALSE);
1694 Heap->TotalFreeSize += FreeSize;
1695 }
1696 else
1697 {
1698 /* Even more complex - the next entry is free, so we can merge them into one! */
1699 SplitBlock->Flags = SplitBlock2->Flags;
1700
1701 /* Remove that next entry */
1702 RtlpRemoveFreeBlock(Heap, SplitBlock2, FALSE, FALSE);
1703
1704 /* Update sizes */
1705 FreeSize += SplitBlock2->Size;
1706 Heap->TotalFreeSize -= SplitBlock2->Size;
1707
1708 if (FreeSize <= HEAP_MAX_BLOCK_SIZE)
1709 {
1710 /* Insert it back */
1711 SplitBlock->Size = (USHORT)FreeSize;
1712
1713 /* Don't forget to update previous size of the next entry! */
1714 if (!(SplitBlock->Flags & HEAP_ENTRY_LAST_ENTRY))
1715 {
1716 ((PHEAP_FREE_ENTRY)((PHEAP_ENTRY)SplitBlock + FreeSize))->PreviousSize = (USHORT)FreeSize;
1717 }
1718
1719 /* Actually insert it */
1720 RtlpInsertFreeBlockHelper(Heap, SplitBlock, (USHORT)FreeSize, FALSE);
1721
1722 /* Update total size */
1723 Heap->TotalFreeSize += FreeSize;
1724 }
1725 else
1726 {
1727 /* Resulting block is quite big */
1728 RtlpInsertFreeBlock(Heap, SplitBlock, FreeSize);
1729 }
1730 }
1731 }
1732
1733 /* Reset flags of the free entry */
1734 FreeFlags = 0;
1735 }
1736 }
1737
1738 /* Set last entry flag */
1739 if (FreeFlags & HEAP_ENTRY_LAST_ENTRY)
1740 InUseEntry->Flags |= HEAP_ENTRY_LAST_ENTRY;
1741
1742 return InUseEntry;
1743 }
1744
1745 PVOID NTAPI
1746 RtlpAllocateNonDedicated(PHEAP Heap,
1747 ULONG Flags,
1748 SIZE_T Size,
1749 SIZE_T AllocationSize,
1750 SIZE_T Index,
1751 BOOLEAN HeapLocked)
1752 {
1753 PLIST_ENTRY FreeListHead, Next;
1754 PHEAP_FREE_ENTRY FreeBlock;
1755 PHEAP_ENTRY InUseEntry;
1756 PHEAP_ENTRY_EXTRA Extra;
1757 EXCEPTION_RECORD ExceptionRecord;
1758
1759 /* Go through the zero list to find a place where to insert the new entry */
1760 FreeListHead = &Heap->FreeLists[0];
1761
1762 /* Start from the largest block to reduce time */
1763 Next = FreeListHead->Blink;
1764 if (FreeListHead != Next)
1765 {
1766 FreeBlock = CONTAINING_RECORD(Next, HEAP_FREE_ENTRY, FreeList);
1767
1768 if (FreeBlock->Size >= Index)
1769 {
1770 /* Our request is smaller than the largest entry in the zero list */
1771
1772 /* Go through the list to find insertion place */
1773 Next = FreeListHead->Flink;
1774 while (FreeListHead != Next)
1775 {
1776 FreeBlock = CONTAINING_RECORD(Next, HEAP_FREE_ENTRY, FreeList);
1777
1778 if (FreeBlock->Size >= Index)
1779 {
1780 /* Found minimally fitting entry. Proceed to either using it as it is
1781 or splitting it to two entries */
1782 RemoveEntryList(&FreeBlock->FreeList);
1783
1784 /* Split it */
1785 InUseEntry = RtlpSplitEntry(Heap, Flags, FreeBlock, AllocationSize, Index, Size);
1786
1787 /* Release the lock */
1788 if (HeapLocked) RtlLeaveHeapLock(Heap->LockVariable);
1789
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)
1794 {
1795 /* Fill this block with a special pattern */
1796 RtlFillMemoryUlong(InUseEntry + 1, Size & ~0x3, ARENA_INUSE_FILLER);
1797 }
1798
1799 /* Fill tail of the block with a special pattern too if requested */
1800 if (Heap->Flags & HEAP_TAIL_CHECKING_ENABLED)
1801 {
1802 RtlFillMemory((PCHAR)(InUseEntry + 1) + Size, sizeof(HEAP_ENTRY), HEAP_TAIL_FILL);
1803 InUseEntry->Flags |= HEAP_ENTRY_FILL_PATTERN;
1804 }
1805
1806 /* Prepare extra if it's present */
1807 if (InUseEntry->Flags & HEAP_ENTRY_EXTRA_PRESENT)
1808 {
1809 Extra = RtlpGetExtraStuffPointer(InUseEntry);
1810 RtlZeroMemory(Extra, sizeof(HEAP_ENTRY_EXTRA));
1811
1812 // TODO: Tagging
1813 }
1814
1815 /* Return pointer to the */
1816 return InUseEntry + 1;
1817 }
1818
1819 /* Advance to the next entry */
1820 Next = Next->Flink;
1821 }
1822 }
1823 }
1824
1825 /* Extend the heap, 0 list didn't have anything suitable */
1826 FreeBlock = RtlpExtendHeap(Heap, AllocationSize);
1827
1828 /* Use the new biggest entry we've got */
1829 if (FreeBlock)
1830 {
1831 RemoveEntryList(&FreeBlock->FreeList);
1832
1833 /* Split it */
1834 InUseEntry = RtlpSplitEntry(Heap, Flags, FreeBlock, AllocationSize, Index, Size);
1835
1836 /* Release the lock */
1837 if (HeapLocked) RtlLeaveHeapLock(Heap->LockVariable);
1838
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)
1843 {
1844 /* Fill this block with a special pattern */
1845 RtlFillMemoryUlong(InUseEntry + 1, Size & ~0x3, ARENA_INUSE_FILLER);
1846 }
1847
1848 /* Fill tail of the block with a special pattern too if requested */
1849 if (Heap->Flags & HEAP_TAIL_CHECKING_ENABLED)
1850 {
1851 RtlFillMemory((PCHAR)(InUseEntry + 1) + Size, sizeof(HEAP_ENTRY), HEAP_TAIL_FILL);
1852 InUseEntry->Flags |= HEAP_ENTRY_FILL_PATTERN;
1853 }
1854
1855 /* Prepare extra if it's present */
1856 if (InUseEntry->Flags & HEAP_ENTRY_EXTRA_PRESENT)
1857 {
1858 Extra = RtlpGetExtraStuffPointer(InUseEntry);
1859 RtlZeroMemory(Extra, sizeof(HEAP_ENTRY_EXTRA));
1860
1861 // TODO: Tagging
1862 }
1863
1864 /* Return pointer to the */
1865 return InUseEntry + 1;
1866 }
1867
1868 /* Really unfortunate, out of memory condition */
1869 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_NO_MEMORY);
1870
1871 /* Generate an exception */
1872 if (Flags & HEAP_GENERATE_EXCEPTIONS)
1873 {
1874 ExceptionRecord.ExceptionCode = STATUS_NO_MEMORY;
1875 ExceptionRecord.ExceptionRecord = NULL;
1876 ExceptionRecord.NumberParameters = 1;
1877 ExceptionRecord.ExceptionFlags = 0;
1878 ExceptionRecord.ExceptionInformation[0] = AllocationSize;
1879
1880 RtlRaiseException(&ExceptionRecord);
1881 }
1882
1883 /* Release the lock */
1884 if (HeapLocked) RtlLeaveHeapLock(Heap->LockVariable);
1885 DPRINT1("HEAP: Allocation failed!\n");
1886 DPRINT1("Flags %x\n", Heap->Flags);
1887 return NULL;
1888 }
1889
1890 /***********************************************************************
1891 * HeapAlloc (KERNEL32.334)
1892 * RETURNS
1893 * Pointer to allocated memory block
1894 * NULL: Failure
1895 * 0x7d030f60--invalid flags in RtlHeapAllocate
1896 * @implemented
1897 */
1898 PVOID NTAPI
1899 RtlAllocateHeap(IN PVOID HeapPtr,
1900 IN ULONG Flags,
1901 IN SIZE_T Size)
1902 {
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;
1916 NTSTATUS Status;
1917
1918 /* Force flags */
1919 Flags |= Heap->ForceFlags;
1920
1921 /* Call special heap */
1922 if (RtlpHeapIsSpecial(Flags))
1923 return RtlDebugAllocateHeap(Heap, Flags, Size);
1924
1925 /* Check for the maximum size */
1926 if (Size >= 0x80000000)
1927 {
1928 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_NO_MEMORY);
1929 DPRINT1("HEAP: Allocation failed!\n");
1930 return NULL;
1931 }
1932
1933 if (Flags & (HEAP_CREATE_ENABLE_TRACING |
1934 HEAP_CREATE_ALIGN_16))
1935 {
1936 DPRINT1("HEAP: RtlAllocateHeap is called with unsupported flags %x, ignoring\n", Flags);
1937 }
1938
1939 //DPRINT("RtlAllocateHeap(%p %x %x)\n", Heap, Flags, Size);
1940
1941 /* Calculate allocation size and index */
1942 if (Size)
1943 AllocationSize = Size;
1944 else
1945 AllocationSize = 1;
1946 AllocationSize = (AllocationSize + Heap->AlignRound) & Heap->AlignMask;
1947
1948 /* Add extra flags in case of settable user value feature is requested,
1949 or there is a tag (small or normal) or there is a request to
1950 capture stack backtraces */
1951 if ((Flags & HEAP_EXTRA_FLAGS_MASK) ||
1952 Heap->PseudoTagEntries)
1953 {
1954 /* Add flag which means that the entry will have extra stuff attached */
1955 EntryFlags |= HEAP_ENTRY_EXTRA_PRESENT;
1956
1957 /* Account for extra stuff size */
1958 AllocationSize += sizeof(HEAP_ENTRY_EXTRA);
1959 }
1960
1961 /* Add settable user flags, if any */
1962 EntryFlags |= (Flags & HEAP_SETTABLE_USER_FLAGS) >> 4;
1963
1964 Index = AllocationSize >> HEAP_ENTRY_SHIFT;
1965
1966 /* Acquire the lock if necessary */
1967 if (!(Flags & HEAP_NO_SERIALIZE))
1968 {
1969 RtlEnterHeapLock(Heap->LockVariable, TRUE);
1970 HeapLocked = TRUE;
1971 }
1972
1973 /* Depending on the size, the allocation is going to be done from dedicated,
1974 non-dedicated lists or a virtual block of memory */
1975 if (Index < HEAP_FREELISTS)
1976 {
1977 FreeListHead = &Heap->FreeLists[Index];
1978
1979 if (!IsListEmpty(FreeListHead))
1980 {
1981 /* There is a free entry in this list */
1982 FreeBlock = CONTAINING_RECORD(FreeListHead->Blink,
1983 HEAP_FREE_ENTRY,
1984 FreeList);
1985
1986 /* Save flags and remove the free entry */
1987 FreeFlags = FreeBlock->Flags;
1988 RtlpRemoveFreeBlock(Heap, FreeBlock, TRUE, FALSE);
1989
1990 /* Update the total free size of the heap */
1991 Heap->TotalFreeSize -= Index;
1992
1993 /* Initialize this block */
1994 InUseEntry = (PHEAP_ENTRY)FreeBlock;
1995 InUseEntry->Flags = EntryFlags | (FreeFlags & HEAP_ENTRY_LAST_ENTRY);
1996 InUseEntry->UnusedBytes = (UCHAR)(AllocationSize - Size);
1997 InUseEntry->SmallTagIndex = 0;
1998 }
1999 else
2000 {
2001 /* Find smallest free block which this request could fit in */
2002 InUseIndex = Index >> 5;
2003 FreeListsInUse = &Heap->u.FreeListsInUseUlong[InUseIndex];
2004
2005 /* This bit magic disables all sizes which are less than the requested allocation size */
2006 FreeListsInUseUlong = *FreeListsInUse++ & ~((1 << ((ULONG)Index & 0x1f)) - 1);
2007
2008 /* If size is definitily more than our lists - go directly to the non-dedicated one */
2009 if (InUseIndex > 3)
2010 return RtlpAllocateNonDedicated(Heap, Flags, Size, AllocationSize, Index, HeapLocked);
2011
2012 /* Go through the list */
2013 for (i = InUseIndex; i < 4; i++)
2014 {
2015 if (FreeListsInUseUlong)
2016 {
2017 FreeListHead = &Heap->FreeLists[i * 32];
2018 break;
2019 }
2020
2021 if (i < 3) FreeListsInUseUlong = *FreeListsInUse++;
2022 }
2023
2024 /* Nothing found, search in the non-dedicated list */
2025 if (i == 4)
2026 return RtlpAllocateNonDedicated(Heap, Flags, Size, AllocationSize, Index, HeapLocked);
2027
2028 /* That list is found, now calculate exact block */
2029 FreeListHead += RtlpFindLeastSetBit(FreeListsInUseUlong);
2030
2031 /* Take this entry and remove it from the list of free blocks */
2032 FreeBlock = CONTAINING_RECORD(FreeListHead->Blink,
2033 HEAP_FREE_ENTRY,
2034 FreeList);
2035 RtlpRemoveFreeBlock(Heap, FreeBlock, TRUE, FALSE);
2036
2037 /* Split it */
2038 InUseEntry = RtlpSplitEntry(Heap, Flags, FreeBlock, AllocationSize, Index, Size);
2039 }
2040
2041 /* Release the lock */
2042 if (HeapLocked) RtlLeaveHeapLock(Heap->LockVariable);
2043
2044 /* Zero memory if that was requested */
2045 if (Flags & HEAP_ZERO_MEMORY)
2046 RtlZeroMemory(InUseEntry + 1, Size);
2047 else if (Heap->Flags & HEAP_FREE_CHECKING_ENABLED)
2048 {
2049 /* Fill this block with a special pattern */
2050 RtlFillMemoryUlong(InUseEntry + 1, Size & ~0x3, ARENA_INUSE_FILLER);
2051 }
2052
2053 /* Fill tail of the block with a special pattern too if requested */
2054 if (Heap->Flags & HEAP_TAIL_CHECKING_ENABLED)
2055 {
2056 RtlFillMemory((PCHAR)(InUseEntry + 1) + Size, sizeof(HEAP_ENTRY), HEAP_TAIL_FILL);
2057 InUseEntry->Flags |= HEAP_ENTRY_FILL_PATTERN;
2058 }
2059
2060 /* Prepare extra if it's present */
2061 if (InUseEntry->Flags & HEAP_ENTRY_EXTRA_PRESENT)
2062 {
2063 Extra = RtlpGetExtraStuffPointer(InUseEntry);
2064 RtlZeroMemory(Extra, sizeof(HEAP_ENTRY_EXTRA));
2065
2066 // TODO: Tagging
2067 }
2068
2069 /* User data starts right after the entry's header */
2070 return InUseEntry + 1;
2071 }
2072 else if (Index <= Heap->VirtualMemoryThreshold)
2073 {
2074 /* The block is too large for dedicated lists, but fine for a non-dedicated one */
2075 return RtlpAllocateNonDedicated(Heap, Flags, Size, AllocationSize, Index, HeapLocked);
2076 }
2077 else if (Heap->Flags & HEAP_GROWABLE)
2078 {
2079 /* We've got a very big allocation request, satisfy it by directly allocating virtual memory */
2080 AllocationSize += sizeof(HEAP_VIRTUAL_ALLOC_ENTRY) - sizeof(HEAP_ENTRY);
2081
2082 Status = ZwAllocateVirtualMemory(NtCurrentProcess(),
2083 (PVOID *)&VirtualBlock,
2084 0,
2085 &AllocationSize,
2086 MEM_COMMIT,
2087 PAGE_READWRITE);
2088
2089 if (!NT_SUCCESS(Status))
2090 {
2091 // Set STATUS!
2092 /* Release the lock */
2093 if (HeapLocked) RtlLeaveHeapLock(Heap->LockVariable);
2094 DPRINT1("HEAP: Allocation failed!\n");
2095 return NULL;
2096 }
2097
2098 /* Initialize the newly allocated block */
2099 VirtualBlock->BusyBlock.Size = (USHORT)(AllocationSize - Size);
2100 ASSERT(VirtualBlock->BusyBlock.Size >= sizeof(HEAP_VIRTUAL_ALLOC_ENTRY));
2101 VirtualBlock->BusyBlock.Flags = EntryFlags | HEAP_ENTRY_VIRTUAL_ALLOC | HEAP_ENTRY_EXTRA_PRESENT;
2102 VirtualBlock->CommitSize = AllocationSize;
2103 VirtualBlock->ReserveSize = AllocationSize;
2104
2105 /* Insert it into the list of virtual allocations */
2106 InsertTailList(&Heap->VirtualAllocdBlocks, &VirtualBlock->Entry);
2107
2108 /* Release the lock */
2109 if (HeapLocked) RtlLeaveHeapLock(Heap->LockVariable);
2110
2111 /* Return pointer to user data */
2112 return VirtualBlock + 1;
2113 }
2114
2115 /* Generate an exception */
2116 if (Flags & HEAP_GENERATE_EXCEPTIONS)
2117 {
2118 ExceptionRecord.ExceptionCode = STATUS_NO_MEMORY;
2119 ExceptionRecord.ExceptionRecord = NULL;
2120 ExceptionRecord.NumberParameters = 1;
2121 ExceptionRecord.ExceptionFlags = 0;
2122 ExceptionRecord.ExceptionInformation[0] = AllocationSize;
2123
2124 RtlRaiseException(&ExceptionRecord);
2125 }
2126
2127 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_BUFFER_TOO_SMALL);
2128
2129 /* Release the lock */
2130 if (HeapLocked) RtlLeaveHeapLock(Heap->LockVariable);
2131 DPRINT1("HEAP: Allocation failed!\n");
2132 return NULL;
2133 }
2134
2135
2136 /***********************************************************************
2137 * HeapFree (KERNEL32.338)
2138 * RETURNS
2139 * TRUE: Success
2140 * FALSE: Failure
2141 *
2142 * @implemented
2143 */
2144 BOOLEAN NTAPI RtlFreeHeap(
2145 HANDLE HeapPtr, /* [in] Handle of heap */
2146 ULONG Flags, /* [in] Heap freeing flags */
2147 PVOID Ptr /* [in] Address of memory to free */
2148 )
2149 {
2150 PHEAP Heap;
2151 PHEAP_ENTRY HeapEntry;
2152 USHORT TagIndex = 0;
2153 SIZE_T BlockSize;
2154 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry;
2155 BOOLEAN Locked = FALSE;
2156 NTSTATUS Status;
2157
2158 /* Freeing NULL pointer is a legal operation */
2159 if (!Ptr) return TRUE;
2160
2161 /* Get pointer to the heap and force flags */
2162 Heap = (PHEAP)HeapPtr;
2163 Flags |= Heap->ForceFlags;
2164
2165 /* Call special heap */
2166 if (RtlpHeapIsSpecial(Flags))
2167 return RtlDebugFreeHeap(Heap, Flags, Ptr);
2168
2169 /* Lock if necessary */
2170 if (!(Flags & HEAP_NO_SERIALIZE))
2171 {
2172 RtlEnterHeapLock(Heap->LockVariable, TRUE);
2173 Locked = TRUE;
2174 }
2175
2176 /* Get pointer to the heap entry */
2177 HeapEntry = (PHEAP_ENTRY)Ptr - 1;
2178
2179 /* Check this entry, fail if it's invalid */
2180 if (!(HeapEntry->Flags & HEAP_ENTRY_BUSY) ||
2181 (((ULONG_PTR)Ptr & 0x7) != 0) ||
2182 (HeapEntry->SegmentOffset >= HEAP_SEGMENTS))
2183 {
2184 /* This is an invalid block */
2185 DPRINT1("HEAP: Trying to free an invalid address %p!\n", Ptr);
2186 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER);
2187
2188 /* Release the heap lock */
2189 if (Locked) RtlLeaveHeapLock(Heap->LockVariable);
2190 return FALSE;
2191 }
2192
2193 if (HeapEntry->Flags & HEAP_ENTRY_VIRTUAL_ALLOC)
2194 {
2195 /* Big allocation */
2196 VirtualEntry = CONTAINING_RECORD(HeapEntry, HEAP_VIRTUAL_ALLOC_ENTRY, BusyBlock);
2197
2198 /* Remove it from the list */
2199 RemoveEntryList(&VirtualEntry->Entry);
2200
2201 // TODO: Tagging
2202
2203 BlockSize = 0;
2204 Status = ZwFreeVirtualMemory(NtCurrentProcess(),
2205 (PVOID *)&VirtualEntry,
2206 &BlockSize,
2207 MEM_RELEASE);
2208
2209 if (!NT_SUCCESS(Status))
2210 {
2211 DPRINT1("HEAP: Failed releasing memory with Status 0x%08X. Heap %p, ptr %p, base address %p\n",
2212 Status, Heap, Ptr, VirtualEntry);
2213 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(Status);
2214 }
2215 }
2216 else
2217 {
2218 /* Normal allocation */
2219 BlockSize = HeapEntry->Size;
2220
2221 // TODO: Tagging
2222
2223 /* Coalesce in kernel mode, and in usermode if it's not disabled */
2224 if (RtlpGetMode() == KernelMode ||
2225 (RtlpGetMode() == UserMode && !(Heap->Flags & HEAP_DISABLE_COALESCE_ON_FREE)))
2226 {
2227 HeapEntry = (PHEAP_ENTRY)RtlpCoalesceFreeBlocks(Heap,
2228 (PHEAP_FREE_ENTRY)HeapEntry,
2229 &BlockSize,
2230 FALSE);
2231 }
2232
2233 /* If there is no need to decommit the block - put it into a free list */
2234 if (BlockSize < Heap->DeCommitFreeBlockThreshold ||
2235 (Heap->TotalFreeSize + BlockSize < Heap->DeCommitTotalFreeThreshold))
2236 {
2237 /* Check if it needs to go to a 0 list */
2238 if (BlockSize > HEAP_MAX_BLOCK_SIZE)
2239 {
2240 /* General-purpose 0 list */
2241 RtlpInsertFreeBlock(Heap, (PHEAP_FREE_ENTRY)HeapEntry, BlockSize);
2242 }
2243 else
2244 {
2245 /* Usual free list */
2246 RtlpInsertFreeBlockHelper(Heap, (PHEAP_FREE_ENTRY)HeapEntry, BlockSize, FALSE);
2247
2248 /* Assert sizes are consistent */
2249 if (!(HeapEntry->Flags & HEAP_ENTRY_LAST_ENTRY))
2250 {
2251 ASSERT((HeapEntry + BlockSize)->PreviousSize == BlockSize);
2252 }
2253
2254 /* Increase the free size */
2255 Heap->TotalFreeSize += BlockSize;
2256 }
2257
2258
2259 if (RtlpGetMode() == UserMode &&
2260 TagIndex != 0)
2261 {
2262 // FIXME: Tagging
2263 UNIMPLEMENTED;
2264 }
2265 }
2266 else
2267 {
2268 /* Decommit this block */
2269 RtlpDeCommitFreeBlock(Heap, (PHEAP_FREE_ENTRY)HeapEntry, BlockSize);
2270 }
2271 }
2272
2273 /* Release the heap lock */
2274 if (Locked) RtlLeaveHeapLock(Heap->LockVariable);
2275
2276 return TRUE;
2277 }
2278
2279 BOOLEAN NTAPI
2280 RtlpGrowBlockInPlace (IN PHEAP Heap,
2281 IN ULONG Flags,
2282 IN PHEAP_ENTRY InUseEntry,
2283 IN SIZE_T Size,
2284 IN SIZE_T Index)
2285 {
2286 UCHAR EntryFlags, RememberFlags;
2287 PHEAP_FREE_ENTRY FreeEntry, UnusedEntry, FollowingEntry;
2288 SIZE_T FreeSize, PrevSize, TailPart, AddedSize = 0;
2289 PHEAP_ENTRY_EXTRA OldExtra, NewExtra;
2290
2291 /* We can't grow beyond specified threshold */
2292 if (Index > Heap->VirtualMemoryThreshold)
2293 return FALSE;
2294
2295 /* Get entry flags */
2296 EntryFlags = InUseEntry->Flags;
2297
2298 /* Get the next free entry */
2299 FreeEntry = (PHEAP_FREE_ENTRY)(InUseEntry + InUseEntry->Size);
2300
2301 if (EntryFlags & HEAP_ENTRY_LAST_ENTRY)
2302 {
2303 /* There is no next block, just uncommitted space. Calculate how much is needed */
2304 FreeSize = (Index - InUseEntry->Size) << HEAP_ENTRY_SHIFT;
2305 FreeSize = ROUND_UP(FreeSize, PAGE_SIZE);
2306
2307 /* Find and commit those pages */
2308 FreeEntry = RtlpFindAndCommitPages(Heap,
2309 Heap->Segments[InUseEntry->SegmentOffset],
2310 &FreeSize,
2311 FreeEntry);
2312
2313 /* Fail if it failed... */
2314 if (!FreeEntry) return FALSE;
2315
2316 /* It was successful, perform coalescing */
2317 FreeSize = FreeSize >> HEAP_ENTRY_SHIFT;
2318 FreeEntry = RtlpCoalesceFreeBlocks(Heap, FreeEntry, &FreeSize, FALSE);
2319
2320 /* Check if it's enough */
2321 if (FreeSize + InUseEntry->Size < Index)
2322 {
2323 /* Still not enough */
2324 RtlpInsertFreeBlock(Heap, FreeEntry, FreeSize);
2325 Heap->TotalFreeSize += FreeSize;
2326 return FALSE;
2327 }
2328
2329 /* Remember flags of this free entry */
2330 RememberFlags = FreeEntry->Flags;
2331
2332 /* Sum up sizes */
2333 FreeSize += InUseEntry->Size;
2334 }
2335 else
2336 {
2337 /* The next block indeed exists. Check if it's free or in use */
2338 if (FreeEntry->Flags & HEAP_ENTRY_BUSY) return FALSE;
2339
2340 /* Next entry is free, check if it can fit the block we need */
2341 FreeSize = InUseEntry->Size + FreeEntry->Size;
2342 if (FreeSize < Index) return FALSE;
2343
2344 /* Remember flags of this free entry */
2345 RememberFlags = FreeEntry->Flags;
2346
2347 /* Remove this block from the free list */
2348 RtlpRemoveFreeBlock(Heap, FreeEntry, FALSE, FALSE);
2349 Heap->TotalFreeSize -= FreeEntry->Size;
2350 }
2351
2352 PrevSize = (InUseEntry->Size << HEAP_ENTRY_SHIFT) - InUseEntry->UnusedBytes;
2353 FreeSize -= Index;
2354
2355 /* Don't produce too small blocks */
2356 if (FreeSize <= 2)
2357 {
2358 Index += FreeSize;
2359 FreeSize = 0;
2360 }
2361
2362 /* Process extra stuff */
2363 if (RememberFlags & HEAP_ENTRY_EXTRA_PRESENT)
2364 {
2365 /* Calculate pointers */
2366 OldExtra = (PHEAP_ENTRY_EXTRA)(InUseEntry + InUseEntry->Size - 1);
2367 NewExtra = (PHEAP_ENTRY_EXTRA)(InUseEntry + Index - 1);
2368
2369 /* Copy contents */
2370 *NewExtra = *OldExtra;
2371
2372 // FIXME Tagging
2373 }
2374
2375 /* Update sizes */
2376 InUseEntry->Size = (USHORT)Index;
2377 InUseEntry->UnusedBytes = (UCHAR)((Index << HEAP_ENTRY_SHIFT) - Size);
2378
2379 /* Check if there is a free space remaining after merging those blocks */
2380 if (!FreeSize)
2381 {
2382 /* Update flags and sizes */
2383 InUseEntry->Flags |= RememberFlags & HEAP_ENTRY_LAST_ENTRY;
2384
2385 /* Either update previous size of the next entry or mark it as a last
2386 entry in the segment*/
2387 if (!(RememberFlags & HEAP_ENTRY_LAST_ENTRY))
2388 (InUseEntry + InUseEntry->Size)->PreviousSize = InUseEntry->Size;
2389 }
2390 else
2391 {
2392 /* Complex case, we need to split the block to give unused free space
2393 back to the heap */
2394 UnusedEntry = (PHEAP_FREE_ENTRY)(InUseEntry + Index);
2395 UnusedEntry->PreviousSize = (USHORT)Index;
2396 UnusedEntry->SegmentOffset = InUseEntry->SegmentOffset;
2397
2398 /* Update the following block or set the last entry in the segment */
2399 if (RememberFlags & HEAP_ENTRY_LAST_ENTRY)
2400 {
2401 /* Set flags and size */
2402 UnusedEntry->Flags = RememberFlags;
2403 UnusedEntry->Size = (USHORT)FreeSize;
2404
2405 /* Insert it to the heap and update total size */
2406 RtlpInsertFreeBlockHelper(Heap, UnusedEntry, FreeSize, FALSE);
2407 Heap->TotalFreeSize += FreeSize;
2408 }
2409 else
2410 {
2411 /* There is a block after this one */
2412 FollowingEntry = (PHEAP_FREE_ENTRY)((PHEAP_ENTRY)UnusedEntry + FreeSize);
2413
2414 if (FollowingEntry->Flags & HEAP_ENTRY_BUSY)
2415 {
2416 /* Update flags and set size of the unused space entry */
2417 UnusedEntry->Flags = RememberFlags & (~HEAP_ENTRY_LAST_ENTRY);
2418 UnusedEntry->Size = (USHORT)FreeSize;
2419
2420 /* Update previous size of the following entry */
2421 FollowingEntry->PreviousSize = (USHORT)FreeSize;
2422
2423 /* Insert it to the heap and update total free size */
2424 RtlpInsertFreeBlockHelper(Heap, UnusedEntry, FreeSize, FALSE);
2425 Heap->TotalFreeSize += FreeSize;
2426 }
2427 else
2428 {
2429 /* That following entry is also free, what a fortune! */
2430 RememberFlags = FollowingEntry->Flags;
2431
2432 /* Remove it */
2433 RtlpRemoveFreeBlock(Heap, FollowingEntry, FALSE, FALSE);
2434 Heap->TotalFreeSize -= FollowingEntry->Size;
2435
2436 /* And make up a new combined block */
2437 FreeSize += FollowingEntry->Size;
2438 UnusedEntry->Flags = RememberFlags;
2439
2440 /* Check where to put it */
2441 if (FreeSize <= HEAP_MAX_BLOCK_SIZE)
2442 {
2443 /* Fine for a dedicated list */
2444 UnusedEntry->Size = (USHORT)FreeSize;
2445
2446 if (!(RememberFlags & HEAP_ENTRY_LAST_ENTRY))
2447 ((PHEAP_ENTRY)UnusedEntry + FreeSize)->PreviousSize = (USHORT)FreeSize;
2448
2449 /* Insert it back and update total size */
2450 RtlpInsertFreeBlockHelper(Heap, UnusedEntry, FreeSize, FALSE);
2451 Heap->TotalFreeSize += FreeSize;
2452 }
2453 else
2454 {
2455 /* The block is very large, leave all the hassle to the insertion routine */
2456 RtlpInsertFreeBlock(Heap, UnusedEntry, FreeSize);
2457 }
2458 }
2459 }
2460 }
2461
2462 /* Properly "zero out" (and fill!) the space */
2463 if (Flags & HEAP_ZERO_MEMORY)
2464 {
2465 RtlZeroMemory((PCHAR)(InUseEntry + 1) + PrevSize, Size - PrevSize);
2466 }
2467 else if (Heap->Flags & HEAP_FREE_CHECKING_ENABLED)
2468 {
2469 /* Calculate tail part which we need to fill */
2470 TailPart = PrevSize & (sizeof(ULONG) - 1);
2471
2472 /* "Invert" it as usual */
2473 if (TailPart) TailPart = 4 - TailPart;
2474
2475 if (Size > (PrevSize + TailPart))
2476 AddedSize = (Size - (PrevSize + TailPart)) & ~(sizeof(ULONG) - 1);
2477
2478 if (AddedSize)
2479 {
2480 RtlFillMemoryUlong((PCHAR)(InUseEntry + 1) + PrevSize + TailPart,
2481 AddedSize,
2482 ARENA_INUSE_FILLER);
2483 }
2484 }
2485
2486 /* Fill the new tail */
2487 if (Heap->Flags & HEAP_TAIL_CHECKING_ENABLED)
2488 {
2489 RtlFillMemory((PCHAR)(InUseEntry + 1) + Size,
2490 HEAP_ENTRY_SIZE,
2491 HEAP_TAIL_FILL);
2492 }
2493
2494 /* Copy user settable flags */
2495 InUseEntry->Flags &= ~HEAP_ENTRY_SETTABLE_FLAGS;
2496 InUseEntry->Flags |= ((Flags & HEAP_SETTABLE_USER_FLAGS) >> 4);
2497
2498 /* Return success */
2499 return TRUE;
2500 }
2501
2502 PHEAP_ENTRY_EXTRA NTAPI
2503 RtlpGetExtraStuffPointer(PHEAP_ENTRY HeapEntry)
2504 {
2505 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualEntry;
2506
2507 /* Check if it's a big block */
2508 if (HeapEntry->Flags & HEAP_ENTRY_VIRTUAL_ALLOC)
2509 {
2510 VirtualEntry = CONTAINING_RECORD(HeapEntry, HEAP_VIRTUAL_ALLOC_ENTRY, BusyBlock);
2511
2512 /* Return a pointer to the extra stuff*/
2513 return &VirtualEntry->ExtraStuff;
2514 }
2515 else
2516 {
2517 /* This is a usual entry, which means extra stuff follows this block */
2518 return (PHEAP_ENTRY_EXTRA)(HeapEntry + HeapEntry->Size - 1);
2519 }
2520 }
2521
2522
2523 /***********************************************************************
2524 * RtlReAllocateHeap
2525 * PARAMS
2526 * Heap [in] Handle of heap block
2527 * Flags [in] Heap reallocation flags
2528 * Ptr, [in] Address of memory to reallocate
2529 * Size [in] Number of bytes to reallocate
2530 *
2531 * RETURNS
2532 * Pointer to reallocated memory block
2533 * NULL: Failure
2534 * 0x7d030f60--invalid flags in RtlHeapAllocate
2535 * @implemented
2536 */
2537 PVOID NTAPI
2538 RtlReAllocateHeap(HANDLE HeapPtr,
2539 ULONG Flags,
2540 PVOID Ptr,
2541 SIZE_T Size)
2542 {
2543 PHEAP Heap = (PHEAP)HeapPtr;
2544 PHEAP_ENTRY InUseEntry, NewInUseEntry;
2545 PHEAP_ENTRY_EXTRA OldExtra, NewExtra;
2546 SIZE_T AllocationSize, FreeSize, DecommitSize;
2547 BOOLEAN HeapLocked = FALSE;
2548 PVOID NewBaseAddress;
2549 PHEAP_FREE_ENTRY SplitBlock, SplitBlock2;
2550 SIZE_T OldSize, Index, OldIndex;
2551 UCHAR FreeFlags;
2552 NTSTATUS Status;
2553 PVOID DecommitBase;
2554 SIZE_T RemainderBytes, ExtraSize;
2555 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualAllocBlock;
2556 EXCEPTION_RECORD ExceptionRecord;
2557
2558 /* Return success in case of a null pointer */
2559 if (!Ptr)
2560 {
2561 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_SUCCESS);
2562 return NULL;
2563 }
2564
2565 /* Force heap flags */
2566 Flags |= Heap->ForceFlags;
2567
2568 /* Call special heap */
2569 if (RtlpHeapIsSpecial(Flags))
2570 return RtlDebugReAllocateHeap(Heap, Flags, Ptr, Size);
2571
2572 /* Make sure size is valid */
2573 if (Size >= 0x80000000)
2574 {
2575 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_NO_MEMORY);
2576 return NULL;
2577 }
2578
2579 /* Calculate allocation size and index */
2580 if (Size)
2581 AllocationSize = Size;
2582 else
2583 AllocationSize = 1;
2584 AllocationSize = (AllocationSize + Heap->AlignRound) & Heap->AlignMask;
2585
2586 /* Add up extra stuff, if it is present anywhere */
2587 if (((((PHEAP_ENTRY)Ptr)-1)->Flags & HEAP_ENTRY_EXTRA_PRESENT) ||
2588 (Flags & HEAP_EXTRA_FLAGS_MASK) ||
2589 Heap->PseudoTagEntries)
2590 {
2591 AllocationSize += sizeof(HEAP_ENTRY_EXTRA);
2592 }
2593
2594 /* Acquire the lock if necessary */
2595 if (!(Flags & HEAP_NO_SERIALIZE))
2596 {
2597 RtlEnterHeapLock(Heap->LockVariable, TRUE);
2598 HeapLocked = TRUE;
2599 Flags &= ~HEAP_NO_SERIALIZE;
2600 }
2601
2602 /* Get the pointer to the in-use entry */
2603 InUseEntry = (PHEAP_ENTRY)Ptr - 1;
2604
2605 /* If that entry is not really in-use, we have a problem */
2606 if (!(InUseEntry->Flags & HEAP_ENTRY_BUSY))
2607 {
2608 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER);
2609
2610 /* Release the lock and return */
2611 if (HeapLocked)
2612 RtlLeaveHeapLock(Heap->LockVariable);
2613 return Ptr;
2614 }
2615
2616 if (InUseEntry->Flags & HEAP_ENTRY_VIRTUAL_ALLOC)
2617 {
2618 /* This is a virtually allocated block. Get its size */
2619 OldSize = RtlpGetSizeOfBigBlock(InUseEntry);
2620
2621 /* Convert it to an index */
2622 OldIndex = (OldSize + InUseEntry->Size) >> HEAP_ENTRY_SHIFT;
2623
2624 /* Calculate new allocation size and round it to the page size */
2625 AllocationSize += FIELD_OFFSET(HEAP_VIRTUAL_ALLOC_ENTRY, BusyBlock);
2626 AllocationSize = ROUND_UP(AllocationSize, PAGE_SIZE);
2627 }
2628 else
2629 {
2630 /* Usual entry */
2631 OldIndex = InUseEntry->Size;
2632
2633 OldSize = (OldIndex << HEAP_ENTRY_SHIFT) - InUseEntry->UnusedBytes;
2634 }
2635
2636 /* Calculate new index */
2637 Index = AllocationSize >> HEAP_ENTRY_SHIFT;
2638
2639 /* Check for 4 different scenarios (old size, new size, old index, new index) */
2640 if (Index <= OldIndex)
2641 {
2642 /* Difference must be greater than 1, adjust if it's not so */
2643 if (Index + 1 == OldIndex)
2644 {
2645 Index++;
2646 AllocationSize += sizeof(HEAP_ENTRY);
2647 }
2648
2649 /* Calculate new size */
2650 if (InUseEntry->Flags & HEAP_ENTRY_VIRTUAL_ALLOC)
2651 {
2652 /* Simple in case of a virtual alloc - just an unused size */
2653 InUseEntry->Size = (USHORT)(AllocationSize - Size);
2654 ASSERT(InUseEntry->Size >= sizeof(HEAP_VIRTUAL_ALLOC_ENTRY));
2655 }
2656 else if (InUseEntry->Flags & HEAP_ENTRY_EXTRA_PRESENT)
2657 {
2658 /* There is extra stuff, take it into account */
2659 OldExtra = (PHEAP_ENTRY_EXTRA)(InUseEntry + InUseEntry->Size - 1);
2660 NewExtra = (PHEAP_ENTRY_EXTRA)(InUseEntry + Index - 1);
2661 *NewExtra = *OldExtra;
2662
2663 // FIXME Tagging, TagIndex
2664
2665 /* Update unused bytes count */
2666 InUseEntry->UnusedBytes = (UCHAR)(AllocationSize - Size);
2667 }
2668 else
2669 {
2670 // FIXME Tagging, SmallTagIndex
2671 InUseEntry->UnusedBytes = (UCHAR)(AllocationSize - Size);
2672 }
2673
2674 /* If new size is bigger than the old size */
2675 if (Size > OldSize)
2676 {
2677 /* Zero out that additional space if required */
2678 if (Flags & HEAP_ZERO_MEMORY)
2679 {
2680 RtlZeroMemory((PCHAR)Ptr + OldSize, Size - OldSize);
2681 }
2682 else if (Heap->Flags & HEAP_FREE_CHECKING_ENABLED)
2683 {
2684 /* Fill it on free if required */
2685 RemainderBytes = OldSize & (sizeof(ULONG) - 1);
2686
2687 if (RemainderBytes)
2688 RemainderBytes = 4 - RemainderBytes;
2689
2690 if (Size > (OldSize + RemainderBytes))
2691 {
2692 /* Calculate actual amount of extra bytes to fill */
2693 ExtraSize = (Size - (OldSize + RemainderBytes)) & ~(sizeof(ULONG) - 1);
2694
2695 /* Fill them if there are any */
2696 if (ExtraSize != 0)
2697 {
2698 RtlFillMemoryUlong((PCHAR)(InUseEntry + 1) + OldSize + RemainderBytes,
2699 ExtraSize,
2700 ARENA_INUSE_FILLER);
2701 }
2702 }
2703 }
2704 }
2705
2706 /* Fill tail of the heap entry if required */
2707 if (Heap->Flags & HEAP_TAIL_CHECKING_ENABLED)
2708 {
2709 RtlFillMemory((PCHAR)(InUseEntry + 1) + Size,
2710 HEAP_ENTRY_SIZE,
2711 HEAP_TAIL_FILL);
2712 }
2713
2714 /* Check if the difference is significant or not */
2715 if (Index != OldIndex)
2716 {
2717 /* Save flags */
2718 FreeFlags = InUseEntry->Flags & ~HEAP_ENTRY_BUSY;
2719
2720 if (FreeFlags & HEAP_ENTRY_VIRTUAL_ALLOC)
2721 {
2722 /* This is a virtual block allocation */
2723 VirtualAllocBlock = CONTAINING_RECORD(InUseEntry, HEAP_VIRTUAL_ALLOC_ENTRY, BusyBlock);
2724
2725 // FIXME Tagging!
2726
2727 DecommitBase = (PCHAR)VirtualAllocBlock + AllocationSize;
2728 DecommitSize = (OldIndex << HEAP_ENTRY_SHIFT) - AllocationSize;
2729
2730 /* Release the memory */
2731 Status = ZwFreeVirtualMemory(NtCurrentProcess(),
2732 (PVOID *)&DecommitBase,
2733 &DecommitSize,
2734 MEM_RELEASE);
2735
2736 if (!NT_SUCCESS(Status))
2737 {
2738 DPRINT1("HEAP: Unable to release memory (pointer %p, size 0x%x), Status %08x\n", DecommitBase, DecommitSize, Status);
2739 }
2740 else
2741 {
2742 /* Otherwise reduce the commit size */
2743 VirtualAllocBlock->CommitSize -= DecommitSize;
2744 }
2745 }
2746 else
2747 {
2748 /* Reduce size of the block and possibly split it */
2749 SplitBlock = (PHEAP_FREE_ENTRY)(InUseEntry + Index);
2750
2751 /* Initialize this entry */
2752 SplitBlock->Flags = FreeFlags;
2753 SplitBlock->PreviousSize = (USHORT)Index;
2754 SplitBlock->SegmentOffset = InUseEntry->SegmentOffset;
2755
2756 /* Remember free size */
2757 FreeSize = InUseEntry->Size - Index;
2758
2759 /* Set new size */
2760 InUseEntry->Size = (USHORT)Index;
2761 InUseEntry->Flags &= ~HEAP_ENTRY_LAST_ENTRY;
2762
2763 /* Is that the last entry */
2764 if (FreeFlags & HEAP_ENTRY_LAST_ENTRY)
2765 {
2766 /* Set its size and insert it to the list */
2767 SplitBlock->Size = (USHORT)FreeSize;
2768 RtlpInsertFreeBlockHelper(Heap, SplitBlock, FreeSize, FALSE);
2769
2770 /* Update total free size */
2771 Heap->TotalFreeSize += FreeSize;
2772 }
2773 else
2774 {
2775 /* Get the block after that one */
2776 SplitBlock2 = (PHEAP_FREE_ENTRY)((PHEAP_ENTRY)SplitBlock + FreeSize);
2777
2778 if (SplitBlock2->Flags & HEAP_ENTRY_BUSY)
2779 {
2780 /* It's in use, add it here*/
2781 SplitBlock->Size = (USHORT)FreeSize;
2782
2783 /* Update previous size of the next entry */
2784 ((PHEAP_FREE_ENTRY)((PHEAP_ENTRY)SplitBlock + FreeSize))->PreviousSize = (USHORT)FreeSize;
2785
2786 /* Insert it to the list */
2787 RtlpInsertFreeBlockHelper(Heap, SplitBlock, FreeSize, FALSE);
2788
2789 /* Update total size */
2790 Heap->TotalFreeSize += FreeSize;
2791 }
2792 else
2793 {
2794 /* Next entry is free, so merge with it */
2795 SplitBlock->Flags = SplitBlock2->Flags;
2796
2797 /* Remove it, update total size */
2798 RtlpRemoveFreeBlock(Heap, SplitBlock2, FALSE, FALSE);
2799 Heap->TotalFreeSize -= SplitBlock2->Size;
2800
2801 /* Calculate total free size */
2802 FreeSize += SplitBlock2->Size;
2803
2804 if (FreeSize <= HEAP_MAX_BLOCK_SIZE)
2805 {
2806 SplitBlock->Size = (USHORT)FreeSize;
2807
2808 if (!(SplitBlock->Flags & HEAP_ENTRY_LAST_ENTRY))
2809 {
2810 /* Update previous size of the next entry */
2811 ((PHEAP_FREE_ENTRY)((PHEAP_ENTRY)SplitBlock + FreeSize))->PreviousSize = (USHORT)FreeSize;
2812 }
2813
2814 /* Insert the new one back and update total size */
2815 RtlpInsertFreeBlockHelper(Heap, SplitBlock, FreeSize, FALSE);
2816 Heap->TotalFreeSize += FreeSize;
2817 }
2818 else
2819 {
2820 /* Just add it */
2821 RtlpInsertFreeBlock(Heap, SplitBlock, FreeSize);
2822 }
2823 }
2824 }
2825 }
2826 }
2827 }
2828 else
2829 {
2830 /* We're growing the block */
2831 if ((InUseEntry->Flags & HEAP_ENTRY_VIRTUAL_ALLOC) ||
2832 !RtlpGrowBlockInPlace(Heap, Flags, InUseEntry, Size, Index))
2833 {
2834 /* Growing in place failed, so growing out of place */
2835 if (Flags & HEAP_REALLOC_IN_PLACE_ONLY)
2836 {
2837 DPRINT1("Realloc in place failed, but it was the only option\n");
2838 Ptr = NULL;
2839 }
2840 else
2841 {
2842 /* Clear tag bits */
2843 Flags &= ~HEAP_TAG_MASK;
2844
2845 /* Process extra stuff */
2846 if (InUseEntry->Flags & HEAP_ENTRY_EXTRA_PRESENT)
2847 {
2848 /* Preserve user settable flags */
2849 Flags &= ~HEAP_SETTABLE_USER_FLAGS;
2850
2851 Flags |= HEAP_SETTABLE_USER_VALUE | ((InUseEntry->Flags & HEAP_ENTRY_SETTABLE_FLAGS) << 4);
2852
2853 /* Get pointer to the old extra data */
2854 OldExtra = RtlpGetExtraStuffPointer(InUseEntry);
2855
2856 /* Save tag index if it was set */
2857 if (OldExtra->TagIndex &&
2858 !(OldExtra->TagIndex & HEAP_PSEUDO_TAG_FLAG))
2859 {
2860 Flags |= OldExtra->TagIndex << HEAP_TAG_SHIFT;
2861 }
2862 }
2863 else if (InUseEntry->SmallTagIndex)
2864 {
2865 /* Take small tag index into account */
2866 Flags |= InUseEntry->SmallTagIndex << HEAP_TAG_SHIFT;
2867 }
2868
2869 /* Allocate new block from the heap */
2870 NewBaseAddress = RtlAllocateHeap(HeapPtr,
2871 Flags & ~HEAP_ZERO_MEMORY,
2872 Size);
2873
2874 /* Proceed if it didn't fail */
2875 if (NewBaseAddress)
2876 {
2877 /* Get new entry pointer */
2878 NewInUseEntry = (PHEAP_ENTRY)NewBaseAddress - 1;
2879
2880 /* Process extra stuff if it exists */
2881 if (NewInUseEntry->Flags & HEAP_ENTRY_EXTRA_PRESENT)
2882 {
2883 NewExtra = RtlpGetExtraStuffPointer(NewInUseEntry);
2884
2885 if (InUseEntry->Flags & HEAP_ENTRY_EXTRA_PRESENT)
2886 {
2887 OldExtra = RtlpGetExtraStuffPointer(InUseEntry);
2888 NewExtra->Settable = OldExtra->Settable;
2889 }
2890 else
2891 {
2892 RtlZeroMemory(NewExtra, sizeof(*NewExtra));
2893 }
2894 }
2895
2896 /* Copy actual user bits */
2897 if (Size < OldSize)
2898 RtlMoveMemory(NewBaseAddress, Ptr, Size);
2899 else
2900 RtlMoveMemory(NewBaseAddress, Ptr, OldSize);
2901
2902 /* Zero remaining part if required */
2903 if (Size > OldSize &&
2904 (Flags & HEAP_ZERO_MEMORY))
2905 {
2906 RtlZeroMemory((PCHAR)NewBaseAddress + OldSize, Size - OldSize);
2907 }
2908
2909 /* Free the old block */
2910 RtlFreeHeap(HeapPtr, Flags, Ptr);
2911 }
2912
2913 Ptr = NewBaseAddress;
2914 }
2915 }
2916 }
2917
2918 /* Did resizing fail? */
2919 if (!Ptr && (Flags & HEAP_GENERATE_EXCEPTIONS))
2920 {
2921 /* Generate an exception if required */
2922 ExceptionRecord.ExceptionCode = STATUS_NO_MEMORY;
2923 ExceptionRecord.ExceptionRecord = NULL;
2924 ExceptionRecord.NumberParameters = 1;
2925 ExceptionRecord.ExceptionFlags = 0;
2926 ExceptionRecord.ExceptionInformation[0] = AllocationSize;
2927
2928 RtlRaiseException(&ExceptionRecord);
2929 }
2930
2931 /* Release the heap lock if it was acquired */
2932 if (HeapLocked)
2933 RtlLeaveHeapLock(Heap->LockVariable);
2934
2935 return Ptr;
2936 }
2937
2938
2939 /***********************************************************************
2940 * RtlCompactHeap
2941 *
2942 * @unimplemented
2943 */
2944 ULONG NTAPI
2945 RtlCompactHeap(HANDLE Heap,
2946 ULONG Flags)
2947 {
2948 UNIMPLEMENTED;
2949 return 0;
2950 }
2951
2952
2953 /***********************************************************************
2954 * RtlLockHeap
2955 * Attempts to acquire the critical section object for a specified heap.
2956 *
2957 * PARAMS
2958 * Heap [in] Handle of heap to lock for exclusive access
2959 *
2960 * RETURNS
2961 * TRUE: Success
2962 * FALSE: Failure
2963 *
2964 * @implemented
2965 */
2966 BOOLEAN NTAPI
2967 RtlLockHeap(IN HANDLE HeapPtr)
2968 {
2969 PHEAP Heap = (PHEAP)HeapPtr;
2970
2971 // FIXME Check for special heap
2972
2973 /* Check if it's really a heap */
2974 if (Heap->Signature != HEAP_SIGNATURE) return FALSE;
2975
2976 /* Lock if it's lockable */
2977 if (!(Heap->Flags & HEAP_NO_SERIALIZE))
2978 {
2979 RtlEnterHeapLock(Heap->LockVariable, TRUE);
2980 }
2981
2982 return TRUE;
2983 }
2984
2985
2986 /***********************************************************************
2987 * RtlUnlockHeap
2988 * Releases ownership of the critical section object.
2989 *
2990 * PARAMS
2991 * Heap [in] Handle to the heap to unlock
2992 *
2993 * RETURNS
2994 * TRUE: Success
2995 * FALSE: Failure
2996 *
2997 * @implemented
2998 */
2999 BOOLEAN NTAPI
3000 RtlUnlockHeap(HANDLE HeapPtr)
3001 {
3002 PHEAP Heap = (PHEAP)HeapPtr;
3003
3004 // FIXME Check for special heap
3005
3006 /* Check if it's really a heap */
3007 if (Heap->Signature != HEAP_SIGNATURE) return FALSE;
3008
3009 /* Unlock if it's lockable */
3010 if (!(Heap->Flags & HEAP_NO_SERIALIZE))
3011 {
3012 RtlLeaveHeapLock(Heap->LockVariable);
3013 }
3014
3015 return TRUE;
3016 }
3017
3018
3019 /***********************************************************************
3020 * RtlSizeHeap
3021 * PARAMS
3022 * Heap [in] Handle of heap
3023 * Flags [in] Heap size control flags
3024 * Ptr [in] Address of memory to return size for
3025 *
3026 * RETURNS
3027 * Size in bytes of allocated memory
3028 * 0xffffffff: Failure
3029 *
3030 * @implemented
3031 */
3032 SIZE_T NTAPI
3033 RtlSizeHeap(
3034 HANDLE HeapPtr,
3035 ULONG Flags,
3036 PVOID Ptr
3037 )
3038 {
3039 PHEAP Heap = (PHEAP)HeapPtr;
3040 PHEAP_ENTRY HeapEntry;
3041 SIZE_T EntrySize;
3042
3043 // FIXME This is a hack around missing SEH support!
3044 if (!Heap)
3045 {
3046 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_HANDLE);
3047 return (SIZE_T)-1;
3048 }
3049
3050 /* Force flags */
3051 Flags |= Heap->ForceFlags;
3052
3053 /* Call special heap */
3054 if (RtlpHeapIsSpecial(Flags))
3055 return RtlDebugSizeHeap(Heap, Flags, Ptr);
3056
3057 /* Get the heap entry pointer */
3058 HeapEntry = (PHEAP_ENTRY)Ptr - 1;
3059
3060 /* Return -1 if that entry is free */
3061 if (!(HeapEntry->Flags & HEAP_ENTRY_BUSY))
3062 {
3063 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER);
3064 return (SIZE_T)-1;
3065 }
3066
3067 /* Get size of this block depending if it's a usual or a big one */
3068 if (HeapEntry->Flags & HEAP_ENTRY_VIRTUAL_ALLOC)
3069 {
3070 EntrySize = RtlpGetSizeOfBigBlock(HeapEntry);
3071 }
3072 else
3073 {
3074 /* Calculate it */
3075 EntrySize = (HeapEntry->Size << HEAP_ENTRY_SHIFT) - HeapEntry->UnusedBytes;
3076 }
3077
3078 /* Return calculated size */
3079 return EntrySize;
3080 }
3081
3082 BOOLEAN NTAPI
3083 RtlpCheckInUsePattern(PHEAP_ENTRY HeapEntry)
3084 {
3085 SIZE_T Size, Result;
3086 PCHAR TailPart;
3087
3088 /* Calculate size */
3089 if (HeapEntry->Flags & HEAP_ENTRY_VIRTUAL_ALLOC)
3090 Size = RtlpGetSizeOfBigBlock(HeapEntry);
3091 else
3092 Size = (HeapEntry->Size << HEAP_ENTRY_SHIFT) - HeapEntry->UnusedBytes;
3093
3094 /* Calculate pointer to the tail part of the block */
3095 TailPart = (PCHAR)(HeapEntry + 1) + Size;
3096
3097 /* Compare tail pattern */
3098 Result = RtlCompareMemory(TailPart,
3099 FillPattern,
3100 HEAP_ENTRY_SIZE);
3101
3102 if (Result != HEAP_ENTRY_SIZE)
3103 {
3104 DPRINT1("HEAP: Heap entry (size %x) %p tail is modified at %p\n", Size, HeapEntry, TailPart + Result);
3105 return FALSE;
3106 }
3107
3108 /* All is fine */
3109 return TRUE;
3110 }
3111
3112 BOOLEAN NTAPI
3113 RtlpValidateHeapHeaders(
3114 PHEAP Heap,
3115 BOOLEAN Recalculate)
3116 {
3117 // We skip header validation for now
3118 return TRUE;
3119 }
3120
3121 BOOLEAN NTAPI
3122 RtlpValidateHeapEntry(
3123 PHEAP Heap,
3124 PHEAP_ENTRY HeapEntry)
3125 {
3126 BOOLEAN BigAllocation, EntryFound = FALSE;
3127 PHEAP_SEGMENT Segment;
3128 ULONG SegmentOffset;
3129
3130 /* Perform various consistency checks of this entry */
3131 if (!HeapEntry) goto invalid_entry;
3132 if ((ULONG_PTR)HeapEntry & (HEAP_ENTRY_SIZE - 1)) goto invalid_entry;
3133 if (!(HeapEntry->Flags & HEAP_ENTRY_BUSY)) goto invalid_entry;
3134
3135 BigAllocation = HeapEntry->Flags & HEAP_ENTRY_VIRTUAL_ALLOC;
3136 Segment = Heap->Segments[HeapEntry->SegmentOffset];
3137
3138 if (BigAllocation &&
3139 (((ULONG_PTR)HeapEntry & (PAGE_SIZE - 1)) != FIELD_OFFSET(HEAP_VIRTUAL_ALLOC_ENTRY, BusyBlock)))
3140 goto invalid_entry;
3141
3142 if (!BigAllocation && (HeapEntry->SegmentOffset >= HEAP_SEGMENTS ||
3143 !Segment ||
3144 HeapEntry < Segment->FirstEntry ||
3145 HeapEntry >= Segment->LastValidEntry))
3146 goto invalid_entry;
3147
3148 if ((HeapEntry->Flags & HEAP_ENTRY_FILL_PATTERN) &&
3149 !RtlpCheckInUsePattern(HeapEntry))
3150 goto invalid_entry;
3151
3152 /* Checks are done, if this is a virtual entry, that's all */
3153 if (HeapEntry->Flags & HEAP_ENTRY_VIRTUAL_ALLOC) return TRUE;
3154
3155 /* Go through segments and check if this entry fits into any of them */
3156 for (SegmentOffset = 0; SegmentOffset < HEAP_SEGMENTS; SegmentOffset++)
3157 {
3158 Segment = Heap->Segments[SegmentOffset];
3159 if (!Segment) continue;
3160
3161 if ((HeapEntry >= Segment->FirstEntry) &&
3162 (HeapEntry < Segment->LastValidEntry))
3163 {
3164 /* Got it */
3165 EntryFound = TRUE;
3166 break;
3167 }
3168 }
3169
3170 /* Return our result of finding entry in the segments */
3171 return EntryFound;
3172
3173 invalid_entry:
3174 DPRINT1("HEAP: Invalid heap entry %p in heap %p\n", HeapEntry, Heap);
3175 return FALSE;
3176 }
3177
3178 BOOLEAN NTAPI
3179 RtlpValidateHeapSegment(
3180 PHEAP Heap,
3181 PHEAP_SEGMENT Segment,
3182 UCHAR SegmentOffset,
3183 PULONG FreeEntriesCount,
3184 PSIZE_T TotalFreeSize,
3185 PSIZE_T TagEntries,
3186 PSIZE_T PseudoTagEntries)
3187 {
3188 PHEAP_UCR_DESCRIPTOR UcrDescriptor;
3189 PLIST_ENTRY UcrEntry;
3190 SIZE_T ByteSize, Size, Result;
3191 PHEAP_ENTRY CurrentEntry;
3192 ULONG UnCommittedPages;
3193 ULONG UnCommittedRanges;
3194 ULONG PreviousSize;
3195
3196 UnCommittedPages = 0;
3197 UnCommittedRanges = 0;
3198
3199 if (IsListEmpty(&Segment->UCRSegmentList))
3200 {
3201 UcrEntry = NULL;
3202 UcrDescriptor = NULL;
3203 }
3204 else
3205 {
3206 UcrEntry = Segment->UCRSegmentList.Flink;
3207 UcrDescriptor = CONTAINING_RECORD(UcrEntry, HEAP_UCR_DESCRIPTOR, SegmentEntry);
3208 }
3209
3210 if (Segment->BaseAddress == Heap)
3211 CurrentEntry = &Heap->Entry;
3212 else
3213 CurrentEntry = &Segment->Entry;
3214
3215 while (CurrentEntry < Segment->LastValidEntry)
3216 {
3217 if (UcrDescriptor &&
3218 ((PVOID)CurrentEntry >= UcrDescriptor->Address))
3219 {
3220 DPRINT1("HEAP: Entry %p is not inside uncommited range [%p .. %p)\n",
3221 CurrentEntry, UcrDescriptor->Address,
3222 (PCHAR)UcrDescriptor->Address + UcrDescriptor->Size);
3223
3224 return FALSE;
3225 }
3226
3227 PreviousSize = 0;
3228
3229 while (CurrentEntry < Segment->LastValidEntry)
3230 {
3231 if (PreviousSize != CurrentEntry->PreviousSize)
3232 {
3233 DPRINT1("HEAP: Entry %p has incorrect PreviousSize %x instead of %x\n",
3234 CurrentEntry, CurrentEntry->PreviousSize, PreviousSize);
3235
3236 return FALSE;
3237 }
3238
3239 PreviousSize = CurrentEntry->Size;
3240 Size = CurrentEntry->Size << HEAP_ENTRY_SHIFT;
3241
3242 if (CurrentEntry->Flags & HEAP_ENTRY_BUSY)
3243 {
3244 if (TagEntries)
3245 {
3246 UNIMPLEMENTED;
3247 }
3248
3249 /* Check fill pattern */
3250 if (CurrentEntry->Flags & HEAP_ENTRY_FILL_PATTERN)
3251 {
3252 if (!RtlpCheckInUsePattern(CurrentEntry))
3253 return FALSE;
3254 }
3255 }
3256 else
3257 {
3258 /* The entry is free, increase free entries count and total free size */
3259 *FreeEntriesCount = *FreeEntriesCount + 1;
3260 *TotalFreeSize += CurrentEntry->Size;
3261
3262 if ((Heap->Flags & HEAP_FREE_CHECKING_ENABLED) &&
3263 (CurrentEntry->Flags & HEAP_ENTRY_FILL_PATTERN))
3264 {
3265 ByteSize = Size - sizeof(HEAP_FREE_ENTRY);
3266
3267 if ((CurrentEntry->Flags & HEAP_ENTRY_EXTRA_PRESENT) &&
3268 (ByteSize > sizeof(HEAP_FREE_ENTRY_EXTRA)))
3269 {
3270 ByteSize -= sizeof(HEAP_FREE_ENTRY_EXTRA);
3271 }
3272
3273 Result = RtlCompareMemoryUlong((PCHAR)((PHEAP_FREE_ENTRY)CurrentEntry + 1),
3274 ByteSize,
3275 ARENA_FREE_FILLER);
3276
3277 if (Result != ByteSize)
3278 {
3279 DPRINT1("HEAP: Free heap block %p modified at %p after it was freed\n",
3280 CurrentEntry,
3281 (PCHAR)(CurrentEntry + 1) + Result);
3282
3283 return FALSE;
3284 }
3285 }
3286 }
3287
3288 if (CurrentEntry->SegmentOffset != SegmentOffset)
3289 {
3290 DPRINT1("HEAP: Heap entry %p SegmentOffset is incorrect %x (should be %x)\n",
3291 CurrentEntry, SegmentOffset, CurrentEntry->SegmentOffset);
3292 return FALSE;
3293 }
3294
3295 /* Check if it's the last entry */
3296 if (CurrentEntry->Flags & HEAP_ENTRY_LAST_ENTRY)
3297 {
3298 CurrentEntry = (PHEAP_ENTRY)((PCHAR)CurrentEntry + Size);
3299
3300 if (!UcrDescriptor)
3301 {
3302 /* Check if it's not really the last one */
3303 if (CurrentEntry != Segment->LastValidEntry)
3304 {
3305 DPRINT1("HEAP: Heap entry %p is not last block in segment (%p)\n",
3306 CurrentEntry, Segment->LastValidEntry);
3307 return FALSE;
3308 }
3309 }
3310 else if (CurrentEntry != UcrDescriptor->Address)
3311 {
3312 DPRINT1("HEAP: Heap entry %p does not match next uncommitted address (%p)\n",
3313 CurrentEntry, UcrDescriptor->Address);
3314
3315 return FALSE;
3316 }
3317 else
3318 {
3319 UnCommittedPages += (ULONG)(UcrDescriptor->Size / PAGE_SIZE);
3320 UnCommittedRanges++;
3321
3322 CurrentEntry = (PHEAP_ENTRY)((PCHAR)UcrDescriptor->Address + UcrDescriptor->Size);
3323
3324 /* Go to the next UCR descriptor */
3325 UcrEntry = UcrEntry->Flink;
3326 if (UcrEntry == &Segment->UCRSegmentList)
3327 {
3328 UcrEntry = NULL;
3329 UcrDescriptor = NULL;
3330 }
3331 else
3332 {
3333 UcrDescriptor = CONTAINING_RECORD(UcrEntry, HEAP_UCR_DESCRIPTOR, SegmentEntry);
3334 }
3335 }
3336
3337 break;
3338 }
3339
3340 /* Advance to the next entry */
3341 CurrentEntry = (PHEAP_ENTRY)((PCHAR)CurrentEntry + Size);
3342 }
3343 }
3344
3345 /* Check total numbers of UCP and UCR */
3346 if (Segment->NumberOfUnCommittedPages != UnCommittedPages)
3347 {
3348 DPRINT1("HEAP: Segment %p NumberOfUnCommittedPages is invalid (%x != %x)\n",
3349 Segment, Segment->NumberOfUnCommittedPages, UnCommittedPages);
3350
3351 return FALSE;
3352 }
3353
3354 if (Segment->NumberOfUnCommittedRanges != UnCommittedRanges)
3355 {
3356 DPRINT1("HEAP: Segment %p NumberOfUnCommittedRanges is invalid (%x != %x)\n",
3357 Segment, Segment->NumberOfUnCommittedRanges, UnCommittedRanges);
3358
3359 return FALSE;
3360 }
3361
3362 return TRUE;
3363 }
3364
3365 BOOLEAN NTAPI
3366 RtlpValidateHeap(PHEAP Heap,
3367 BOOLEAN ForceValidation)
3368 {
3369 PHEAP_SEGMENT Segment;
3370 BOOLEAN EmptyList;
3371 UCHAR SegmentOffset;
3372 SIZE_T Size, TotalFreeSize;
3373 ULONG PreviousSize;
3374 PHEAP_VIRTUAL_ALLOC_ENTRY VirtualAllocBlock;
3375 PLIST_ENTRY ListHead, NextEntry;
3376 PHEAP_FREE_ENTRY FreeEntry;
3377 ULONG FreeBlocksCount, FreeListEntriesCount;
3378
3379 /* Check headers */
3380 if (!RtlpValidateHeapHeaders(Heap, FALSE))
3381 return FALSE;
3382
3383 /* Skip validation if it's not needed */
3384 if (!ForceValidation && !(Heap->Flags & HEAP_VALIDATE_ALL_ENABLED))
3385 return TRUE;
3386
3387 /* Check free lists bitmaps */
3388 FreeListEntriesCount = 0;
3389 ListHead = &Heap->FreeLists[0];
3390
3391 for (Size = 0; Size < HEAP_FREELISTS; Size++)
3392 {
3393 if (Size)
3394 {
3395 /* This is a dedicated list. Check if it's empty */
3396 EmptyList = IsListEmpty(ListHead);
3397
3398 if (Heap->u.FreeListsInUseBytes[Size >> 3] & (1 << (Size & 7)))
3399 {
3400 if (EmptyList)
3401 {
3402 DPRINT1("HEAP: Empty %x-free list marked as non-empty\n", Size);
3403 return FALSE;
3404 }
3405 }
3406 else
3407 {
3408 if (!EmptyList)
3409 {
3410 DPRINT1("HEAP: Non-empty %x-free list marked as empty\n", Size);
3411 return FALSE;
3412 }
3413 }
3414 }
3415
3416 /* Now check this list entries */
3417 NextEntry = ListHead->Flink;
3418 PreviousSize = 0;
3419
3420 while (ListHead != NextEntry)
3421 {
3422 FreeEntry = CONTAINING_RECORD(NextEntry, HEAP_FREE_ENTRY, FreeList);
3423 NextEntry = NextEntry->Flink;
3424
3425 /* If there is an in-use entry in a free list - that's quite a big problem */
3426 if (FreeEntry->Flags & HEAP_ENTRY_BUSY)
3427 {
3428 DPRINT1("HEAP: %Ix-dedicated list free element %p is marked in-use\n", Size, FreeEntry);
3429 return FALSE;
3430 }
3431
3432 /* Check sizes according to that specific list's size */
3433 if ((Size == 0) && (FreeEntry->Size < HEAP_FREELISTS))
3434 {
3435 DPRINT1("HEAP: Non dedicated list free element %p has size %x which would fit a dedicated list\n", FreeEntry, FreeEntry->Size);
3436 return FALSE;
3437 }
3438 else if (Size && (FreeEntry->Size != Size))
3439 {
3440 DPRINT1("HEAP: %Ix-dedicated list free element %p has incorrect size %x\n", Size, FreeEntry, FreeEntry->Size);
3441 return FALSE;
3442 }
3443 else if ((Size == 0) && (FreeEntry->Size < PreviousSize))
3444 {
3445 DPRINT1("HEAP: Non dedicated list free element %p is not put in order\n", FreeEntry);
3446 return FALSE;
3447 }
3448
3449 /* Remember previous size*/
3450 PreviousSize = FreeEntry->Size;
3451
3452 /* Add up to the total amount of free entries */
3453 FreeListEntriesCount++;
3454 }
3455
3456 /* Go to the head of the next free list */
3457 ListHead++;
3458 }
3459
3460 /* Check big allocations */
3461 ListHead = &Heap->VirtualAllocdBlocks;
3462 NextEntry = ListHead->Flink;
3463
3464 while (ListHead != NextEntry)
3465 {
3466 VirtualAllocBlock = CONTAINING_RECORD(NextEntry, HEAP_VIRTUAL_ALLOC_ENTRY, Entry);
3467
3468 /* We can only check the fill pattern */
3469 if (VirtualAllocBlock->BusyBlock.Flags & HEAP_ENTRY_FILL_PATTERN)
3470 {
3471 if (!RtlpCheckInUsePattern(&VirtualAllocBlock->BusyBlock))
3472 return FALSE;
3473 }
3474
3475 NextEntry = NextEntry->Flink;
3476 }
3477
3478 /* Check all segments */
3479 FreeBlocksCount = 0;
3480 TotalFreeSize = 0;
3481
3482 for (SegmentOffset = 0; SegmentOffset < HEAP_SEGMENTS; SegmentOffset++)
3483 {
3484 Segment = Heap->Segments[SegmentOffset];
3485
3486 /* Go to the next one if there is no segment */
3487 if (!Segment) continue;
3488
3489 if (!RtlpValidateHeapSegment(Heap,
3490 Segment,
3491 SegmentOffset,
3492 &FreeBlocksCount,
3493 &TotalFreeSize,
3494 NULL,
3495 NULL))
3496 {
3497 return FALSE;
3498 }
3499 }
3500
3501 if (FreeListEntriesCount != FreeBlocksCount)
3502 {
3503 DPRINT1("HEAP: Free blocks count in arena (%lu) does not match free blocks number in the free lists (%lu)\n", FreeBlocksCount, FreeListEntriesCount);
3504 return FALSE;
3505 }
3506
3507 if (Heap->TotalFreeSize != TotalFreeSize)
3508 {
3509 DPRINT1("HEAP: Total size of free blocks in arena (%Iu) does not equal to the one in heap header (%Iu)\n", TotalFreeSize, Heap->TotalFreeSize);
3510 return FALSE;
3511 }
3512
3513 return TRUE;
3514 }
3515
3516 /***********************************************************************
3517 * RtlValidateHeap
3518 * Validates a specified heap.
3519 *
3520 * PARAMS
3521 * Heap [in] Handle to the heap
3522 * Flags [in] Bit flags that control access during operation
3523 * Block [in] Optional pointer to memory block to validate
3524 *
3525 * NOTES
3526 * Flags is ignored.
3527 *
3528 * RETURNS
3529 * TRUE: Success
3530 * FALSE: Failure
3531 *
3532 * @implemented
3533 */
3534 BOOLEAN NTAPI RtlValidateHeap(
3535 HANDLE HeapPtr,
3536 ULONG Flags,
3537 PVOID Block
3538 )
3539 {
3540 PHEAP Heap = (PHEAP)HeapPtr;
3541 BOOLEAN HeapLocked = FALSE;
3542 BOOLEAN HeapValid;
3543
3544 /* Check for page heap */
3545 if (Heap->ForceFlags & HEAP_FLAG_PAGE_ALLOCS)
3546 return RtlpDebugPageHeapValidate(HeapPtr, Flags, Block);
3547
3548 /* Check signature */
3549 if (Heap->Signature != HEAP_SIGNATURE)
3550 {
3551 DPRINT1("HEAP: Signature %lx is invalid for heap %p\n", Heap->Signature, Heap);
3552 return FALSE;
3553 }
3554
3555 /* Force flags */
3556 Flags = Heap->ForceFlags;
3557
3558 /* Acquire the lock if necessary */
3559 if (!(Flags & HEAP_NO_SERIALIZE))
3560 {
3561 RtlEnterHeapLock(Heap->LockVariable, TRUE);
3562 HeapLocked = TRUE;
3563 }
3564
3565 /* Either validate whole heap or just one entry */
3566 if (!Block)
3567 HeapValid = RtlpValidateHeap(Heap, TRUE);
3568 else
3569 HeapValid = RtlpValidateHeapEntry(Heap, (PHEAP_ENTRY)Block - 1);
3570
3571 /* Unlock if it's lockable */
3572 if (HeapLocked)
3573 {
3574 RtlLeaveHeapLock(Heap->LockVariable);
3575 }
3576
3577 return HeapValid;
3578 }
3579
3580 /*
3581 * @implemented
3582 */
3583 NTSTATUS NTAPI
3584 RtlEnumProcessHeaps(PHEAP_ENUMERATION_ROUTINE HeapEnumerationRoutine,
3585 PVOID lParam)
3586 {
3587 UNIMPLEMENTED;
3588 return STATUS_NOT_IMPLEMENTED;
3589 }
3590
3591
3592 /*
3593 * @implemented
3594 */
3595 ULONG NTAPI
3596 RtlGetProcessHeaps(ULONG count,
3597 HANDLE *heaps)
3598 {
3599 UNIMPLEMENTED;
3600 return 0;
3601 }
3602
3603
3604 /*
3605 * @implemented
3606 */
3607 BOOLEAN NTAPI
3608 RtlValidateProcessHeaps(VOID)
3609 {
3610 UNIMPLEMENTED;
3611 return TRUE;
3612 }
3613
3614
3615 /*
3616 * @unimplemented
3617 */
3618 BOOLEAN NTAPI
3619 RtlZeroHeap(
3620 IN PVOID HeapHandle,
3621 IN ULONG Flags
3622 )
3623 {
3624 UNIMPLEMENTED;
3625 return FALSE;
3626 }
3627
3628 /*
3629 * @implemented
3630 */
3631 BOOLEAN
3632 NTAPI
3633 RtlSetUserValueHeap(IN PVOID HeapHandle,
3634 IN ULONG Flags,
3635 IN PVOID BaseAddress,
3636 IN PVOID UserValue)
3637 {
3638 PHEAP Heap = (PHEAP)HeapHandle;
3639 PHEAP_ENTRY HeapEntry;
3640 PHEAP_ENTRY_EXTRA Extra;
3641 BOOLEAN HeapLocked = FALSE, ValueSet = FALSE;
3642
3643 /* Force flags */
3644 Flags |= Heap->Flags;
3645
3646 /* Call special heap */
3647 if (RtlpHeapIsSpecial(Flags))
3648 return RtlDebugSetUserValueHeap(Heap, Flags, BaseAddress, UserValue);
3649
3650 /* Lock if it's lockable */
3651 if (!(Heap->Flags & HEAP_NO_SERIALIZE))
3652 {
3653 RtlEnterHeapLock(Heap->LockVariable, TRUE);
3654 HeapLocked = TRUE;
3655 }
3656
3657 /* Get a pointer to the entry */
3658 HeapEntry = (PHEAP_ENTRY)BaseAddress - 1;
3659
3660 /* If it's a free entry - return error */
3661 if (!(HeapEntry->Flags & HEAP_ENTRY_BUSY))
3662 {
3663 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER);
3664
3665 /* Release the heap lock if it was acquired */
3666 if (HeapLocked)
3667 RtlLeaveHeapLock(Heap->LockVariable);
3668
3669 return FALSE;
3670 }
3671
3672 /* Check if this entry has an extra stuff associated with it */
3673 if (HeapEntry->Flags & HEAP_ENTRY_EXTRA_PRESENT)
3674 {
3675 /* Use extra to store the value */
3676 Extra = RtlpGetExtraStuffPointer(HeapEntry);
3677 Extra->Settable = (ULONG_PTR)UserValue;
3678
3679 /* Indicate that value was set */
3680 ValueSet = TRUE;
3681 }
3682
3683 /* Release the heap lock if it was acquired */
3684 if (HeapLocked)
3685 RtlLeaveHeapLock(Heap->LockVariable);
3686
3687 return ValueSet;
3688 }
3689
3690 /*
3691 * @implemented
3692 */
3693 BOOLEAN
3694 NTAPI
3695 RtlSetUserFlagsHeap(IN PVOID HeapHandle,
3696 IN ULONG Flags,
3697 IN PVOID BaseAddress,
3698 IN ULONG UserFlagsReset,
3699 IN ULONG UserFlagsSet)
3700 {
3701 PHEAP Heap = (PHEAP)HeapHandle;
3702 PHEAP_ENTRY HeapEntry;
3703 BOOLEAN HeapLocked = FALSE;
3704
3705 /* Force flags */
3706 Flags |= Heap->Flags;
3707
3708 /* Call special heap */
3709 if (RtlpHeapIsSpecial(Flags))
3710 return RtlDebugSetUserFlagsHeap(Heap, Flags, BaseAddress, UserFlagsReset, UserFlagsSet);
3711
3712 /* Lock if it's lockable */
3713 if (!(Heap->Flags & HEAP_NO_SERIALIZE))
3714 {
3715 RtlEnterHeapLock(Heap->LockVariable, TRUE);
3716 HeapLocked = TRUE;
3717 }
3718
3719 /* Get a pointer to the entry */
3720 HeapEntry = (PHEAP_ENTRY)BaseAddress - 1;
3721
3722 /* If it's a free entry - return error */
3723 if (!(HeapEntry->Flags & HEAP_ENTRY_BUSY))
3724 {
3725 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER);
3726
3727 /* Release the heap lock if it was acquired */
3728 if (HeapLocked)
3729 RtlLeaveHeapLock(Heap->LockVariable);
3730
3731 return FALSE;
3732 }
3733
3734 /* Set / reset flags */
3735 HeapEntry->Flags &= ~(UserFlagsReset >> 4);
3736 HeapEntry->Flags |= (UserFlagsSet >> 4);
3737
3738 /* Release the heap lock if it was acquired */
3739 if (HeapLocked)
3740 RtlLeaveHeapLock(Heap->LockVariable);
3741
3742 return TRUE;
3743 }
3744
3745 /*
3746 * @implemented
3747 */
3748 BOOLEAN
3749 NTAPI
3750 RtlGetUserInfoHeap(IN PVOID HeapHandle,
3751 IN ULONG Flags,
3752 IN PVOID BaseAddress,
3753 OUT PVOID *UserValue,
3754 OUT PULONG UserFlags)
3755 {
3756 PHEAP Heap = (PHEAP)HeapHandle;
3757 PHEAP_ENTRY HeapEntry;
3758 PHEAP_ENTRY_EXTRA Extra;
3759 BOOLEAN HeapLocked = FALSE;
3760
3761 /* Force flags */
3762 Flags |= Heap->Flags;
3763
3764 /* Call special heap */
3765 if (RtlpHeapIsSpecial(Flags))
3766 return RtlDebugGetUserInfoHeap(Heap, Flags, BaseAddress, UserValue, UserFlags);
3767
3768 /* Lock if it's lockable */
3769 if (!(Heap->Flags & HEAP_NO_SERIALIZE))
3770 {
3771 RtlEnterHeapLock(Heap->LockVariable, TRUE);
3772 HeapLocked = TRUE;
3773 }
3774
3775 /* Get a pointer to the entry */
3776 HeapEntry = (PHEAP_ENTRY)BaseAddress - 1;
3777
3778 /* If it's a free entry - return error */
3779 if (!(HeapEntry->Flags & HEAP_ENTRY_BUSY))
3780 {
3781 RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_INVALID_PARAMETER);
3782
3783 /* Release the heap lock if it was acquired */
3784 if (HeapLocked)
3785 RtlLeaveHeapLock(Heap->LockVariable);
3786
3787 return FALSE;
3788 }
3789
3790 /* Check if this entry has an extra stuff associated with it */
3791 if (HeapEntry->Flags & HEAP_ENTRY_EXTRA_PRESENT)
3792 {
3793 /* Get pointer to extra data */
3794 Extra = RtlpGetExtraStuffPointer(HeapEntry);
3795
3796 /* Pass user value */
3797 if (UserValue)
3798 *UserValue = (PVOID)Extra->Settable;
3799 }
3800
3801 /* Decode and return user flags */
3802 if (UserFlags)
3803 *UserFlags = (HeapEntry->Flags & HEAP_ENTRY_SETTABLE_FLAGS) << 4;
3804
3805 /* Release the heap lock if it was acquired */
3806 if (HeapLocked)
3807 RtlLeaveHeapLock(Heap->LockVariable);
3808
3809 return TRUE;
3810 }
3811
3812 /*
3813 * @unimplemented
3814 */
3815 NTSTATUS
3816 NTAPI
3817 RtlUsageHeap(IN HANDLE Heap,
3818 IN ULONG Flags,
3819 OUT PRTL_HEAP_USAGE Usage)
3820 {
3821 /* TODO */
3822 UNIMPLEMENTED;
3823 return STATUS_NOT_IMPLEMENTED;
3824 }
3825
3826 PWSTR
3827 NTAPI
3828 RtlQueryTagHeap(IN PVOID HeapHandle,
3829 IN ULONG Flags,
3830 IN USHORT TagIndex,
3831 IN BOOLEAN ResetCounters,
3832 OUT PRTL_HEAP_TAG_INFO HeapTagInfo)
3833 {
3834 /* TODO */
3835 UNIMPLEMENTED;
3836 return NULL;
3837 }
3838
3839 ULONG
3840 NTAPI
3841 RtlExtendHeap(IN HANDLE Heap,
3842 IN ULONG Flags,
3843 IN PVOID P,
3844 IN SIZE_T Size)
3845 {
3846 /* TODO */
3847 UNIMPLEMENTED;
3848 return 0;
3849 }
3850
3851 ULONG
3852 NTAPI
3853 RtlCreateTagHeap(IN HANDLE HeapHandle,
3854 IN ULONG Flags,
3855 IN PWSTR TagName,
3856 IN PWSTR TagSubName)
3857 {
3858 /* TODO */
3859 UNIMPLEMENTED;
3860 return 0;
3861 }
3862
3863 NTSTATUS
3864 NTAPI
3865 RtlWalkHeap(IN HANDLE HeapHandle,
3866 IN PVOID HeapEntry)
3867 {
3868 UNIMPLEMENTED;
3869 return STATUS_NOT_IMPLEMENTED;
3870 }
3871
3872 PVOID
3873 NTAPI
3874 RtlProtectHeap(IN PVOID HeapHandle,
3875 IN BOOLEAN ReadOnly)
3876 {
3877 UNIMPLEMENTED;
3878 return NULL;
3879 }
3880
3881 NTSTATUS
3882 NTAPI
3883 RtlSetHeapInformation(IN HANDLE HeapHandle OPTIONAL,
3884 IN HEAP_INFORMATION_CLASS HeapInformationClass,
3885 IN PVOID HeapInformation,
3886 IN SIZE_T HeapInformationLength)
3887 {
3888 /* Setting heap information is not really supported except for enabling LFH */
3889 if (HeapInformationClass == HeapCompatibilityInformation)
3890 {
3891 /* Check buffer length */
3892 if (HeapInformationLength < sizeof(ULONG))
3893 {
3894 /* The provided buffer is too small */
3895 return STATUS_BUFFER_TOO_SMALL;
3896 }
3897
3898 /* Check for a special magic value for enabling LFH */
3899 if (*(PULONG)HeapInformation != 2)
3900 {
3901 return STATUS_UNSUCCESSFUL;
3902 }
3903
3904 DPRINT1("RtlSetHeapInformation() needs to enable LFH\n");
3905 return STATUS_SUCCESS;
3906 }
3907
3908 return STATUS_SUCCESS;
3909 }
3910
3911 NTSTATUS
3912 NTAPI
3913 RtlQueryHeapInformation(HANDLE HeapHandle,
3914 HEAP_INFORMATION_CLASS HeapInformationClass,
3915 PVOID HeapInformation,
3916 SIZE_T HeapInformationLength,
3917 PSIZE_T ReturnLength OPTIONAL)
3918 {
3919 PHEAP Heap = (PHEAP)HeapHandle;
3920
3921 /* Only HeapCompatibilityInformation is supported */
3922 if (HeapInformationClass == HeapCompatibilityInformation)
3923 {
3924 /* Set result length */
3925 if (ReturnLength)
3926 *ReturnLength = sizeof(ULONG);
3927
3928 /* Check buffer length */
3929 if (HeapInformationLength < sizeof(ULONG))
3930 {
3931 /* It's too small, return needed length */
3932 return STATUS_BUFFER_TOO_SMALL;
3933 }
3934
3935 /* Return front end heap type */
3936 *(PULONG)HeapInformation = Heap->FrontEndHeapType;
3937
3938 return STATUS_SUCCESS;
3939 }
3940
3941 return STATUS_UNSUCCESSFUL;
3942 }
3943
3944 NTSTATUS
3945 NTAPI
3946 RtlMultipleAllocateHeap(IN PVOID HeapHandle,
3947 IN ULONG Flags,
3948 IN SIZE_T Size,
3949 IN ULONG Count,
3950 OUT PVOID *Array)
3951 {
3952 UNIMPLEMENTED;
3953 return 0;
3954 }
3955
3956 NTSTATUS
3957 NTAPI
3958 RtlMultipleFreeHeap(IN PVOID HeapHandle,
3959 IN ULONG Flags,
3960 IN ULONG Count,
3961 OUT PVOID *Array)
3962 {
3963 UNIMPLEMENTED;
3964 return 0;
3965 }
3966
3967 /* EOF */