2 * PROJECT: ReactOS Kernel
3 * LICENSE: BSD - See COPYING.ARM in the top level directory
4 * FILE: ntoskrnl/mm/ARM3/virtual.c
5 * PURPOSE: ARM Memory Manager Virtual Memory Management
6 * PROGRAMMERS: ReactOS Portable Systems Group
9 /* INCLUDES *******************************************************************/
10 /* So long, and Thanks for All the Fish */
16 #define MODULE_INVOLVED_IN_ARM3
17 #include "../ARM3/miarm.h"
19 #define MI_MAPPED_COPY_PAGES 14
20 #define MI_POOL_COPY_BYTES 512
21 #define MI_MAX_TRANSFER_SIZE 64 * 1024
24 MiProtectVirtualMemory(IN PEPROCESS Process
,
25 IN OUT PVOID
*BaseAddress
,
26 IN OUT PSIZE_T NumberOfBytesToProtect
,
27 IN ULONG NewAccessProtection
,
28 OUT PULONG OldAccessProtection OPTIONAL
);
32 MiFlushTbAndCapture(IN PMMVAD FoundVad
,
34 IN ULONG ProtectionMask
,
36 IN BOOLEAN CaptureDirtyBit
);
39 /* PRIVATE FUNCTIONS **********************************************************/
43 MiCalculatePageCommitment(IN ULONG_PTR StartingAddress
,
44 IN ULONG_PTR EndingAddress
,
48 PMMPTE PointerPte
, LastPte
, PointerPde
;
51 /* Compute starting and ending PTE and PDE addresses */
52 PointerPde
= MiAddressToPde(StartingAddress
);
53 PointerPte
= MiAddressToPte(StartingAddress
);
54 LastPte
= MiAddressToPte(EndingAddress
);
56 /* Handle commited pages first */
57 if (Vad
->u
.VadFlags
.MemCommit
== 1)
59 /* This is a committed VAD, so Assume the whole range is committed */
60 CommittedPages
= BYTES_TO_PAGES(EndingAddress
- StartingAddress
);
62 /* Is the PDE demand-zero? */
63 PointerPde
= MiAddressToPte(PointerPte
);
64 if (PointerPde
->u
.Long
!= 0)
66 /* It is not. Is it valid? */
67 if (PointerPde
->u
.Hard
.Valid
== 0)
70 PointerPte
= MiPteToAddress(PointerPde
);
71 MiMakeSystemAddressValid(PointerPte
, Process
);
76 /* It is, skip it and move to the next PDE, unless we're done */
78 PointerPte
= MiPteToAddress(PointerPde
);
79 if (PointerPte
> LastPte
) return CommittedPages
;
82 /* Now loop all the PTEs in the range */
83 while (PointerPte
<= LastPte
)
85 /* Have we crossed a PDE boundary? */
86 if (MiIsPteOnPdeBoundary(PointerPte
))
88 /* Is this PDE demand zero? */
89 PointerPde
= MiAddressToPte(PointerPte
);
90 if (PointerPde
->u
.Long
!= 0)
92 /* It isn't -- is it valid? */
93 if (PointerPde
->u
.Hard
.Valid
== 0)
95 /* Nope, fault it in */
96 PointerPte
= MiPteToAddress(PointerPde
);
97 MiMakeSystemAddressValid(PointerPte
, Process
);
102 /* It is, skip it and move to the next PDE */
104 PointerPte
= MiPteToAddress(PointerPde
);
109 /* Is this PTE demand zero? */
110 if (PointerPte
->u
.Long
!= 0)
112 /* It isn't -- is it a decommited, invalid, or faulted PTE? */
113 if ((PointerPte
->u
.Soft
.Protection
== MM_DECOMMIT
) &&
114 (PointerPte
->u
.Hard
.Valid
== 0) &&
115 ((PointerPte
->u
.Soft
.Prototype
== 0) ||
116 (PointerPte
->u
.Soft
.PageFileHigh
== MI_PTE_LOOKUP_NEEDED
)))
118 /* It is, so remove it from the count of commited pages */
123 /* Move to the next PTE */
127 /* Return how many committed pages there still are */
128 return CommittedPages
;
131 /* This is a non-commited VAD, so assume none of it is committed */
134 /* Is the PDE demand-zero? */
135 PointerPde
= MiAddressToPte(PointerPte
);
136 if (PointerPde
->u
.Long
!= 0)
138 /* It isn't -- is it invalid? */
139 if (PointerPde
->u
.Hard
.Valid
== 0)
141 /* It is, so page it in */
142 PointerPte
= MiPteToAddress(PointerPde
);
143 MiMakeSystemAddressValid(PointerPte
, Process
);
148 /* It is, so skip it and move to the next PDE */
150 PointerPte
= MiPteToAddress(PointerPde
);
151 if (PointerPte
> LastPte
) return CommittedPages
;
154 /* Loop all the PTEs in this PDE */
155 while (PointerPte
<= LastPte
)
157 /* Have we crossed a PDE boundary? */
158 if (MiIsPteOnPdeBoundary(PointerPte
))
160 /* Is this new PDE demand-zero? */
161 PointerPde
= MiAddressToPte(PointerPte
);
162 if (PointerPde
->u
.Long
!= 0)
164 /* It isn't. Is it valid? */
165 if (PointerPde
->u
.Hard
.Valid
== 0)
167 /* It isn't, so make it valid */
168 PointerPte
= MiPteToAddress(PointerPde
);
169 MiMakeSystemAddressValid(PointerPte
, Process
);
174 /* It is, so skip it and move to the next one */
176 PointerPte
= MiPteToAddress(PointerPde
);
181 /* Is this PTE demand-zero? */
182 if (PointerPte
->u
.Long
!= 0)
184 /* Nope. Is it a valid, non-decommited, non-paged out PTE? */
185 if ((PointerPte
->u
.Soft
.Protection
!= MM_DECOMMIT
) ||
186 (PointerPte
->u
.Hard
.Valid
== 1) ||
187 ((PointerPte
->u
.Soft
.Prototype
== 1) &&
188 (PointerPte
->u
.Soft
.PageFileHigh
!= MI_PTE_LOOKUP_NEEDED
)))
190 /* It is! So we'll treat this as a committed page */
195 /* Move to the next PTE */
199 /* Return how many committed pages we found in this VAD */
200 return CommittedPages
;
205 MiMakeSystemAddressValid(IN PVOID PageTableVirtualAddress
,
206 IN PEPROCESS CurrentProcess
)
209 BOOLEAN WsShared
= FALSE
, WsSafe
= FALSE
, LockChange
= FALSE
;
210 PETHREAD CurrentThread
= PsGetCurrentThread();
212 /* Must be a non-pool page table, since those are double-mapped already */
213 ASSERT(PageTableVirtualAddress
> MM_HIGHEST_USER_ADDRESS
);
214 ASSERT((PageTableVirtualAddress
< MmPagedPoolStart
) ||
215 (PageTableVirtualAddress
> MmPagedPoolEnd
));
217 /* Working set lock or PFN lock should be held */
218 ASSERT(KeAreAllApcsDisabled() == TRUE
);
220 /* Check if the page table is valid */
221 while (!MmIsAddressValid(PageTableVirtualAddress
))
223 /* Release the working set lock */
224 MiUnlockProcessWorkingSetForFault(CurrentProcess
,
230 Status
= MmAccessFault(FALSE
, PageTableVirtualAddress
, KernelMode
, NULL
);
231 if (!NT_SUCCESS(Status
))
233 /* This should not fail */
234 KeBugCheckEx(KERNEL_DATA_INPAGE_ERROR
,
237 (ULONG_PTR
)CurrentProcess
,
238 (ULONG_PTR
)PageTableVirtualAddress
);
241 /* Lock the working set again */
242 MiLockProcessWorkingSetForFault(CurrentProcess
,
247 /* This flag will be useful later when we do better locking */
251 /* Let caller know what the lock state is */
257 MiMakeSystemAddressValidPfn(IN PVOID VirtualAddress
,
261 BOOLEAN LockChange
= FALSE
;
263 /* Must be e kernel address */
264 ASSERT(VirtualAddress
> MM_HIGHEST_USER_ADDRESS
);
266 /* Check if the page is valid */
267 while (!MmIsAddressValid(VirtualAddress
))
269 /* Release the PFN database */
270 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
273 Status
= MmAccessFault(FALSE
, VirtualAddress
, KernelMode
, NULL
);
274 if (!NT_SUCCESS(Status
))
276 /* This should not fail */
277 KeBugCheckEx(KERNEL_DATA_INPAGE_ERROR
,
281 (ULONG_PTR
)VirtualAddress
);
284 /* This flag will be useful later when we do better locking */
287 /* Lock the PFN database */
288 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
291 /* Let caller know what the lock state is */
297 MiDeleteSystemPageableVm(IN PMMPTE PointerPte
,
298 IN PFN_NUMBER PageCount
,
300 OUT PPFN_NUMBER ValidPages
)
302 PFN_COUNT ActualPages
= 0;
303 PETHREAD CurrentThread
= PsGetCurrentThread();
305 PFN_NUMBER PageFrameIndex
, PageTableIndex
;
307 ASSERT(KeGetCurrentIrql() <= APC_LEVEL
);
309 /* Lock the system working set */
310 MiLockWorkingSet(CurrentThread
, &MmSystemCacheWs
);
315 /* Make sure there's some data about the page */
316 if (PointerPte
->u
.Long
)
318 /* As always, only handle current ARM3 scenarios */
319 ASSERT(PointerPte
->u
.Soft
.Prototype
== 0);
320 ASSERT(PointerPte
->u
.Soft
.Transition
== 0);
322 /* Normally this is one possibility -- freeing a valid page */
323 if (PointerPte
->u
.Hard
.Valid
)
325 /* Get the page PFN */
326 PageFrameIndex
= PFN_FROM_PTE(PointerPte
);
327 Pfn1
= MiGetPfnEntry(PageFrameIndex
);
329 /* Should not have any working set data yet */
330 ASSERT(Pfn1
->u1
.WsIndex
== 0);
332 /* Actual valid, legitimate, pages */
333 if (ValidPages
) (*ValidPages
)++;
335 /* Get the page table entry */
336 PageTableIndex
= Pfn1
->u4
.PteFrame
;
337 Pfn2
= MiGetPfnEntry(PageTableIndex
);
339 /* Lock the PFN database */
340 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
342 /* Delete it the page */
343 MI_SET_PFN_DELETED(Pfn1
);
344 MiDecrementShareCount(Pfn1
, PageFrameIndex
);
346 /* Decrement the page table too */
347 MiDecrementShareCount(Pfn2
, PageTableIndex
);
349 /* Release the PFN database */
350 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
352 /* Destroy the PTE */
353 MI_ERASE_PTE(PointerPte
);
358 * The only other ARM3 possibility is a demand zero page, which would
359 * mean freeing some of the paged pool pages that haven't even been
360 * touched yet, as part of a larger allocation.
362 * Right now, we shouldn't expect any page file information in the PTE
364 ASSERT(PointerPte
->u
.Soft
.PageFileHigh
== 0);
366 /* Destroy the PTE */
367 MI_ERASE_PTE(PointerPte
);
370 /* Actual legitimate pages */
379 /* Release the working set */
380 MiUnlockWorkingSet(CurrentThread
, &MmSystemCacheWs
);
382 /* Flush the entire TLB */
383 KeFlushEntireTb(TRUE
, TRUE
);
391 MiDeletePte(IN PMMPTE PointerPte
,
392 IN PVOID VirtualAddress
,
393 IN PEPROCESS CurrentProcess
,
394 IN PMMPTE PrototypePte
)
398 PFN_NUMBER PageFrameIndex
;
401 /* PFN lock must be held */
402 ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL
);
404 /* Capture the PTE */
405 TempPte
= *PointerPte
;
407 /* We only support valid PTEs for now */
408 ASSERT(TempPte
.u
.Hard
.Valid
== 1);
409 if (TempPte
.u
.Hard
.Valid
== 0)
411 /* Invalid PTEs not supported yet */
412 ASSERT(TempPte
.u
.Soft
.Prototype
== 0);
413 ASSERT(TempPte
.u
.Soft
.Transition
== 0);
416 /* Get the PFN entry */
417 PageFrameIndex
= PFN_FROM_PTE(&TempPte
);
418 Pfn1
= MiGetPfnEntry(PageFrameIndex
);
420 /* Check if this is a valid, prototype PTE */
421 if (Pfn1
->u3
.e1
.PrototypePte
== 1)
423 /* Get the PDE and make sure it's faulted in */
424 PointerPde
= MiPteToPde(PointerPte
);
425 if (PointerPde
->u
.Hard
.Valid
== 0)
427 #if (_MI_PAGING_LEVELS == 2)
428 /* Could be paged pool access from a new process -- synchronize the page directories */
429 if (!NT_SUCCESS(MiCheckPdeForPagedPool(VirtualAddress
)))
432 /* The PDE must be valid at this point */
433 KeBugCheckEx(MEMORY_MANAGEMENT
,
435 (ULONG_PTR
)PointerPte
,
437 (ULONG_PTR
)VirtualAddress
);
439 #if (_MI_PAGING_LEVELS == 2)
442 /* Drop the share count */
443 MiDecrementShareCount(Pfn1
, PageFrameIndex
);
445 /* Either a fork, or this is the shared user data page */
446 if ((PointerPte
<= MiHighestUserPte
) && (PrototypePte
!= Pfn1
->PteAddress
))
448 /* If it's not the shared user page, then crash, since there's no fork() yet */
449 if ((PAGE_ALIGN(VirtualAddress
) != (PVOID
)USER_SHARED_DATA
) ||
450 (MmHighestUserAddress
<= (PVOID
)USER_SHARED_DATA
))
452 /* Must be some sort of memory corruption */
453 KeBugCheckEx(MEMORY_MANAGEMENT
,
455 (ULONG_PTR
)PointerPte
,
456 (ULONG_PTR
)PrototypePte
,
457 (ULONG_PTR
)Pfn1
->PteAddress
);
463 /* Make sure the saved PTE address is valid */
464 if ((PMMPTE
)((ULONG_PTR
)Pfn1
->PteAddress
& ~0x1) != PointerPte
)
466 /* The PFN entry is illegal, or invalid */
467 KeBugCheckEx(MEMORY_MANAGEMENT
,
469 (ULONG_PTR
)PointerPte
,
471 (ULONG_PTR
)Pfn1
->PteAddress
);
474 /* There should only be 1 shared reference count */
475 ASSERT(Pfn1
->u2
.ShareCount
== 1);
477 /* Drop the reference on the page table. */
478 MiDecrementShareCount(MiGetPfnEntry(Pfn1
->u4
.PteFrame
), Pfn1
->u4
.PteFrame
);
480 /* Mark the PFN for deletion and dereference what should be the last ref */
481 MI_SET_PFN_DELETED(Pfn1
);
482 MiDecrementShareCount(Pfn1
, PageFrameIndex
);
484 /* We should eventually do this */
485 //CurrentProcess->NumberOfPrivatePages--;
488 /* Destroy the PTE and flush the TLB */
489 MI_ERASE_PTE(PointerPte
);
495 MiDeleteVirtualAddresses(IN ULONG_PTR Va
,
496 IN ULONG_PTR EndingAddress
,
499 PMMPTE PointerPte
, PrototypePte
, LastPrototypePte
;
502 PEPROCESS CurrentProcess
;
504 BOOLEAN AddressGap
= FALSE
;
505 PSUBSECTION Subsection
;
507 /* Get out if this is a fake VAD, RosMm will free the marea pages */
508 if ((Vad
) && (Vad
->u
.VadFlags
.Spare
== 1)) return;
510 /* Grab the process and PTE/PDE for the address being deleted */
511 CurrentProcess
= PsGetCurrentProcess();
512 PointerPde
= MiAddressToPde(Va
);
513 PointerPte
= MiAddressToPte(Va
);
515 /* Check if this is a section VAD or a VM VAD */
516 if (!(Vad
) || (Vad
->u
.VadFlags
.PrivateMemory
) || !(Vad
->FirstPrototypePte
))
518 /* Don't worry about prototypes */
519 PrototypePte
= LastPrototypePte
= NULL
;
523 /* Get the prototype PTE */
524 PrototypePte
= Vad
->FirstPrototypePte
;
525 LastPrototypePte
= Vad
->FirstPrototypePte
+ 1;
528 /* In all cases, we don't support fork() yet */
529 ASSERT(CurrentProcess
->CloneRoot
== NULL
);
531 /* Loop the PTE for each VA */
534 /* First keep going until we find a valid PDE */
535 while (!PointerPde
->u
.Long
)
537 /* There are gaps in the address space */
540 /* Still no valid PDE, try the next 4MB (or whatever) */
543 /* Update the PTE on this new boundary */
544 PointerPte
= MiPteToAddress(PointerPde
);
546 /* Check if all the PDEs are invalid, so there's nothing to free */
547 Va
= (ULONG_PTR
)MiPteToAddress(PointerPte
);
548 if (Va
> EndingAddress
) return;
551 /* Now check if the PDE is mapped in */
552 if (!PointerPde
->u
.Hard
.Valid
)
554 /* It isn't, so map it in */
555 PointerPte
= MiPteToAddress(PointerPde
);
556 MiMakeSystemAddressValid(PointerPte
, CurrentProcess
);
559 /* Now we should have a valid PDE, mapped in, and still have some VA */
560 ASSERT(PointerPde
->u
.Hard
.Valid
== 1);
561 ASSERT(Va
<= EndingAddress
);
563 /* Check if this is a section VAD with gaps in it */
564 if ((AddressGap
) && (LastPrototypePte
))
566 /* We need to skip to the next correct prototype PTE */
567 PrototypePte
= MI_GET_PROTOTYPE_PTE_FOR_VPN(Vad
, Va
>> PAGE_SHIFT
);
569 /* And we need the subsection to skip to the next last prototype PTE */
570 Subsection
= MiLocateSubsection(Vad
, Va
>> PAGE_SHIFT
);
574 LastPrototypePte
= &Subsection
->SubsectionBase
[Subsection
->PtesInSubsection
];
578 /* No more subsections, we are done with prototype PTEs */
583 /* Lock the PFN Database while we delete the PTEs */
584 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
587 /* Capture the PDE and make sure it exists */
588 TempPte
= *PointerPte
;
591 MiDecrementPageTableReferences((PVOID
)Va
);
593 /* Check if the PTE is actually mapped in */
594 if (MI_IS_MAPPED_PTE(&TempPte
))
596 /* Are we dealing with section VAD? */
597 if ((LastPrototypePte
) && (PrototypePte
> LastPrototypePte
))
599 /* We need to skip to the next correct prototype PTE */
600 PrototypePte
= MI_GET_PROTOTYPE_PTE_FOR_VPN(Vad
, Va
>> PAGE_SHIFT
);
602 /* And we need the subsection to skip to the next last prototype PTE */
603 Subsection
= MiLocateSubsection(Vad
, Va
>> PAGE_SHIFT
);
607 LastPrototypePte
= &Subsection
->SubsectionBase
[Subsection
->PtesInSubsection
];
611 /* No more subsections, we are done with prototype PTEs */
616 /* Check for prototype PTE */
617 if ((TempPte
.u
.Hard
.Valid
== 0) &&
618 (TempPte
.u
.Soft
.Prototype
== 1))
621 MI_ERASE_PTE(PointerPte
);
625 /* Delete the PTE proper */
626 MiDeletePte(PointerPte
,
634 /* The PTE was never mapped, just nuke it here */
635 MI_ERASE_PTE(PointerPte
);
639 /* Update the address and PTE for it */
644 /* Making sure the PDE is still valid */
645 ASSERT(PointerPde
->u
.Hard
.Valid
== 1);
647 while ((Va
& (PDE_MAPPED_VA
- 1)) && (Va
<= EndingAddress
));
649 /* The PDE should still be valid at this point */
650 ASSERT(PointerPde
->u
.Hard
.Valid
== 1);
652 /* Check remaining PTE count (go back 1 page due to above loop) */
653 if (MiQueryPageTableReferences((PVOID
)(Va
- PAGE_SIZE
)) == 0)
655 if (PointerPde
->u
.Long
!= 0)
657 /* Delete the PTE proper */
658 MiDeletePte(PointerPde
,
659 MiPteToAddress(PointerPde
),
665 /* Release the lock and get out if we're done */
666 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
667 if (Va
> EndingAddress
) return;
669 /* Otherwise, we exited because we hit a new PDE boundary, so start over */
670 PointerPde
= MiAddressToPde(Va
);
676 MiGetExceptionInfo(IN PEXCEPTION_POINTERS ExceptionInfo
,
677 OUT PBOOLEAN HaveBadAddress
,
678 OUT PULONG_PTR BadAddress
)
680 PEXCEPTION_RECORD ExceptionRecord
;
686 *HaveBadAddress
= FALSE
;
689 // Get the exception record
691 ExceptionRecord
= ExceptionInfo
->ExceptionRecord
;
694 // Look at the exception code
696 if ((ExceptionRecord
->ExceptionCode
== STATUS_ACCESS_VIOLATION
) ||
697 (ExceptionRecord
->ExceptionCode
== STATUS_GUARD_PAGE_VIOLATION
) ||
698 (ExceptionRecord
->ExceptionCode
== STATUS_IN_PAGE_ERROR
))
701 // We can tell the address if we have more than one parameter
703 if (ExceptionRecord
->NumberParameters
> 1)
706 // Return the address
708 *HaveBadAddress
= TRUE
;
709 *BadAddress
= ExceptionRecord
->ExceptionInformation
[1];
714 // Continue executing the next handler
716 return EXCEPTION_EXECUTE_HANDLER
;
721 MiDoMappedCopy(IN PEPROCESS SourceProcess
,
722 IN PVOID SourceAddress
,
723 IN PEPROCESS TargetProcess
,
724 OUT PVOID TargetAddress
,
725 IN SIZE_T BufferSize
,
726 IN KPROCESSOR_MODE PreviousMode
,
727 OUT PSIZE_T ReturnSize
)
729 PFN_NUMBER MdlBuffer
[(sizeof(MDL
) / sizeof(PFN_NUMBER
)) + MI_MAPPED_COPY_PAGES
+ 1];
730 PMDL Mdl
= (PMDL
)MdlBuffer
;
731 SIZE_T TotalSize
, CurrentSize
, RemainingSize
;
732 volatile BOOLEAN FailedInProbe
= FALSE
, FailedInMapping
= FALSE
, FailedInMoving
;
733 volatile BOOLEAN PagesLocked
;
734 PVOID CurrentAddress
= SourceAddress
, CurrentTargetAddress
= TargetAddress
;
735 volatile PVOID MdlAddress
;
737 BOOLEAN HaveBadAddress
;
738 ULONG_PTR BadAddress
;
739 NTSTATUS Status
= STATUS_SUCCESS
;
743 // Calculate the maximum amount of data to move
745 TotalSize
= MI_MAPPED_COPY_PAGES
* PAGE_SIZE
;
746 if (BufferSize
<= TotalSize
) TotalSize
= BufferSize
;
747 CurrentSize
= TotalSize
;
748 RemainingSize
= BufferSize
;
751 // Loop as long as there is still data
753 while (RemainingSize
> 0)
756 // Check if this transfer will finish everything off
758 if (RemainingSize
< CurrentSize
) CurrentSize
= RemainingSize
;
761 // Attach to the source address space
763 KeStackAttachProcess(&SourceProcess
->Pcb
, &ApcState
);
766 // Reset state for this pass
770 FailedInMoving
= FALSE
;
771 ASSERT(FailedInProbe
== FALSE
);
774 // Protect user-mode copy
779 // If this is our first time, probe the buffer
781 if ((CurrentAddress
== SourceAddress
) && (PreviousMode
!= KernelMode
))
784 // Catch a failure here
786 FailedInProbe
= TRUE
;
791 ProbeForRead(SourceAddress
, BufferSize
, sizeof(CHAR
));
796 FailedInProbe
= FALSE
;
800 // Initialize and probe and lock the MDL
802 MmInitializeMdl(Mdl
, CurrentAddress
, CurrentSize
);
803 MmProbeAndLockPages(Mdl
, PreviousMode
, IoReadAccess
);
809 MdlAddress
= MmMapLockedPagesSpecifyCache(Mdl
,
818 // Use our SEH handler to pick this up
820 FailedInMapping
= TRUE
;
821 ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES
);
825 // Now let go of the source and grab to the target process
827 KeUnstackDetachProcess(&ApcState
);
828 KeStackAttachProcess(&TargetProcess
->Pcb
, &ApcState
);
831 // Check if this is our first time through
833 if ((CurrentAddress
== SourceAddress
) && (PreviousMode
!= KernelMode
))
836 // Catch a failure here
838 FailedInProbe
= TRUE
;
843 ProbeForWrite(TargetAddress
, BufferSize
, sizeof(CHAR
));
848 FailedInProbe
= FALSE
;
852 // Now do the actual move
854 FailedInMoving
= TRUE
;
855 RtlCopyMemory(CurrentTargetAddress
, MdlAddress
, CurrentSize
);
857 _SEH2_EXCEPT(MiGetExceptionInfo(_SEH2_GetExceptionInformation(),
862 // Detach from whoever we may be attached to
864 KeUnstackDetachProcess(&ApcState
);
867 // Check if we had mapped the pages
869 if (MdlAddress
) MmUnmapLockedPages(MdlAddress
, Mdl
);
872 // Check if we had locked the pages
874 if (PagesLocked
) MmUnlockPages(Mdl
);
877 // Check if we hit working set quota
879 if (_SEH2_GetExceptionCode() == STATUS_WORKING_SET_QUOTA
)
884 _SEH2_YIELD(return STATUS_WORKING_SET_QUOTA
);
888 // Check if we failed during the probe or mapping
890 if ((FailedInProbe
) || (FailedInMapping
))
895 Status
= _SEH2_GetExceptionCode();
896 _SEH2_YIELD(return Status
);
900 // Otherwise, we failed probably during the move
902 *ReturnSize
= BufferSize
- RemainingSize
;
906 // Check if we know exactly where we stopped copying
911 // Return the exact number of bytes copied
913 *ReturnSize
= BadAddress
- (ULONG_PTR
)SourceAddress
;
918 // Return partial copy
920 Status
= STATUS_PARTIAL_COPY
;
925 // Check for SEH status
927 if (Status
!= STATUS_SUCCESS
) return Status
;
930 // Detach from target
932 KeUnstackDetachProcess(&ApcState
);
937 MmUnmapLockedPages(MdlAddress
, Mdl
);
941 // Update location and size
943 RemainingSize
-= CurrentSize
;
944 CurrentAddress
= (PVOID
)((ULONG_PTR
)CurrentAddress
+ CurrentSize
);
945 CurrentTargetAddress
= (PVOID
)((ULONG_PTR
)CurrentTargetAddress
+ CurrentSize
);
951 *ReturnSize
= BufferSize
;
952 return STATUS_SUCCESS
;
957 MiDoPoolCopy(IN PEPROCESS SourceProcess
,
958 IN PVOID SourceAddress
,
959 IN PEPROCESS TargetProcess
,
960 OUT PVOID TargetAddress
,
961 IN SIZE_T BufferSize
,
962 IN KPROCESSOR_MODE PreviousMode
,
963 OUT PSIZE_T ReturnSize
)
965 UCHAR StackBuffer
[MI_POOL_COPY_BYTES
];
966 SIZE_T TotalSize
, CurrentSize
, RemainingSize
;
967 volatile BOOLEAN FailedInProbe
= FALSE
, FailedInMoving
, HavePoolAddress
= FALSE
;
968 PVOID CurrentAddress
= SourceAddress
, CurrentTargetAddress
= TargetAddress
;
971 BOOLEAN HaveBadAddress
;
972 ULONG_PTR BadAddress
;
973 NTSTATUS Status
= STATUS_SUCCESS
;
977 // Calculate the maximum amount of data to move
979 TotalSize
= MI_MAX_TRANSFER_SIZE
;
980 if (BufferSize
<= MI_MAX_TRANSFER_SIZE
) TotalSize
= BufferSize
;
981 CurrentSize
= TotalSize
;
982 RemainingSize
= BufferSize
;
985 // Check if we can use the stack
987 if (BufferSize
<= MI_POOL_COPY_BYTES
)
992 PoolAddress
= (PVOID
)StackBuffer
;
999 PoolAddress
= ExAllocatePoolWithTag(NonPagedPool
, TotalSize
, 'VmRw');
1000 if (!PoolAddress
) ASSERT(FALSE
);
1001 HavePoolAddress
= TRUE
;
1005 // Loop as long as there is still data
1007 while (RemainingSize
> 0)
1010 // Check if this transfer will finish everything off
1012 if (RemainingSize
< CurrentSize
) CurrentSize
= RemainingSize
;
1015 // Attach to the source address space
1017 KeStackAttachProcess(&SourceProcess
->Pcb
, &ApcState
);
1020 // Reset state for this pass
1022 FailedInMoving
= FALSE
;
1023 ASSERT(FailedInProbe
== FALSE
);
1026 // Protect user-mode copy
1031 // If this is our first time, probe the buffer
1033 if ((CurrentAddress
== SourceAddress
) && (PreviousMode
!= KernelMode
))
1036 // Catch a failure here
1038 FailedInProbe
= TRUE
;
1043 ProbeForRead(SourceAddress
, BufferSize
, sizeof(CHAR
));
1048 FailedInProbe
= FALSE
;
1054 RtlCopyMemory(PoolAddress
, CurrentAddress
, CurrentSize
);
1057 // Now let go of the source and grab to the target process
1059 KeUnstackDetachProcess(&ApcState
);
1060 KeStackAttachProcess(&TargetProcess
->Pcb
, &ApcState
);
1063 // Check if this is our first time through
1065 if ((CurrentAddress
== SourceAddress
) && (PreviousMode
!= KernelMode
))
1068 // Catch a failure here
1070 FailedInProbe
= TRUE
;
1075 ProbeForWrite(TargetAddress
, BufferSize
, sizeof(CHAR
));
1080 FailedInProbe
= FALSE
;
1084 // Now do the actual move
1086 FailedInMoving
= TRUE
;
1087 RtlCopyMemory(CurrentTargetAddress
, PoolAddress
, CurrentSize
);
1089 _SEH2_EXCEPT(MiGetExceptionInfo(_SEH2_GetExceptionInformation(),
1094 // Detach from whoever we may be attached to
1096 KeUnstackDetachProcess(&ApcState
);
1099 // Check if we had allocated pool
1101 if (HavePoolAddress
) ExFreePoolWithTag(PoolAddress
, 'VmRw');
1104 // Check if we failed during the probe
1111 Status
= _SEH2_GetExceptionCode();
1112 _SEH2_YIELD(return Status
);
1116 // Otherwise, we failed, probably during the move
1118 *ReturnSize
= BufferSize
- RemainingSize
;
1122 // Check if we know exactly where we stopped copying
1127 // Return the exact number of bytes copied
1129 *ReturnSize
= BadAddress
- (ULONG_PTR
)SourceAddress
;
1134 // Return partial copy
1136 Status
= STATUS_PARTIAL_COPY
;
1141 // Check for SEH status
1143 if (Status
!= STATUS_SUCCESS
) return Status
;
1146 // Detach from target
1148 KeUnstackDetachProcess(&ApcState
);
1151 // Update location and size
1153 RemainingSize
-= CurrentSize
;
1154 CurrentAddress
= (PVOID
)((ULONG_PTR
)CurrentAddress
+ CurrentSize
);
1155 CurrentTargetAddress
= (PVOID
)((ULONG_PTR
)CurrentTargetAddress
+
1160 // Check if we had allocated pool
1162 if (HavePoolAddress
) ExFreePoolWithTag(PoolAddress
, 'VmRw');
1167 *ReturnSize
= BufferSize
;
1168 return STATUS_SUCCESS
;
1173 MmCopyVirtualMemory(IN PEPROCESS SourceProcess
,
1174 IN PVOID SourceAddress
,
1175 IN PEPROCESS TargetProcess
,
1176 OUT PVOID TargetAddress
,
1177 IN SIZE_T BufferSize
,
1178 IN KPROCESSOR_MODE PreviousMode
,
1179 OUT PSIZE_T ReturnSize
)
1182 PEPROCESS Process
= SourceProcess
;
1185 // Don't accept zero-sized buffers
1187 if (!BufferSize
) return STATUS_SUCCESS
;
1190 // If we are copying from ourselves, lock the target instead
1192 if (SourceProcess
== PsGetCurrentProcess()) Process
= TargetProcess
;
1195 // Acquire rundown protection
1197 if (!ExAcquireRundownProtection(&Process
->RundownProtect
))
1202 return STATUS_PROCESS_IS_TERMINATING
;
1206 // See if we should use the pool copy
1208 if (BufferSize
> MI_POOL_COPY_BYTES
)
1213 Status
= MiDoMappedCopy(SourceProcess
,
1226 Status
= MiDoPoolCopy(SourceProcess
,
1238 ExReleaseRundownProtection(&Process
->RundownProtect
);
1244 MmFlushVirtualMemory(IN PEPROCESS Process
,
1245 IN OUT PVOID
*BaseAddress
,
1246 IN OUT PSIZE_T RegionSize
,
1247 OUT PIO_STATUS_BLOCK IoStatusBlock
)
1255 return STATUS_SUCCESS
;
1260 MiGetPageProtection(IN PMMPTE PointerPte
)
1266 /* Copy this PTE's contents */
1267 TempPte
= *PointerPte
;
1269 /* Assure it's not totally zero */
1270 ASSERT(TempPte
.u
.Long
);
1272 /* Check for a special prototype format */
1273 if (TempPte
.u
.Soft
.Valid
== 0 &&
1274 TempPte
.u
.Soft
.Prototype
== 1)
1276 /* Unsupported now */
1281 /* In the easy case of transition or demand zero PTE just return its protection */
1282 if (!TempPte
.u
.Hard
.Valid
) return MmProtectToValue
[TempPte
.u
.Soft
.Protection
];
1284 /* If we get here, the PTE is valid, so look up the page in PFN database */
1285 Pfn
= MiGetPfnEntry(TempPte
.u
.Hard
.PageFrameNumber
);
1286 if (!Pfn
->u3
.e1
.PrototypePte
)
1288 /* Return protection of the original pte */
1289 ASSERT(Pfn
->u4
.AweAllocation
== 0);
1290 return MmProtectToValue
[Pfn
->OriginalPte
.u
.Soft
.Protection
];
1293 /* This is software PTE */
1294 DPRINT1("Prototype PTE: %lx %p\n", TempPte
.u
.Hard
.PageFrameNumber
, Pfn
);
1295 DPRINT1("VA: %p\n", MiPteToAddress(&TempPte
));
1296 DPRINT1("Mask: %lx\n", TempPte
.u
.Soft
.Protection
);
1297 DPRINT1("Mask2: %lx\n", Pfn
->OriginalPte
.u
.Soft
.Protection
);
1298 return MmProtectToValue
[TempPte
.u
.Soft
.Protection
];
1303 MiQueryAddressState(IN PVOID Va
,
1305 IN PEPROCESS TargetProcess
,
1306 OUT PULONG ReturnedProtect
,
1310 PMMPTE PointerPte
, ProtoPte
;
1312 MMPTE TempPte
, TempProtoPte
;
1313 BOOLEAN DemandZeroPte
= TRUE
, ValidPte
= FALSE
;
1314 ULONG State
= MEM_RESERVE
, Protect
= 0;
1315 ASSERT((Vad
->StartingVpn
<= ((ULONG_PTR
)Va
>> PAGE_SHIFT
)) &&
1316 (Vad
->EndingVpn
>= ((ULONG_PTR
)Va
>> PAGE_SHIFT
)));
1318 /* Only normal VADs supported */
1319 ASSERT(Vad
->u
.VadFlags
.VadType
== VadNone
);
1321 /* Get the PDE and PTE for the address */
1322 PointerPde
= MiAddressToPde(Va
);
1323 PointerPte
= MiAddressToPte(Va
);
1325 /* Return the next range */
1326 *NextVa
= (PVOID
)((ULONG_PTR
)Va
+ PAGE_SIZE
);
1328 /* Is the PDE demand-zero? */
1329 if (PointerPde
->u
.Long
!= 0)
1331 /* It is not. Is it valid? */
1332 if (PointerPde
->u
.Hard
.Valid
== 0)
1334 /* Is isn't, fault it in */
1335 PointerPte
= MiPteToAddress(PointerPde
);
1336 MiMakeSystemAddressValid(PointerPte
, TargetProcess
);
1342 /* It is, skip it and move to the next PDE */
1343 *NextVa
= MiPdeToAddress(PointerPde
+ 1);
1346 /* Is it safe to try reading the PTE? */
1349 /* FIXME: watch out for large pages */
1350 ASSERT(PointerPde
->u
.Hard
.LargePage
== FALSE
);
1352 /* Capture the PTE */
1353 TempPte
= *PointerPte
;
1354 if (TempPte
.u
.Long
!= 0)
1356 /* The PTE is valid, so it's not zeroed out */
1357 DemandZeroPte
= FALSE
;
1359 /* Is it a decommited, invalid, or faulted PTE? */
1360 if ((TempPte
.u
.Soft
.Protection
== MM_DECOMMIT
) &&
1361 (TempPte
.u
.Hard
.Valid
== 0) &&
1362 ((TempPte
.u
.Soft
.Prototype
== 0) ||
1363 (TempPte
.u
.Soft
.PageFileHigh
== MI_PTE_LOOKUP_NEEDED
)))
1365 /* Otherwise our defaults should hold */
1366 ASSERT(Protect
== 0);
1367 ASSERT(State
== MEM_RESERVE
);
1371 /* This means it's committed */
1374 /* We don't support these */
1375 ASSERT(Vad
->u
.VadFlags
.VadType
!= VadDevicePhysicalMemory
);
1376 ASSERT(Vad
->u
.VadFlags
.VadType
!= VadRotatePhysical
);
1377 ASSERT(Vad
->u
.VadFlags
.VadType
!= VadAwe
);
1379 /* Get protection state of this page */
1380 Protect
= MiGetPageProtection(PointerPte
);
1382 /* Check if this is an image-backed VAD */
1383 if ((TempPte
.u
.Soft
.Valid
== 0) &&
1384 (TempPte
.u
.Soft
.Prototype
== 1) &&
1385 (Vad
->u
.VadFlags
.PrivateMemory
== 0) &&
1388 DPRINT1("Not supported\n");
1395 /* Check if this was a demand-zero PTE, since we need to find the state */
1398 /* Not yet handled */
1399 ASSERT(Vad
->u
.VadFlags
.VadType
!= VadDevicePhysicalMemory
);
1400 ASSERT(Vad
->u
.VadFlags
.VadType
!= VadAwe
);
1402 /* Check if this is private commited memory, or an section-backed VAD */
1403 if ((Vad
->u
.VadFlags
.PrivateMemory
== 0) && (Vad
->ControlArea
))
1405 /* Tell caller about the next range */
1406 *NextVa
= (PVOID
)((ULONG_PTR
)Va
+ PAGE_SIZE
);
1408 /* Get the prototype PTE for this VAD */
1409 ProtoPte
= MI_GET_PROTOTYPE_PTE_FOR_VPN(Vad
,
1410 (ULONG_PTR
)Va
>> PAGE_SHIFT
);
1413 /* We should unlock the working set, but it's not being held! */
1415 /* Is the prototype PTE actually valid (committed)? */
1416 TempProtoPte
= *ProtoPte
;
1417 if (TempProtoPte
.u
.Long
)
1419 /* Unless this is a memory-mapped file, handle it like private VAD */
1421 ASSERT(Vad
->u
.VadFlags
.VadType
!= VadImageMap
);
1422 Protect
= MmProtectToValue
[Vad
->u
.VadFlags
.Protection
];
1425 /* We should re-lock the working set */
1428 else if (Vad
->u
.VadFlags
.MemCommit
)
1430 /* This is committed memory */
1433 /* Convert the protection */
1434 Protect
= MmProtectToValue
[Vad
->u
.VadFlags
.Protection
];
1438 /* Return the protection code */
1439 *ReturnedProtect
= Protect
;
1445 MiQueryMemoryBasicInformation(IN HANDLE ProcessHandle
,
1446 IN PVOID BaseAddress
,
1447 OUT PVOID MemoryInformation
,
1448 IN SIZE_T MemoryInformationLength
,
1449 OUT PSIZE_T ReturnLength
)
1451 PEPROCESS TargetProcess
;
1452 NTSTATUS Status
= STATUS_SUCCESS
;
1454 PVOID Address
, NextAddress
;
1455 BOOLEAN Found
= FALSE
;
1456 ULONG NewProtect
, NewState
;
1458 MEMORY_BASIC_INFORMATION MemoryInfo
;
1459 KAPC_STATE ApcState
;
1460 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
1461 PMEMORY_AREA MemoryArea
;
1462 SIZE_T ResultLength
;
1464 /* Check for illegal addresses in user-space, or the shared memory area */
1465 if ((BaseAddress
> MM_HIGHEST_VAD_ADDRESS
) ||
1466 (PAGE_ALIGN(BaseAddress
) == (PVOID
)MM_SHARED_USER_DATA_VA
))
1468 Address
= PAGE_ALIGN(BaseAddress
);
1470 /* Make up an info structure describing this range */
1471 MemoryInfo
.BaseAddress
= Address
;
1472 MemoryInfo
.AllocationProtect
= PAGE_READONLY
;
1473 MemoryInfo
.Type
= MEM_PRIVATE
;
1475 /* Special case for shared data */
1476 if (Address
== (PVOID
)MM_SHARED_USER_DATA_VA
)
1478 MemoryInfo
.AllocationBase
= (PVOID
)MM_SHARED_USER_DATA_VA
;
1479 MemoryInfo
.State
= MEM_COMMIT
;
1480 MemoryInfo
.Protect
= PAGE_READONLY
;
1481 MemoryInfo
.RegionSize
= PAGE_SIZE
;
1485 MemoryInfo
.AllocationBase
= (PCHAR
)MM_HIGHEST_VAD_ADDRESS
+ 1;
1486 MemoryInfo
.State
= MEM_RESERVE
;
1487 MemoryInfo
.Protect
= PAGE_NOACCESS
;
1488 MemoryInfo
.RegionSize
= (ULONG_PTR
)MM_HIGHEST_USER_ADDRESS
+ 1 - (ULONG_PTR
)Address
;
1491 /* Return the data, NtQueryInformation already probed it*/
1492 if (PreviousMode
!= KernelMode
)
1496 *(PMEMORY_BASIC_INFORMATION
)MemoryInformation
= MemoryInfo
;
1497 if (ReturnLength
) *ReturnLength
= sizeof(MEMORY_BASIC_INFORMATION
);
1499 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1501 Status
= _SEH2_GetExceptionCode();
1507 *(PMEMORY_BASIC_INFORMATION
)MemoryInformation
= MemoryInfo
;
1508 if (ReturnLength
) *ReturnLength
= sizeof(MEMORY_BASIC_INFORMATION
);
1514 /* Check if this is for a local or remote process */
1515 if (ProcessHandle
== NtCurrentProcess())
1517 TargetProcess
= PsGetCurrentProcess();
1521 /* Reference the target process */
1522 Status
= ObReferenceObjectByHandle(ProcessHandle
,
1523 PROCESS_QUERY_INFORMATION
,
1525 ExGetPreviousMode(),
1526 (PVOID
*)&TargetProcess
,
1528 if (!NT_SUCCESS(Status
)) return Status
;
1530 /* Attach to it now */
1531 KeStackAttachProcess(&TargetProcess
->Pcb
, &ApcState
);
1534 /* Lock the address space and make sure the process isn't already dead */
1535 MmLockAddressSpace(&TargetProcess
->Vm
);
1536 if (TargetProcess
->VmDeleted
)
1538 /* Unlock the address space of the process */
1539 MmUnlockAddressSpace(&TargetProcess
->Vm
);
1541 /* Check if we were attached */
1542 if (ProcessHandle
!= NtCurrentProcess())
1544 /* Detach and dereference the process */
1545 KeUnstackDetachProcess(&ApcState
);
1546 ObDereferenceObject(TargetProcess
);
1550 DPRINT1("Process is dying\n");
1551 return STATUS_PROCESS_IS_TERMINATING
;
1555 ASSERT(TargetProcess
->VadRoot
.NumberGenericTableElements
);
1556 if (TargetProcess
->VadRoot
.NumberGenericTableElements
)
1558 /* Scan on the right */
1559 Vad
= (PMMVAD
)TargetProcess
->VadRoot
.BalancedRoot
.RightChild
;
1560 BaseVpn
= (ULONG_PTR
)BaseAddress
>> PAGE_SHIFT
;
1563 /* Check if this VAD covers the allocation range */
1564 if ((BaseVpn
>= Vad
->StartingVpn
) &&
1565 (BaseVpn
<= Vad
->EndingVpn
))
1572 /* Check if this VAD is too high */
1573 if (BaseVpn
< Vad
->StartingVpn
)
1575 /* Stop if there is no left child */
1576 if (!Vad
->LeftChild
) break;
1578 /* Search on the left next */
1579 Vad
= Vad
->LeftChild
;
1583 /* Then this VAD is too low, keep searching on the right */
1584 ASSERT(BaseVpn
> Vad
->EndingVpn
);
1586 /* Stop if there is no right child */
1587 if (!Vad
->RightChild
) break;
1589 /* Search on the right next */
1590 Vad
= Vad
->RightChild
;
1595 /* Was a VAD found? */
1598 Address
= PAGE_ALIGN(BaseAddress
);
1600 /* Calculate region size */
1603 if (Vad
->StartingVpn
>= BaseVpn
)
1605 /* Region size is the free space till the start of that VAD */
1606 MemoryInfo
.RegionSize
= (ULONG_PTR
)(Vad
->StartingVpn
<< PAGE_SHIFT
) - (ULONG_PTR
)Address
;
1610 /* Get the next VAD */
1611 Vad
= (PMMVAD
)MiGetNextNode((PMMADDRESS_NODE
)Vad
);
1614 /* Region size is the free space till the start of that VAD */
1615 MemoryInfo
.RegionSize
= (ULONG_PTR
)(Vad
->StartingVpn
<< PAGE_SHIFT
) - (ULONG_PTR
)Address
;
1619 /* Maximum possible region size with that base address */
1620 MemoryInfo
.RegionSize
= (PCHAR
)MM_HIGHEST_VAD_ADDRESS
+ 1 - (PCHAR
)Address
;
1626 /* Maximum possible region size with that base address */
1627 MemoryInfo
.RegionSize
= (PCHAR
)MM_HIGHEST_VAD_ADDRESS
+ 1 - (PCHAR
)Address
;
1630 /* Unlock the address space of the process */
1631 MmUnlockAddressSpace(&TargetProcess
->Vm
);
1633 /* Check if we were attached */
1634 if (ProcessHandle
!= NtCurrentProcess())
1636 /* Detach and derefernece the process */
1637 KeUnstackDetachProcess(&ApcState
);
1638 ObDereferenceObject(TargetProcess
);
1641 /* Build the rest of the initial information block */
1642 MemoryInfo
.BaseAddress
= Address
;
1643 MemoryInfo
.AllocationBase
= NULL
;
1644 MemoryInfo
.AllocationProtect
= 0;
1645 MemoryInfo
.State
= MEM_FREE
;
1646 MemoryInfo
.Protect
= PAGE_NOACCESS
;
1647 MemoryInfo
.Type
= 0;
1649 /* Return the data, NtQueryInformation already probed it*/
1650 if (PreviousMode
!= KernelMode
)
1654 *(PMEMORY_BASIC_INFORMATION
)MemoryInformation
= MemoryInfo
;
1655 if (ReturnLength
) *ReturnLength
= sizeof(MEMORY_BASIC_INFORMATION
);
1657 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1659 Status
= _SEH2_GetExceptionCode();
1665 *(PMEMORY_BASIC_INFORMATION
)MemoryInformation
= MemoryInfo
;
1666 if (ReturnLength
) *ReturnLength
= sizeof(MEMORY_BASIC_INFORMATION
);
1672 /* Set the correct memory type based on what kind of VAD this is */
1673 if ((Vad
->u
.VadFlags
.PrivateMemory
) ||
1674 (Vad
->u
.VadFlags
.VadType
== VadRotatePhysical
))
1676 MemoryInfo
.Type
= MEM_PRIVATE
;
1678 else if (Vad
->u
.VadFlags
.VadType
== VadImageMap
)
1680 MemoryInfo
.Type
= MEM_IMAGE
;
1684 MemoryInfo
.Type
= MEM_MAPPED
;
1687 /* Find the memory area the specified address belongs to */
1688 MemoryArea
= MmLocateMemoryAreaByAddress(&TargetProcess
->Vm
, BaseAddress
);
1689 ASSERT(MemoryArea
!= NULL
);
1691 /* Determine information dependent on the memory area type */
1692 if (MemoryArea
->Type
== MEMORY_AREA_SECTION_VIEW
)
1694 Status
= MmQuerySectionView(MemoryArea
, BaseAddress
, &MemoryInfo
, &ResultLength
);
1695 if (!NT_SUCCESS(Status
))
1697 DPRINT1("MmQuerySectionView failed. MemoryArea=%p (%p-%p), BaseAddress=%p\n",
1698 MemoryArea
, MemoryArea
->StartingAddress
, MemoryArea
->EndingAddress
, BaseAddress
);
1699 NT_ASSERT(NT_SUCCESS(Status
));
1704 /* Build the initial information block */
1705 Address
= PAGE_ALIGN(BaseAddress
);
1706 MemoryInfo
.BaseAddress
= Address
;
1707 MemoryInfo
.AllocationBase
= (PVOID
)(Vad
->StartingVpn
<< PAGE_SHIFT
);
1708 MemoryInfo
.AllocationProtect
= MmProtectToValue
[Vad
->u
.VadFlags
.Protection
];
1709 MemoryInfo
.Type
= MEM_PRIVATE
;
1711 /* Find the largest chunk of memory which has the same state and protection mask */
1712 MemoryInfo
.State
= MiQueryAddressState(Address
,
1715 &MemoryInfo
.Protect
,
1717 Address
= NextAddress
;
1718 while (((ULONG_PTR
)Address
>> PAGE_SHIFT
) <= Vad
->EndingVpn
)
1720 /* Keep going unless the state or protection mask changed */
1721 NewState
= MiQueryAddressState(Address
, Vad
, TargetProcess
, &NewProtect
, &NextAddress
);
1722 if ((NewState
!= MemoryInfo
.State
) || (NewProtect
!= MemoryInfo
.Protect
)) break;
1723 Address
= NextAddress
;
1726 /* Now that we know the last VA address, calculate the region size */
1727 MemoryInfo
.RegionSize
= ((ULONG_PTR
)Address
- (ULONG_PTR
)MemoryInfo
.BaseAddress
);
1730 /* Unlock the address space of the process */
1731 MmUnlockAddressSpace(&TargetProcess
->Vm
);
1733 /* Check if we were attached */
1734 if (ProcessHandle
!= NtCurrentProcess())
1736 /* Detach and derefernece the process */
1737 KeUnstackDetachProcess(&ApcState
);
1738 ObDereferenceObject(TargetProcess
);
1741 /* Return the data, NtQueryInformation already probed it */
1742 if (PreviousMode
!= KernelMode
)
1746 *(PMEMORY_BASIC_INFORMATION
)MemoryInformation
= MemoryInfo
;
1747 if (ReturnLength
) *ReturnLength
= sizeof(MEMORY_BASIC_INFORMATION
);
1749 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1751 Status
= _SEH2_GetExceptionCode();
1757 *(PMEMORY_BASIC_INFORMATION
)MemoryInformation
= MemoryInfo
;
1758 if (ReturnLength
) *ReturnLength
= sizeof(MEMORY_BASIC_INFORMATION
);
1762 DPRINT("Base: %p AllocBase: %p AllocProtect: %lx Protect: %lx "
1763 "State: %lx Type: %lx Size: %lx\n",
1764 MemoryInfo
.BaseAddress
, MemoryInfo
.AllocationBase
,
1765 MemoryInfo
.AllocationProtect
, MemoryInfo
.Protect
,
1766 MemoryInfo
.State
, MemoryInfo
.Type
, MemoryInfo
.RegionSize
);
1773 MiIsEntireRangeCommitted(IN ULONG_PTR StartingAddress
,
1774 IN ULONG_PTR EndingAddress
,
1776 IN PEPROCESS Process
)
1778 PMMPTE PointerPte
, LastPte
, PointerPde
;
1779 BOOLEAN OnBoundary
= TRUE
;
1782 /* Get the PDE and PTE addresses */
1783 PointerPde
= MiAddressToPde(StartingAddress
);
1784 PointerPte
= MiAddressToPte(StartingAddress
);
1785 LastPte
= MiAddressToPte(EndingAddress
);
1787 /* Loop all the PTEs */
1788 while (PointerPte
<= LastPte
)
1790 /* Check if we've hit an new PDE boundary */
1793 /* Is this PDE demand zero? */
1794 PointerPde
= MiAddressToPte(PointerPte
);
1795 if (PointerPde
->u
.Long
!= 0)
1797 /* It isn't -- is it valid? */
1798 if (PointerPde
->u
.Hard
.Valid
== 0)
1800 /* Nope, fault it in */
1801 PointerPte
= MiPteToAddress(PointerPde
);
1802 MiMakeSystemAddressValid(PointerPte
, Process
);
1807 /* The PTE was already valid, so move to the next one */
1809 PointerPte
= MiPteToAddress(PointerPde
);
1811 /* Is the entire VAD committed? If not, fail */
1812 if (!Vad
->u
.VadFlags
.MemCommit
) return FALSE
;
1814 /* Everything is committed so far past the range, return true */
1815 if (PointerPte
> LastPte
) return TRUE
;
1819 /* Is the PTE demand zero? */
1820 if (PointerPte
->u
.Long
== 0)
1822 /* Is the entire VAD committed? If not, fail */
1823 if (!Vad
->u
.VadFlags
.MemCommit
) return FALSE
;
1827 /* It isn't -- is it a decommited, invalid, or faulted PTE? */
1828 if ((PointerPte
->u
.Soft
.Protection
== MM_DECOMMIT
) &&
1829 (PointerPte
->u
.Hard
.Valid
== 0) &&
1830 ((PointerPte
->u
.Soft
.Prototype
== 0) ||
1831 (PointerPte
->u
.Soft
.PageFileHigh
== MI_PTE_LOOKUP_NEEDED
)))
1833 /* Then part of the range is decommitted, so fail */
1838 /* Move to the next PTE */
1840 OnBoundary
= MiIsPteOnPdeBoundary(PointerPte
);
1843 /* All PTEs seem valid, and no VAD checks failed, the range is okay */
1849 MiRosProtectVirtualMemory(IN PEPROCESS Process
,
1850 IN OUT PVOID
*BaseAddress
,
1851 IN OUT PSIZE_T NumberOfBytesToProtect
,
1852 IN ULONG NewAccessProtection
,
1853 OUT PULONG OldAccessProtection OPTIONAL
)
1855 PMEMORY_AREA MemoryArea
;
1856 PMMSUPPORT AddressSpace
;
1857 ULONG OldAccessProtection_
;
1860 *NumberOfBytesToProtect
= PAGE_ROUND_UP((ULONG_PTR
)(*BaseAddress
) + (*NumberOfBytesToProtect
)) - PAGE_ROUND_DOWN(*BaseAddress
);
1861 *BaseAddress
= (PVOID
)PAGE_ROUND_DOWN(*BaseAddress
);
1863 AddressSpace
= &Process
->Vm
;
1864 MmLockAddressSpace(AddressSpace
);
1865 MemoryArea
= MmLocateMemoryAreaByAddress(AddressSpace
, *BaseAddress
);
1866 if (MemoryArea
== NULL
|| MemoryArea
->DeleteInProgress
)
1868 MmUnlockAddressSpace(AddressSpace
);
1869 return STATUS_UNSUCCESSFUL
;
1872 if (OldAccessProtection
== NULL
) OldAccessProtection
= &OldAccessProtection_
;
1874 ASSERT(MemoryArea
->Type
== MEMORY_AREA_SECTION_VIEW
);
1875 Status
= MmProtectSectionView(AddressSpace
,
1878 *NumberOfBytesToProtect
,
1879 NewAccessProtection
,
1880 OldAccessProtection
);
1882 MmUnlockAddressSpace(AddressSpace
);
1889 MiProtectVirtualMemory(IN PEPROCESS Process
,
1890 IN OUT PVOID
*BaseAddress
,
1891 IN OUT PSIZE_T NumberOfBytesToProtect
,
1892 IN ULONG NewAccessProtection
,
1893 OUT PULONG OldAccessProtection OPTIONAL
)
1895 PMEMORY_AREA MemoryArea
;
1897 PMMSUPPORT AddressSpace
;
1898 ULONG_PTR StartingAddress
, EndingAddress
;
1899 PMMPTE PointerPde
, PointerPte
, LastPte
;
1902 ULONG ProtectionMask
, OldProtect
;
1904 NTSTATUS Status
= STATUS_SUCCESS
;
1905 PETHREAD Thread
= PsGetCurrentThread();
1906 TABLE_SEARCH_RESULT Result
;
1908 /* Calculate base address for the VAD */
1909 StartingAddress
= (ULONG_PTR
)PAGE_ALIGN((*BaseAddress
));
1910 EndingAddress
= (((ULONG_PTR
)*BaseAddress
+ *NumberOfBytesToProtect
- 1) | (PAGE_SIZE
- 1));
1912 /* Calculate the protection mask and make sure it's valid */
1913 ProtectionMask
= MiMakeProtectionMask(NewAccessProtection
);
1914 if (ProtectionMask
== MM_INVALID_PROTECTION
)
1916 DPRINT1("Invalid protection mask\n");
1917 return STATUS_INVALID_PAGE_PROTECTION
;
1920 /* Check for ROS specific memory area */
1921 MemoryArea
= MmLocateMemoryAreaByAddress(&Process
->Vm
, *BaseAddress
);
1922 if ((MemoryArea
) && (MemoryArea
->Type
== MEMORY_AREA_SECTION_VIEW
))
1925 return MiRosProtectVirtualMemory(Process
,
1927 NumberOfBytesToProtect
,
1928 NewAccessProtection
,
1929 OldAccessProtection
);
1932 /* Lock the address space and make sure the process isn't already dead */
1933 AddressSpace
= MmGetCurrentAddressSpace();
1934 MmLockAddressSpace(AddressSpace
);
1935 if (Process
->VmDeleted
)
1937 DPRINT1("Process is dying\n");
1938 Status
= STATUS_PROCESS_IS_TERMINATING
;
1942 /* Get the VAD for this address range, and make sure it exists */
1943 Result
= MiCheckForConflictingNode(StartingAddress
>> PAGE_SHIFT
,
1944 EndingAddress
>> PAGE_SHIFT
,
1946 (PMMADDRESS_NODE
*)&Vad
);
1947 if (Result
!= TableFoundNode
)
1949 DPRINT("Could not find a VAD for this allocation\n");
1950 Status
= STATUS_CONFLICTING_ADDRESSES
;
1954 /* Make sure the address is within this VAD's boundaries */
1955 if ((((ULONG_PTR
)StartingAddress
>> PAGE_SHIFT
) < Vad
->StartingVpn
) ||
1956 (((ULONG_PTR
)EndingAddress
>> PAGE_SHIFT
) > Vad
->EndingVpn
))
1958 Status
= STATUS_CONFLICTING_ADDRESSES
;
1962 /* These kinds of VADs are not supported atm */
1963 if ((Vad
->u
.VadFlags
.VadType
== VadAwe
) ||
1964 (Vad
->u
.VadFlags
.VadType
== VadDevicePhysicalMemory
) ||
1965 (Vad
->u
.VadFlags
.VadType
== VadLargePages
))
1967 DPRINT1("Illegal VAD for attempting to set protection\n");
1968 Status
= STATUS_CONFLICTING_ADDRESSES
;
1972 /* Check for a VAD whose protection can't be changed */
1973 if (Vad
->u
.VadFlags
.NoChange
== 1)
1975 DPRINT1("Trying to change protection of a NoChange VAD\n");
1976 Status
= STATUS_INVALID_PAGE_PROTECTION
;
1980 /* Is this section, or private memory? */
1981 if (Vad
->u
.VadFlags
.PrivateMemory
== 0)
1983 /* Not yet supported */
1984 if (Vad
->u
.VadFlags
.VadType
== VadLargePageSection
)
1986 DPRINT1("Illegal VAD for attempting to set protection\n");
1987 Status
= STATUS_CONFLICTING_ADDRESSES
;
1991 /* Rotate VADs are not yet supported */
1992 if (Vad
->u
.VadFlags
.VadType
== VadRotatePhysical
)
1994 DPRINT1("Illegal VAD for attempting to set protection\n");
1995 Status
= STATUS_CONFLICTING_ADDRESSES
;
1999 /* Not valid on section files */
2000 if (NewAccessProtection
& (PAGE_NOCACHE
| PAGE_WRITECOMBINE
))
2003 DPRINT1("Invalid protection flags for section\n");
2004 Status
= STATUS_INVALID_PARAMETER_4
;
2008 /* Check if data or page file mapping protection PTE is compatible */
2009 if (!Vad
->ControlArea
->u
.Flags
.Image
)
2012 DPRINT1("Fixme: Not checking for valid protection\n");
2015 /* This is a section, and this is not yet supported */
2016 DPRINT1("Section protection not yet supported\n");
2021 /* Private memory, check protection flags */
2022 if ((NewAccessProtection
& PAGE_WRITECOPY
) ||
2023 (NewAccessProtection
& PAGE_EXECUTE_WRITECOPY
))
2025 DPRINT1("Invalid protection flags for private memory\n");
2026 Status
= STATUS_INVALID_PARAMETER_4
;
2030 /* Lock the working set */
2031 MiLockProcessWorkingSetUnsafe(Process
, Thread
);
2033 /* Check if all pages in this range are committed */
2034 Committed
= MiIsEntireRangeCommitted(StartingAddress
,
2041 DPRINT1("The entire range is not committed\n");
2042 Status
= STATUS_NOT_COMMITTED
;
2043 MiUnlockProcessWorkingSetUnsafe(Process
, Thread
);
2047 /* Compute starting and ending PTE and PDE addresses */
2048 PointerPde
= MiAddressToPde(StartingAddress
);
2049 PointerPte
= MiAddressToPte(StartingAddress
);
2050 LastPte
= MiAddressToPte(EndingAddress
);
2052 /* Make this PDE valid */
2053 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
2055 /* Save protection of the first page */
2056 if (PointerPte
->u
.Long
!= 0)
2058 /* Capture the page protection and make the PDE valid */
2059 OldProtect
= MiGetPageProtection(PointerPte
);
2060 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
2064 /* Grab the old protection from the VAD itself */
2065 OldProtect
= MmProtectToValue
[Vad
->u
.VadFlags
.Protection
];
2068 /* Loop all the PTEs now */
2069 while (PointerPte
<= LastPte
)
2071 /* Check if we've crossed a PDE boundary and make the new PDE valid too */
2072 if (MiIsPteOnPdeBoundary(PointerPte
))
2074 PointerPde
= MiAddressToPte(PointerPte
);
2075 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
2078 /* Capture the PTE and check if it was empty */
2079 PteContents
= *PointerPte
;
2080 if (PteContents
.u
.Long
== 0)
2082 /* This used to be a zero PTE and it no longer is, so we must add a
2083 reference to the pagetable. */
2084 MiIncrementPageTableReferences(MiPteToAddress(PointerPte
));
2087 /* Check what kind of PTE we are dealing with */
2088 if (PteContents
.u
.Hard
.Valid
== 1)
2090 /* Get the PFN entry */
2091 Pfn1
= MiGetPfnEntry(PFN_FROM_PTE(&PteContents
));
2093 /* We don't support this yet */
2094 ASSERT(Pfn1
->u3
.e1
.PrototypePte
== 0);
2096 /* Check if the page should not be accessible at all */
2097 if ((NewAccessProtection
& PAGE_NOACCESS
) ||
2098 (NewAccessProtection
& PAGE_GUARD
))
2100 /* The page should be in the WS and we should make it transition now */
2101 DPRINT1("Making valid page invalid is not yet supported!\n");
2102 Status
= STATUS_NOT_IMPLEMENTED
;
2103 /* Unlock the working set */
2104 MiUnlockProcessWorkingSetUnsafe(Process
, Thread
);
2108 /* Write the protection mask and write it with a TLB flush */
2109 Pfn1
->OriginalPte
.u
.Soft
.Protection
= ProtectionMask
;
2110 MiFlushTbAndCapture(Vad
,
2118 /* We don't support these cases yet */
2119 ASSERT(PteContents
.u
.Soft
.Prototype
== 0);
2120 ASSERT(PteContents
.u
.Soft
.Transition
== 0);
2122 /* The PTE is already demand-zero, just update the protection mask */
2123 PteContents
.u
.Soft
.Protection
= ProtectionMask
;
2124 MI_WRITE_INVALID_PTE(PointerPte
, PteContents
);
2125 ASSERT(PointerPte
->u
.Long
!= 0);
2128 /* Move to the next PTE */
2132 /* Unlock the working set */
2133 MiUnlockProcessWorkingSetUnsafe(Process
, Thread
);
2136 /* Unlock the address space */
2137 MmUnlockAddressSpace(AddressSpace
);
2139 /* Return parameters and success */
2140 *NumberOfBytesToProtect
= EndingAddress
- StartingAddress
+ 1;
2141 *BaseAddress
= (PVOID
)StartingAddress
;
2142 *OldAccessProtection
= OldProtect
;
2143 return STATUS_SUCCESS
;
2146 /* Unlock the address space and return the failure code */
2147 MmUnlockAddressSpace(AddressSpace
);
2153 MiMakePdeExistAndMakeValid(IN PMMPTE PointerPde
,
2154 IN PEPROCESS TargetProcess
,
2157 PMMPTE PointerPte
, PointerPpe
, PointerPxe
;
2160 // Sanity checks. The latter is because we only use this function with the
2161 // PFN lock not held, so it may go away in the future.
2163 ASSERT(KeAreAllApcsDisabled() == TRUE
);
2164 ASSERT(OldIrql
== MM_NOIRQL
);
2167 // Also get the PPE and PXE. This is okay not to #ifdef because they will
2168 // return the same address as the PDE on 2-level page table systems.
2170 // If everything is already valid, there is nothing to do.
2172 PointerPpe
= MiAddressToPte(PointerPde
);
2173 PointerPxe
= MiAddressToPde(PointerPde
);
2174 if ((PointerPxe
->u
.Hard
.Valid
) &&
2175 (PointerPpe
->u
.Hard
.Valid
) &&
2176 (PointerPde
->u
.Hard
.Valid
))
2182 // At least something is invalid, so begin by getting the PTE for the PDE itself
2183 // and then lookup each additional level. We must do it in this precise order
2184 // because the pagfault.c code (as well as in Windows) depends that the next
2185 // level up (higher) must be valid when faulting a lower level
2187 PointerPte
= MiPteToAddress(PointerPde
);
2191 // Make sure APCs continued to be disabled
2193 ASSERT(KeAreAllApcsDisabled() == TRUE
);
2196 // First, make the PXE valid if needed
2198 if (!PointerPxe
->u
.Hard
.Valid
)
2200 MiMakeSystemAddressValid(PointerPpe
, TargetProcess
);
2201 ASSERT(PointerPxe
->u
.Hard
.Valid
== 1);
2207 if (!PointerPpe
->u
.Hard
.Valid
)
2209 MiMakeSystemAddressValid(PointerPde
, TargetProcess
);
2210 ASSERT(PointerPpe
->u
.Hard
.Valid
== 1);
2214 // And finally, make the PDE itself valid.
2216 MiMakeSystemAddressValid(PointerPte
, TargetProcess
);
2219 // This should've worked the first time so the loop is really just for
2220 // show -- ASSERT that we're actually NOT going to be looping.
2222 ASSERT(PointerPxe
->u
.Hard
.Valid
== 1);
2223 ASSERT(PointerPpe
->u
.Hard
.Valid
== 1);
2224 ASSERT(PointerPde
->u
.Hard
.Valid
== 1);
2225 } while (!(PointerPxe
->u
.Hard
.Valid
) ||
2226 !(PointerPpe
->u
.Hard
.Valid
) ||
2227 !(PointerPde
->u
.Hard
.Valid
));
2232 MiProcessValidPteList(IN PMMPTE
*ValidPteList
,
2238 PFN_NUMBER PageFrameIndex
;
2242 // Acquire the PFN lock and loop all the PTEs in the list
2244 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
2245 for (i
= 0; i
!= Count
; i
++)
2248 // The PTE must currently be valid
2250 TempPte
= *ValidPteList
[i
];
2251 ASSERT(TempPte
.u
.Hard
.Valid
== 1);
2254 // Get the PFN entry for the page itself, and then for its page table
2256 PageFrameIndex
= PFN_FROM_PTE(&TempPte
);
2257 Pfn1
= MiGetPfnEntry(PageFrameIndex
);
2258 Pfn2
= MiGetPfnEntry(Pfn1
->u4
.PteFrame
);
2261 // Decrement the share count on the page table, and then on the page
2264 MiDecrementShareCount(Pfn2
, Pfn1
->u4
.PteFrame
);
2265 MI_SET_PFN_DELETED(Pfn1
);
2266 MiDecrementShareCount(Pfn1
, PageFrameIndex
);
2269 // Make the page decommitted
2271 MI_WRITE_INVALID_PTE(ValidPteList
[i
], MmDecommittedPte
);
2275 // All the PTEs have been dereferenced and made invalid, flush the TLB now
2276 // and then release the PFN lock
2279 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
2284 MiDecommitPages(IN PVOID StartingAddress
,
2285 IN PMMPTE EndingPte
,
2286 IN PEPROCESS Process
,
2289 PMMPTE PointerPde
, PointerPte
, CommitPte
= NULL
;
2290 ULONG CommitReduction
= 0;
2291 PMMPTE ValidPteList
[256];
2295 PETHREAD CurrentThread
= PsGetCurrentThread();
2298 // Get the PTE and PTE for the address, and lock the working set
2299 // If this was a VAD for a MEM_COMMIT allocation, also figure out where the
2300 // commited range ends so that we can do the right accounting.
2302 PointerPde
= MiAddressToPde(StartingAddress
);
2303 PointerPte
= MiAddressToPte(StartingAddress
);
2304 if (Vad
->u
.VadFlags
.MemCommit
) CommitPte
= MiAddressToPte(Vad
->EndingVpn
<< PAGE_SHIFT
);
2305 MiLockProcessWorkingSetUnsafe(Process
, CurrentThread
);
2308 // Make the PDE valid, and now loop through each page's worth of data
2310 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
2311 while (PointerPte
<= EndingPte
)
2314 // Check if we've crossed a PDE boundary
2316 if (MiIsPteOnPdeBoundary(PointerPte
))
2319 // Get the new PDE and flush the valid PTEs we had built up until
2320 // now. This helps reduce the amount of TLB flushing we have to do.
2321 // Note that Windows does a much better job using timestamps and
2322 // such, and does not flush the entire TLB all the time, but right
2323 // now we have bigger problems to worry about than TLB flushing.
2325 PointerPde
= MiAddressToPde(StartingAddress
);
2328 MiProcessValidPteList(ValidPteList
, PteCount
);
2333 // Make this PDE valid
2335 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
2339 // Read this PTE. It might be active or still demand-zero.
2341 PteContents
= *PointerPte
;
2342 if (PteContents
.u
.Long
)
2345 // The PTE is active. It might be valid and in a working set, or
2346 // it might be a prototype PTE or paged out or even in transition.
2348 if (PointerPte
->u
.Long
== MmDecommittedPte
.u
.Long
)
2351 // It's already decommited, so there's nothing for us to do here
2358 // Remove it from the counters, and check if it was valid or not
2360 //Process->NumberOfPrivatePages--;
2361 if (PteContents
.u
.Hard
.Valid
)
2364 // It's valid. At this point make sure that it is not a ROS
2365 // PFN. Also, we don't support ProtoPTEs in this code path.
2367 Pfn1
= MiGetPfnEntry(PteContents
.u
.Hard
.PageFrameNumber
);
2368 ASSERT(MI_IS_ROS_PFN(Pfn1
) == FALSE
);
2369 ASSERT(Pfn1
->u3
.e1
.PrototypePte
== FALSE
);
2372 // Flush any pending PTEs that we had not yet flushed, if our
2373 // list has gotten too big, then add this PTE to the flush list.
2375 if (PteCount
== 256)
2377 MiProcessValidPteList(ValidPteList
, PteCount
);
2380 ValidPteList
[PteCount
++] = PointerPte
;
2385 // We do not support any of these other scenarios at the moment
2387 ASSERT(PteContents
.u
.Soft
.Prototype
== 0);
2388 ASSERT(PteContents
.u
.Soft
.Transition
== 0);
2389 ASSERT(PteContents
.u
.Soft
.PageFileHigh
== 0);
2392 // So the only other possibility is that it is still a demand
2393 // zero PTE, in which case we undo the accounting we did
2394 // earlier and simply make the page decommitted.
2396 //Process->NumberOfPrivatePages++;
2397 MI_WRITE_INVALID_PTE(PointerPte
, MmDecommittedPte
);
2404 // This used to be a zero PTE and it no longer is, so we must add a
2405 // reference to the pagetable.
2407 MiIncrementPageTableReferences(StartingAddress
);
2410 // Next, we account for decommitted PTEs and make the PTE as such
2412 if (PointerPte
> CommitPte
) CommitReduction
++;
2413 MI_WRITE_INVALID_PTE(PointerPte
, MmDecommittedPte
);
2417 // Move to the next PTE and the next address
2420 StartingAddress
= (PVOID
)((ULONG_PTR
)StartingAddress
+ PAGE_SIZE
);
2424 // Flush any dangling PTEs from the loop in the last page table, and then
2425 // release the working set and return the commit reduction accounting.
2427 if (PteCount
) MiProcessValidPteList(ValidPteList
, PteCount
);
2428 MiUnlockProcessWorkingSetUnsafe(Process
, CurrentThread
);
2429 return CommitReduction
;
2432 /* PUBLIC FUNCTIONS ***********************************************************/
2439 MmGetVirtualForPhysical(IN PHYSICAL_ADDRESS PhysicalAddress
)
2450 MmSecureVirtualMemory(IN PVOID Address
,
2454 static BOOLEAN Warn
; if (!Warn
++) UNIMPLEMENTED
;
2463 MmUnsecureVirtualMemory(IN PVOID SecureMem
)
2465 static BOOLEAN Warn
; if (!Warn
++) UNIMPLEMENTED
;
2468 /* SYSTEM CALLS ***************************************************************/
2472 NtReadVirtualMemory(IN HANDLE ProcessHandle
,
2473 IN PVOID BaseAddress
,
2475 IN SIZE_T NumberOfBytesToRead
,
2476 OUT PSIZE_T NumberOfBytesRead OPTIONAL
)
2478 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
2480 NTSTATUS Status
= STATUS_SUCCESS
;
2481 SIZE_T BytesRead
= 0;
2485 // Check if we came from user mode
2487 if (PreviousMode
!= KernelMode
)
2490 // Validate the read addresses
2492 if ((((ULONG_PTR
)BaseAddress
+ NumberOfBytesToRead
) < (ULONG_PTR
)BaseAddress
) ||
2493 (((ULONG_PTR
)Buffer
+ NumberOfBytesToRead
) < (ULONG_PTR
)Buffer
) ||
2494 (((ULONG_PTR
)BaseAddress
+ NumberOfBytesToRead
) > MmUserProbeAddress
) ||
2495 (((ULONG_PTR
)Buffer
+ NumberOfBytesToRead
) > MmUserProbeAddress
))
2498 // Don't allow to write into kernel space
2500 return STATUS_ACCESS_VIOLATION
;
2504 // Enter SEH for probe
2509 // Probe the output value
2511 if (NumberOfBytesRead
) ProbeForWriteSize_t(NumberOfBytesRead
);
2513 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2516 // Get exception code
2518 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2524 // Don't do zero-byte transfers
2526 if (NumberOfBytesToRead
)
2529 // Reference the process
2531 Status
= ObReferenceObjectByHandle(ProcessHandle
,
2537 if (NT_SUCCESS(Status
))
2542 Status
= MmCopyVirtualMemory(Process
,
2544 PsGetCurrentProcess(),
2546 NumberOfBytesToRead
,
2551 // Dereference the process
2553 ObDereferenceObject(Process
);
2558 // Check if the caller sent this parameter
2560 if (NumberOfBytesRead
)
2563 // Enter SEH to guard write
2568 // Return the number of bytes read
2570 *NumberOfBytesRead
= BytesRead
;
2572 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2586 NtWriteVirtualMemory(IN HANDLE ProcessHandle
,
2587 IN PVOID BaseAddress
,
2589 IN SIZE_T NumberOfBytesToWrite
,
2590 OUT PSIZE_T NumberOfBytesWritten OPTIONAL
)
2592 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
2594 NTSTATUS Status
= STATUS_SUCCESS
;
2595 SIZE_T BytesWritten
= 0;
2599 // Check if we came from user mode
2601 if (PreviousMode
!= KernelMode
)
2604 // Validate the read addresses
2606 if ((((ULONG_PTR
)BaseAddress
+ NumberOfBytesToWrite
) < (ULONG_PTR
)BaseAddress
) ||
2607 (((ULONG_PTR
)Buffer
+ NumberOfBytesToWrite
) < (ULONG_PTR
)Buffer
) ||
2608 (((ULONG_PTR
)BaseAddress
+ NumberOfBytesToWrite
) > MmUserProbeAddress
) ||
2609 (((ULONG_PTR
)Buffer
+ NumberOfBytesToWrite
) > MmUserProbeAddress
))
2612 // Don't allow to write into kernel space
2614 return STATUS_ACCESS_VIOLATION
;
2618 // Enter SEH for probe
2623 // Probe the output value
2625 if (NumberOfBytesWritten
) ProbeForWriteSize_t(NumberOfBytesWritten
);
2627 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2630 // Get exception code
2632 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2638 // Don't do zero-byte transfers
2640 if (NumberOfBytesToWrite
)
2643 // Reference the process
2645 Status
= ObReferenceObjectByHandle(ProcessHandle
,
2651 if (NT_SUCCESS(Status
))
2656 Status
= MmCopyVirtualMemory(PsGetCurrentProcess(),
2660 NumberOfBytesToWrite
,
2665 // Dereference the process
2667 ObDereferenceObject(Process
);
2672 // Check if the caller sent this parameter
2674 if (NumberOfBytesWritten
)
2677 // Enter SEH to guard write
2682 // Return the number of bytes written
2684 *NumberOfBytesWritten
= BytesWritten
;
2686 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2700 NtProtectVirtualMemory(IN HANDLE ProcessHandle
,
2701 IN OUT PVOID
*UnsafeBaseAddress
,
2702 IN OUT SIZE_T
*UnsafeNumberOfBytesToProtect
,
2703 IN ULONG NewAccessProtection
,
2704 OUT PULONG UnsafeOldAccessProtection
)
2707 ULONG OldAccessProtection
;
2709 PEPROCESS CurrentProcess
= PsGetCurrentProcess();
2710 PVOID BaseAddress
= NULL
;
2711 SIZE_T NumberOfBytesToProtect
= 0;
2712 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
2714 BOOLEAN Attached
= FALSE
;
2715 KAPC_STATE ApcState
;
2719 // Check for valid protection flags
2721 Protection
= NewAccessProtection
& ~(PAGE_GUARD
|PAGE_NOCACHE
);
2722 if (Protection
!= PAGE_NOACCESS
&&
2723 Protection
!= PAGE_READONLY
&&
2724 Protection
!= PAGE_READWRITE
&&
2725 Protection
!= PAGE_WRITECOPY
&&
2726 Protection
!= PAGE_EXECUTE
&&
2727 Protection
!= PAGE_EXECUTE_READ
&&
2728 Protection
!= PAGE_EXECUTE_READWRITE
&&
2729 Protection
!= PAGE_EXECUTE_WRITECOPY
)
2734 return STATUS_INVALID_PAGE_PROTECTION
;
2738 // Check if we came from user mode
2740 if (PreviousMode
!= KernelMode
)
2743 // Enter SEH for probing
2748 // Validate all outputs
2750 ProbeForWritePointer(UnsafeBaseAddress
);
2751 ProbeForWriteSize_t(UnsafeNumberOfBytesToProtect
);
2752 ProbeForWriteUlong(UnsafeOldAccessProtection
);
2757 BaseAddress
= *UnsafeBaseAddress
;
2758 NumberOfBytesToProtect
= *UnsafeNumberOfBytesToProtect
;
2760 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2763 // Get exception code
2765 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2774 BaseAddress
= *UnsafeBaseAddress
;
2775 NumberOfBytesToProtect
= *UnsafeNumberOfBytesToProtect
;
2779 // Catch illegal base address
2781 if (BaseAddress
> MM_HIGHEST_USER_ADDRESS
) return STATUS_INVALID_PARAMETER_2
;
2784 // Catch illegal region size
2786 if ((MmUserProbeAddress
- (ULONG_PTR
)BaseAddress
) < NumberOfBytesToProtect
)
2791 return STATUS_INVALID_PARAMETER_3
;
2795 // 0 is also illegal
2797 if (!NumberOfBytesToProtect
) return STATUS_INVALID_PARAMETER_3
;
2800 // Get a reference to the process
2802 Status
= ObReferenceObjectByHandle(ProcessHandle
,
2803 PROCESS_VM_OPERATION
,
2808 if (!NT_SUCCESS(Status
)) return Status
;
2811 // Check if we should attach
2813 if (CurrentProcess
!= Process
)
2818 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
2823 // Do the actual work
2825 Status
= MiProtectVirtualMemory(Process
,
2827 &NumberOfBytesToProtect
,
2828 NewAccessProtection
,
2829 &OldAccessProtection
);
2834 if (Attached
) KeUnstackDetachProcess(&ApcState
);
2837 // Release reference
2839 ObDereferenceObject(Process
);
2842 // Enter SEH to return data
2847 // Return data to user
2849 *UnsafeOldAccessProtection
= OldAccessProtection
;
2850 *UnsafeBaseAddress
= BaseAddress
;
2851 *UnsafeNumberOfBytesToProtect
= NumberOfBytesToProtect
;
2853 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2870 // HACK until we have proper WSLIST support
2871 PMMWSLE Wsle
= &Pfn1
->Wsle
;
2873 if ((LockType
& MAP_PROCESS
) && (Wsle
->u1
.e1
.LockedInWs
))
2875 if ((LockType
& MAP_SYSTEM
) && (Wsle
->u1
.e1
.LockedInMemory
))
2887 // HACK until we have proper WSLIST support
2888 PMMWSLE Wsle
= &Pfn1
->Wsle
;
2890 if (!Wsle
->u1
.e1
.LockedInWs
&&
2891 !Wsle
->u1
.e1
.LockedInMemory
)
2893 MiReferenceProbedPageAndBumpLockCount(Pfn1
);
2896 if (LockType
& MAP_PROCESS
)
2897 Wsle
->u1
.e1
.LockedInWs
= 1;
2898 if (LockType
& MAP_SYSTEM
)
2899 Wsle
->u1
.e1
.LockedInMemory
= 1;
2908 // HACK until we have proper WSLIST support
2909 PMMWSLE Wsle
= &Pfn1
->Wsle
;
2911 if (LockType
& MAP_PROCESS
)
2912 Wsle
->u1
.e1
.LockedInWs
= 0;
2913 if (LockType
& MAP_SYSTEM
)
2914 Wsle
->u1
.e1
.LockedInMemory
= 0;
2916 if (!Wsle
->u1
.e1
.LockedInWs
&&
2917 !Wsle
->u1
.e1
.LockedInMemory
)
2919 MiDereferencePfnAndDropLockCount(Pfn1
);
2925 MiCheckVadsForLockOperation(
2926 _Inout_ PVOID
*BaseAddress
,
2927 _Inout_ PSIZE_T RegionSize
,
2928 _Inout_ PVOID
*EndAddress
)
2934 /* Get the base address and align the start address */
2935 *EndAddress
= (PUCHAR
)*BaseAddress
+ *RegionSize
;
2936 *EndAddress
= ALIGN_UP_POINTER_BY(*EndAddress
, PAGE_SIZE
);
2937 *BaseAddress
= ALIGN_DOWN_POINTER_BY(*BaseAddress
, PAGE_SIZE
);
2939 /* First loop and check all VADs */
2940 CurrentVa
= *BaseAddress
;
2941 while (CurrentVa
< *EndAddress
)
2944 Vad
= MiLocateAddress(CurrentVa
);
2947 /// FIXME: this might be a memory area for a section view...
2948 return STATUS_ACCESS_VIOLATION
;
2951 /* Check VAD type */
2952 if ((Vad
->u
.VadFlags
.VadType
!= VadNone
) &&
2953 (Vad
->u
.VadFlags
.VadType
!= VadImageMap
) &&
2954 (Vad
->u
.VadFlags
.VadType
!= VadWriteWatch
))
2956 *EndAddress
= CurrentVa
;
2957 *RegionSize
= (PUCHAR
)*EndAddress
- (PUCHAR
)*BaseAddress
;
2958 return STATUS_INCOMPATIBLE_FILE_MAP
;
2961 CurrentVa
= (PVOID
)((Vad
->EndingVpn
+ 1) << PAGE_SHIFT
);
2964 *RegionSize
= (PUCHAR
)*EndAddress
- (PUCHAR
)*BaseAddress
;
2965 return STATUS_SUCCESS
;
2970 MiLockVirtualMemory(
2971 IN OUT PVOID
*BaseAddress
,
2972 IN OUT PSIZE_T RegionSize
,
2975 PEPROCESS CurrentProcess
;
2976 PMMSUPPORT AddressSpace
;
2977 PVOID CurrentVa
, EndAddress
;
2978 PMMPTE PointerPte
, LastPte
;
2980 #if (_MI_PAGING_LEVELS >= 3)
2983 #if (_MI_PAGING_LEVELS == 4)
2987 NTSTATUS Status
, TempStatus
;
2989 /* Lock the address space */
2990 AddressSpace
= MmGetCurrentAddressSpace();
2991 MmLockAddressSpace(AddressSpace
);
2993 /* Make sure we still have an address space */
2994 CurrentProcess
= PsGetCurrentProcess();
2995 if (CurrentProcess
->VmDeleted
)
2997 Status
= STATUS_PROCESS_IS_TERMINATING
;
3001 /* Check the VADs in the requested range */
3002 Status
= MiCheckVadsForLockOperation(BaseAddress
, RegionSize
, &EndAddress
);
3003 if (!NT_SUCCESS(Status
))
3008 /* Enter SEH for probing */
3011 /* Loop all pages and probe them */
3012 CurrentVa
= *BaseAddress
;
3013 while (CurrentVa
< EndAddress
)
3015 (void)(*(volatile CHAR
*)CurrentVa
);
3016 CurrentVa
= (PUCHAR
)CurrentVa
+ PAGE_SIZE
;
3019 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3021 Status
= _SEH2_GetExceptionCode();
3026 /* All pages were accessible, since we hold the address space lock, nothing
3027 can be de-committed. Assume success for now. */
3028 Status
= STATUS_SUCCESS
;
3030 /* Get the PTE and PDE */
3031 PointerPte
= MiAddressToPte(*BaseAddress
);
3032 PointerPde
= MiAddressToPde(*BaseAddress
);
3033 #if (_MI_PAGING_LEVELS >= 3)
3034 PointerPpe
= MiAddressToPpe(*BaseAddress
);
3036 #if (_MI_PAGING_LEVELS == 4)
3037 PointerPxe
= MiAddressToPxe(*BaseAddress
);
3040 /* Get the last PTE */
3041 LastPte
= MiAddressToPte((PVOID
)((ULONG_PTR
)EndAddress
- 1));
3043 /* Lock the process working set */
3044 MiLockProcessWorkingSet(CurrentProcess
, PsGetCurrentThread());
3046 /* Loop the pages */
3049 /* Check for a page that is not accessible */
3051 #if (_MI_PAGING_LEVELS == 4)
3052 (PointerPxe
->u
.Hard
.Valid
== 0) ||
3054 #if (_MI_PAGING_LEVELS >= 3)
3055 (PointerPpe
->u
.Hard
.Valid
== 0) ||
3057 (PointerPde
->u
.Hard
.Valid
== 0) ||
3058 (PointerPte
->u
.Hard
.Valid
== 0))
3060 /* Release process working set */
3061 MiUnlockProcessWorkingSet(CurrentProcess
, PsGetCurrentThread());
3063 /* Access the page */
3064 CurrentVa
= MiPteToAddress(PointerPte
);
3066 //HACK: Pass a placeholder TrapInformation so the fault handler knows we're unlocked
3067 TempStatus
= MmAccessFault(TRUE
, CurrentVa
, KernelMode
, (PVOID
)0xBADBADA3);
3068 if (!NT_SUCCESS(TempStatus
))
3070 // This should only happen, when remote backing storage is not accessible
3072 Status
= TempStatus
;
3076 /* Lock the process working set */
3077 MiLockProcessWorkingSet(CurrentProcess
, PsGetCurrentThread());
3081 Pfn1
= MiGetPfnEntry(PFN_FROM_PTE(PointerPte
));
3082 ASSERT(Pfn1
!= NULL
);
3084 /* Check the previous lock status */
3085 if (MI_IS_LOCKED_VA(Pfn1
, MapType
))
3087 Status
= STATUS_WAS_LOCKED
;
3091 MI_LOCK_VA(Pfn1
, MapType
);
3093 /* Go to the next PTE */
3096 /* Check if we're on a PDE boundary */
3097 if (MiIsPteOnPdeBoundary(PointerPte
)) PointerPde
++;
3098 #if (_MI_PAGING_LEVELS >= 3)
3099 if (MiIsPteOnPpeBoundary(PointerPte
)) PointerPpe
++;
3101 #if (_MI_PAGING_LEVELS == 4)
3102 if (MiIsPteOnPxeBoundary(PointerPte
)) PointerPxe
++;
3104 } while (PointerPte
<= LastPte
);
3106 /* Release process working set */
3107 MiUnlockProcessWorkingSet(CurrentProcess
, PsGetCurrentThread());
3110 /* Unlock address space */
3111 MmUnlockAddressSpace(AddressSpace
);
3118 NtLockVirtualMemory(IN HANDLE ProcessHandle
,
3119 IN OUT PVOID
*BaseAddress
,
3120 IN OUT PSIZE_T NumberOfBytesToLock
,
3124 PEPROCESS CurrentProcess
= PsGetCurrentProcess();
3126 BOOLEAN Attached
= FALSE
;
3127 KAPC_STATE ApcState
;
3128 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
3129 PVOID CapturedBaseAddress
;
3130 SIZE_T CapturedBytesToLock
;
3136 if ((MapType
& ~(MAP_PROCESS
| MAP_SYSTEM
)))
3139 // Invalid set of flags
3141 return STATUS_INVALID_PARAMETER
;
3145 // At least one flag must be specified
3147 if (!(MapType
& (MAP_PROCESS
| MAP_SYSTEM
)))
3152 return STATUS_INVALID_PARAMETER
;
3156 // Enter SEH for probing
3161 // Validate output data
3163 ProbeForWritePointer(BaseAddress
);
3164 ProbeForWriteSize_t(NumberOfBytesToLock
);
3169 CapturedBaseAddress
= *BaseAddress
;
3170 CapturedBytesToLock
= *NumberOfBytesToLock
;
3172 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3175 // Get exception code
3177 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3182 // Catch illegal base address
3184 if (CapturedBaseAddress
> MM_HIGHEST_USER_ADDRESS
) return STATUS_INVALID_PARAMETER
;
3187 // Catch illegal region size
3189 if ((MmUserProbeAddress
- (ULONG_PTR
)CapturedBaseAddress
) < CapturedBytesToLock
)
3194 return STATUS_INVALID_PARAMETER
;
3198 // 0 is also illegal
3200 if (!CapturedBytesToLock
) return STATUS_INVALID_PARAMETER
;
3203 // Get a reference to the process
3205 Status
= ObReferenceObjectByHandle(ProcessHandle
,
3206 PROCESS_VM_OPERATION
,
3211 if (!NT_SUCCESS(Status
)) return Status
;
3214 // Check if this is is system-mapped
3216 if (MapType
& MAP_SYSTEM
)
3219 // Check for required privilege
3221 if (!SeSinglePrivilegeCheck(SeLockMemoryPrivilege
, PreviousMode
))
3224 // Fail: Don't have it
3226 ObDereferenceObject(Process
);
3227 return STATUS_PRIVILEGE_NOT_HELD
;
3232 // Check if we should attach
3234 if (CurrentProcess
!= Process
)
3239 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
3244 // Call the internal function
3246 Status
= MiLockVirtualMemory(&CapturedBaseAddress
,
3247 &CapturedBytesToLock
,
3253 if (Attached
) KeUnstackDetachProcess(&ApcState
);
3256 // Release reference
3258 ObDereferenceObject(Process
);
3261 // Enter SEH to return data
3266 // Return data to user
3268 *BaseAddress
= CapturedBaseAddress
;
3269 *NumberOfBytesToLock
= CapturedBytesToLock
;
3271 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3274 // Get exception code
3276 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3289 MiUnlockVirtualMemory(
3290 IN OUT PVOID
*BaseAddress
,
3291 IN OUT PSIZE_T RegionSize
,
3294 PEPROCESS CurrentProcess
;
3295 PMMSUPPORT AddressSpace
;
3297 PMMPTE PointerPte
, LastPte
;
3299 #if (_MI_PAGING_LEVELS >= 3)
3302 #if (_MI_PAGING_LEVELS == 4)
3308 /* Lock the address space */
3309 AddressSpace
= MmGetCurrentAddressSpace();
3310 MmLockAddressSpace(AddressSpace
);
3312 /* Make sure we still have an address space */
3313 CurrentProcess
= PsGetCurrentProcess();
3314 if (CurrentProcess
->VmDeleted
)
3316 Status
= STATUS_PROCESS_IS_TERMINATING
;
3320 /* Check the VADs in the requested range */
3321 Status
= MiCheckVadsForLockOperation(BaseAddress
, RegionSize
, &EndAddress
);
3323 /* Note: only bail out, if we hit an area without a VAD. If we hit an
3324 incompatible VAD we continue, like Windows does */
3325 if (Status
== STATUS_ACCESS_VIOLATION
)
3327 Status
= STATUS_NOT_LOCKED
;
3331 /* Get the PTE and PDE */
3332 PointerPte
= MiAddressToPte(*BaseAddress
);
3333 PointerPde
= MiAddressToPde(*BaseAddress
);
3334 #if (_MI_PAGING_LEVELS >= 3)
3335 PointerPpe
= MiAddressToPpe(*BaseAddress
);
3337 #if (_MI_PAGING_LEVELS == 4)
3338 PointerPxe
= MiAddressToPxe(*BaseAddress
);
3341 /* Get the last PTE */
3342 LastPte
= MiAddressToPte((PVOID
)((ULONG_PTR
)EndAddress
- 1));
3344 /* Lock the process working set */
3345 MiLockProcessWorkingSet(CurrentProcess
, PsGetCurrentThread());
3347 /* Loop the pages */
3350 /* Check for a page that is not present */
3352 #if (_MI_PAGING_LEVELS == 4)
3353 (PointerPxe
->u
.Hard
.Valid
== 0) ||
3355 #if (_MI_PAGING_LEVELS >= 3)
3356 (PointerPpe
->u
.Hard
.Valid
== 0) ||
3358 (PointerPde
->u
.Hard
.Valid
== 0) ||
3359 (PointerPte
->u
.Hard
.Valid
== 0))
3361 /* Remember it, but keep going */
3362 Status
= STATUS_NOT_LOCKED
;
3367 Pfn1
= MiGetPfnEntry(PFN_FROM_PTE(PointerPte
));
3368 ASSERT(Pfn1
!= NULL
);
3370 /* Check if all of the requested locks are present */
3371 if (((MapType
& MAP_SYSTEM
) && !MI_IS_LOCKED_VA(Pfn1
, MAP_SYSTEM
)) ||
3372 ((MapType
& MAP_PROCESS
) && !MI_IS_LOCKED_VA(Pfn1
, MAP_PROCESS
)))
3374 /* Remember it, but keep going */
3375 Status
= STATUS_NOT_LOCKED
;
3377 /* Check if no lock is present */
3378 if (!MI_IS_LOCKED_VA(Pfn1
, MAP_PROCESS
| MAP_SYSTEM
))
3380 DPRINT1("FIXME: Should remove the page from WS\n");
3385 /* Go to the next PTE */
3388 /* Check if we're on a PDE boundary */
3389 if (MiIsPteOnPdeBoundary(PointerPte
)) PointerPde
++;
3390 #if (_MI_PAGING_LEVELS >= 3)
3391 if (MiIsPteOnPpeBoundary(PointerPte
)) PointerPpe
++;
3393 #if (_MI_PAGING_LEVELS == 4)
3394 if (MiIsPteOnPxeBoundary(PointerPte
)) PointerPxe
++;
3396 } while (PointerPte
<= LastPte
);
3398 /* Check if we hit a page that was not locked */
3399 if (Status
== STATUS_NOT_LOCKED
)
3401 goto CleanupWithWsLock
;
3404 /* All pages in the region were locked, so unlock them all */
3406 /* Get the PTE and PDE */
3407 PointerPte
= MiAddressToPte(*BaseAddress
);
3408 PointerPde
= MiAddressToPde(*BaseAddress
);
3409 #if (_MI_PAGING_LEVELS >= 3)
3410 PointerPpe
= MiAddressToPpe(*BaseAddress
);
3412 #if (_MI_PAGING_LEVELS == 4)
3413 PointerPxe
= MiAddressToPxe(*BaseAddress
);
3416 /* Loop the pages */
3420 Pfn1
= MiGetPfnEntry(PFN_FROM_PTE(PointerPte
));
3421 MI_UNLOCK_VA(Pfn1
, MapType
);
3423 /* Go to the next PTE */
3426 /* Check if we're on a PDE boundary */
3427 if (MiIsPteOnPdeBoundary(PointerPte
)) PointerPde
++;
3428 #if (_MI_PAGING_LEVELS >= 3)
3429 if (MiIsPteOnPpeBoundary(PointerPte
)) PointerPpe
++;
3431 #if (_MI_PAGING_LEVELS == 4)
3432 if (MiIsPteOnPxeBoundary(PointerPte
)) PointerPxe
++;
3434 } while (PointerPte
<= LastPte
);
3436 /* Everything is done */
3437 Status
= STATUS_SUCCESS
;
3441 /* Release process working set */
3442 MiUnlockProcessWorkingSet(CurrentProcess
, PsGetCurrentThread());
3445 /* Unlock address space */
3446 MmUnlockAddressSpace(AddressSpace
);
3454 NtUnlockVirtualMemory(IN HANDLE ProcessHandle
,
3455 IN OUT PVOID
*BaseAddress
,
3456 IN OUT PSIZE_T NumberOfBytesToUnlock
,
3460 PEPROCESS CurrentProcess
= PsGetCurrentProcess();
3462 BOOLEAN Attached
= FALSE
;
3463 KAPC_STATE ApcState
;
3464 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
3465 PVOID CapturedBaseAddress
;
3466 SIZE_T CapturedBytesToUnlock
;
3472 if ((MapType
& ~(MAP_PROCESS
| MAP_SYSTEM
)))
3475 // Invalid set of flags
3477 return STATUS_INVALID_PARAMETER
;
3481 // At least one flag must be specified
3483 if (!(MapType
& (MAP_PROCESS
| MAP_SYSTEM
)))
3488 return STATUS_INVALID_PARAMETER
;
3492 // Enter SEH for probing
3497 // Validate output data
3499 ProbeForWritePointer(BaseAddress
);
3500 ProbeForWriteSize_t(NumberOfBytesToUnlock
);
3505 CapturedBaseAddress
= *BaseAddress
;
3506 CapturedBytesToUnlock
= *NumberOfBytesToUnlock
;
3508 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3511 // Get exception code
3513 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3518 // Catch illegal base address
3520 if (CapturedBaseAddress
> MM_HIGHEST_USER_ADDRESS
) return STATUS_INVALID_PARAMETER
;
3523 // Catch illegal region size
3525 if ((MmUserProbeAddress
- (ULONG_PTR
)CapturedBaseAddress
) < CapturedBytesToUnlock
)
3530 return STATUS_INVALID_PARAMETER
;
3534 // 0 is also illegal
3536 if (!CapturedBytesToUnlock
) return STATUS_INVALID_PARAMETER
;
3539 // Get a reference to the process
3541 Status
= ObReferenceObjectByHandle(ProcessHandle
,
3542 PROCESS_VM_OPERATION
,
3547 if (!NT_SUCCESS(Status
)) return Status
;
3550 // Check if this is is system-mapped
3552 if (MapType
& MAP_SYSTEM
)
3555 // Check for required privilege
3557 if (!SeSinglePrivilegeCheck(SeLockMemoryPrivilege
, PreviousMode
))
3560 // Fail: Don't have it
3562 ObDereferenceObject(Process
);
3563 return STATUS_PRIVILEGE_NOT_HELD
;
3568 // Check if we should attach
3570 if (CurrentProcess
!= Process
)
3575 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
3580 // Call the internal function
3582 Status
= MiUnlockVirtualMemory(&CapturedBaseAddress
,
3583 &CapturedBytesToUnlock
,
3589 if (Attached
) KeUnstackDetachProcess(&ApcState
);
3592 // Release reference
3594 ObDereferenceObject(Process
);
3597 // Enter SEH to return data
3602 // Return data to user
3604 *BaseAddress
= CapturedBaseAddress
;
3605 *NumberOfBytesToUnlock
= CapturedBytesToUnlock
;
3607 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3610 // Get exception code
3612 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3619 return STATUS_SUCCESS
;
3624 NtFlushVirtualMemory(IN HANDLE ProcessHandle
,
3625 IN OUT PVOID
*BaseAddress
,
3626 IN OUT PSIZE_T NumberOfBytesToFlush
,
3627 OUT PIO_STATUS_BLOCK IoStatusBlock
)
3631 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
3632 PVOID CapturedBaseAddress
;
3633 SIZE_T CapturedBytesToFlush
;
3634 IO_STATUS_BLOCK LocalStatusBlock
;
3638 // Check if we came from user mode
3640 if (PreviousMode
!= KernelMode
)
3643 // Enter SEH for probing
3648 // Validate all outputs
3650 ProbeForWritePointer(BaseAddress
);
3651 ProbeForWriteSize_t(NumberOfBytesToFlush
);
3652 ProbeForWriteIoStatusBlock(IoStatusBlock
);
3657 CapturedBaseAddress
= *BaseAddress
;
3658 CapturedBytesToFlush
= *NumberOfBytesToFlush
;
3660 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3663 // Get exception code
3665 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3674 CapturedBaseAddress
= *BaseAddress
;
3675 CapturedBytesToFlush
= *NumberOfBytesToFlush
;
3679 // Catch illegal base address
3681 if (CapturedBaseAddress
> MM_HIGHEST_USER_ADDRESS
) return STATUS_INVALID_PARAMETER
;
3684 // Catch illegal region size
3686 if ((MmUserProbeAddress
- (ULONG_PTR
)CapturedBaseAddress
) < CapturedBytesToFlush
)
3691 return STATUS_INVALID_PARAMETER
;
3695 // Get a reference to the process
3697 Status
= ObReferenceObjectByHandle(ProcessHandle
,
3698 PROCESS_VM_OPERATION
,
3703 if (!NT_SUCCESS(Status
)) return Status
;
3708 Status
= MmFlushVirtualMemory(Process
,
3709 &CapturedBaseAddress
,
3710 &CapturedBytesToFlush
,
3714 // Release reference
3716 ObDereferenceObject(Process
);
3719 // Enter SEH to return data
3724 // Return data to user
3726 *BaseAddress
= PAGE_ALIGN(CapturedBaseAddress
);
3727 *NumberOfBytesToFlush
= 0;
3728 *IoStatusBlock
= LocalStatusBlock
;
3730 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3746 NtGetWriteWatch(IN HANDLE ProcessHandle
,
3748 IN PVOID BaseAddress
,
3749 IN SIZE_T RegionSize
,
3750 IN PVOID
*UserAddressArray
,
3751 OUT PULONG_PTR EntriesInUserAddressArray
,
3752 OUT PULONG Granularity
)
3757 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
3758 ULONG_PTR CapturedEntryCount
;
3762 // Check if we came from user mode
3764 if (PreviousMode
!= KernelMode
)
3767 // Enter SEH for probing
3772 // Catch illegal base address
3774 if (BaseAddress
> MM_HIGHEST_USER_ADDRESS
) _SEH2_YIELD(return STATUS_INVALID_PARAMETER_2
);
3777 // Catch illegal region size
3779 if ((MmUserProbeAddress
- (ULONG_PTR
)BaseAddress
) < RegionSize
)
3784 _SEH2_YIELD(return STATUS_INVALID_PARAMETER_3
);
3788 // Validate all data
3790 ProbeForWriteSize_t(EntriesInUserAddressArray
);
3791 ProbeForWriteUlong(Granularity
);
3796 CapturedEntryCount
= *EntriesInUserAddressArray
;
3799 // Must have a count
3801 if (CapturedEntryCount
== 0) _SEH2_YIELD(return STATUS_INVALID_PARAMETER_5
);
3804 // Can't be larger than the maximum
3806 if (CapturedEntryCount
> (MAXULONG_PTR
/ sizeof(ULONG_PTR
)))
3811 _SEH2_YIELD(return STATUS_INVALID_PARAMETER_5
);
3815 // Probe the actual array
3817 ProbeForWrite(UserAddressArray
,
3818 CapturedEntryCount
* sizeof(PVOID
),
3821 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3824 // Get exception code
3826 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3835 CapturedEntryCount
= *EntriesInUserAddressArray
;
3836 ASSERT(CapturedEntryCount
!= 0);
3840 // Check if this is a local request
3842 if (ProcessHandle
== NtCurrentProcess())
3845 // No need to reference the process
3847 Process
= PsGetCurrentProcess();
3852 // Reference the target
3854 Status
= ObReferenceObjectByHandle(ProcessHandle
,
3855 PROCESS_VM_OPERATION
,
3860 if (!NT_SUCCESS(Status
)) return Status
;
3864 // Compute the last address and validate it
3866 EndAddress
= (PVOID
)((ULONG_PTR
)BaseAddress
+ RegionSize
- 1);
3867 if (BaseAddress
> EndAddress
)
3872 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
3873 return STATUS_INVALID_PARAMETER_4
;
3882 // Dereference if needed
3884 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
3887 // Enter SEH to return data
3892 // Return data to user
3894 *EntriesInUserAddressArray
= 0;
3895 *Granularity
= PAGE_SIZE
;
3897 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3900 // Get exception code
3902 Status
= _SEH2_GetExceptionCode();
3909 return STATUS_SUCCESS
;
3917 NtResetWriteWatch(IN HANDLE ProcessHandle
,
3918 IN PVOID BaseAddress
,
3919 IN SIZE_T RegionSize
)
3924 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
3925 ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL
);
3928 // Catch illegal base address
3930 if (BaseAddress
> MM_HIGHEST_USER_ADDRESS
) return STATUS_INVALID_PARAMETER_2
;
3933 // Catch illegal region size
3935 if ((MmUserProbeAddress
- (ULONG_PTR
)BaseAddress
) < RegionSize
)
3940 return STATUS_INVALID_PARAMETER_3
;
3944 // Check if this is a local request
3946 if (ProcessHandle
== NtCurrentProcess())
3949 // No need to reference the process
3951 Process
= PsGetCurrentProcess();
3956 // Reference the target
3958 Status
= ObReferenceObjectByHandle(ProcessHandle
,
3959 PROCESS_VM_OPERATION
,
3964 if (!NT_SUCCESS(Status
)) return Status
;
3968 // Compute the last address and validate it
3970 EndAddress
= (PVOID
)((ULONG_PTR
)BaseAddress
+ RegionSize
- 1);
3971 if (BaseAddress
> EndAddress
)
3976 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
3977 return STATUS_INVALID_PARAMETER_3
;
3986 // Dereference if needed
3988 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
3993 return STATUS_SUCCESS
;
3998 NtQueryVirtualMemory(IN HANDLE ProcessHandle
,
3999 IN PVOID BaseAddress
,
4000 IN MEMORY_INFORMATION_CLASS MemoryInformationClass
,
4001 OUT PVOID MemoryInformation
,
4002 IN SIZE_T MemoryInformationLength
,
4003 OUT PSIZE_T ReturnLength
)
4005 NTSTATUS Status
= STATUS_SUCCESS
;
4006 KPROCESSOR_MODE PreviousMode
;
4008 DPRINT("Querying class %d about address: %p\n", MemoryInformationClass
, BaseAddress
);
4010 /* Bail out if the address is invalid */
4011 if (BaseAddress
> MM_HIGHEST_USER_ADDRESS
) return STATUS_INVALID_PARAMETER
;
4013 /* Probe return buffer */
4014 PreviousMode
= ExGetPreviousMode();
4015 if (PreviousMode
!= KernelMode
)
4019 ProbeForWrite(MemoryInformation
,
4020 MemoryInformationLength
,
4023 if (ReturnLength
) ProbeForWriteSize_t(ReturnLength
);
4025 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
4027 Status
= _SEH2_GetExceptionCode();
4031 if (!NT_SUCCESS(Status
))
4037 switch(MemoryInformationClass
)
4039 case MemoryBasicInformation
:
4040 /* Validate the size information of the class */
4041 if (MemoryInformationLength
< sizeof(MEMORY_BASIC_INFORMATION
))
4043 /* The size is invalid */
4044 return STATUS_INFO_LENGTH_MISMATCH
;
4046 Status
= MiQueryMemoryBasicInformation(ProcessHandle
,
4049 MemoryInformationLength
,
4053 case MemorySectionName
:
4054 /* Validate the size information of the class */
4055 if (MemoryInformationLength
< sizeof(MEMORY_SECTION_NAME
))
4057 /* The size is invalid */
4058 return STATUS_INFO_LENGTH_MISMATCH
;
4060 Status
= MiQueryMemorySectionName(ProcessHandle
,
4063 MemoryInformationLength
,
4066 case MemoryWorkingSetList
:
4067 case MemoryBasicVlmInformation
:
4069 DPRINT1("Unhandled memory information class %d\n", MemoryInformationClass
);
4081 NtAllocateVirtualMemory(IN HANDLE ProcessHandle
,
4082 IN OUT PVOID
* UBaseAddress
,
4083 IN ULONG_PTR ZeroBits
,
4084 IN OUT PSIZE_T URegionSize
,
4085 IN ULONG AllocationType
,
4089 PMEMORY_AREA MemoryArea
;
4090 PFN_NUMBER PageCount
;
4091 PMMVAD Vad
, FoundVad
;
4093 PMMSUPPORT AddressSpace
;
4095 ULONG_PTR PRegionSize
, StartingAddress
, EndingAddress
;
4096 PEPROCESS CurrentProcess
= PsGetCurrentProcess();
4097 KPROCESSOR_MODE PreviousMode
= KeGetPreviousMode();
4098 PETHREAD CurrentThread
= PsGetCurrentThread();
4099 KAPC_STATE ApcState
;
4100 ULONG ProtectionMask
, QuotaCharge
= 0, QuotaFree
= 0;
4101 BOOLEAN Attached
= FALSE
, ChangeProtection
= FALSE
;
4103 PMMPTE PointerPte
, PointerPde
, LastPte
;
4104 TABLE_SEARCH_RESULT Result
;
4105 PMMADDRESS_NODE Parent
;
4108 /* Check for valid Zero bits */
4111 DPRINT1("Too many zero bits\n");
4112 return STATUS_INVALID_PARAMETER_3
;
4115 /* Check for valid Allocation Types */
4116 if ((AllocationType
& ~(MEM_COMMIT
| MEM_RESERVE
| MEM_RESET
| MEM_PHYSICAL
|
4117 MEM_TOP_DOWN
| MEM_WRITE_WATCH
)))
4119 DPRINT1("Invalid Allocation Type\n");
4120 return STATUS_INVALID_PARAMETER_5
;
4123 /* Check for at least one of these Allocation Types to be set */
4124 if (!(AllocationType
& (MEM_COMMIT
| MEM_RESERVE
| MEM_RESET
)))
4126 DPRINT1("No memory allocation base type\n");
4127 return STATUS_INVALID_PARAMETER_5
;
4130 /* MEM_RESET is an exclusive flag, make sure that is valid too */
4131 if ((AllocationType
& MEM_RESET
) && (AllocationType
!= MEM_RESET
))
4133 DPRINT1("Invalid use of MEM_RESET\n");
4134 return STATUS_INVALID_PARAMETER_5
;
4137 /* Check if large pages are being used */
4138 if (AllocationType
& MEM_LARGE_PAGES
)
4140 /* Large page allocations MUST be committed */
4141 if (!(AllocationType
& MEM_COMMIT
))
4143 DPRINT1("Must supply MEM_COMMIT with MEM_LARGE_PAGES\n");
4144 return STATUS_INVALID_PARAMETER_5
;
4147 /* These flags are not allowed with large page allocations */
4148 if (AllocationType
& (MEM_PHYSICAL
| MEM_RESET
| MEM_WRITE_WATCH
))
4150 DPRINT1("Using illegal flags with MEM_LARGE_PAGES\n");
4151 return STATUS_INVALID_PARAMETER_5
;
4155 /* MEM_WRITE_WATCH can only be used if MEM_RESERVE is also used */
4156 if ((AllocationType
& MEM_WRITE_WATCH
) && !(AllocationType
& MEM_RESERVE
))
4158 DPRINT1("MEM_WRITE_WATCH used without MEM_RESERVE\n");
4159 return STATUS_INVALID_PARAMETER_5
;
4162 /* MEM_PHYSICAL can only be used if MEM_RESERVE is also used */
4163 if ((AllocationType
& MEM_PHYSICAL
) && !(AllocationType
& MEM_RESERVE
))
4165 DPRINT1("MEM_WRITE_WATCH used without MEM_RESERVE\n");
4166 return STATUS_INVALID_PARAMETER_5
;
4169 /* Check for valid MEM_PHYSICAL usage */
4170 if (AllocationType
& MEM_PHYSICAL
)
4172 /* Only these flags are allowed with MEM_PHYSIAL */
4173 if (AllocationType
& ~(MEM_RESERVE
| MEM_TOP_DOWN
| MEM_PHYSICAL
))
4175 DPRINT1("Using illegal flags with MEM_PHYSICAL\n");
4176 return STATUS_INVALID_PARAMETER_5
;
4179 /* Then make sure PAGE_READWRITE is used */
4180 if (Protect
!= PAGE_READWRITE
)
4182 DPRINT1("MEM_PHYSICAL used without PAGE_READWRITE\n");
4183 return STATUS_INVALID_PARAMETER_6
;
4187 /* Calculate the protection mask and make sure it's valid */
4188 ProtectionMask
= MiMakeProtectionMask(Protect
);
4189 if (ProtectionMask
== MM_INVALID_PROTECTION
)
4191 DPRINT1("Invalid protection mask\n");
4192 return STATUS_INVALID_PAGE_PROTECTION
;
4198 /* Check for user-mode parameters */
4199 if (PreviousMode
!= KernelMode
)
4201 /* Make sure they are writable */
4202 ProbeForWritePointer(UBaseAddress
);
4203 ProbeForWriteUlong(URegionSize
);
4206 /* Capture their values */
4207 PBaseAddress
= *UBaseAddress
;
4208 PRegionSize
= *URegionSize
;
4210 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
4212 /* Return the exception code */
4213 _SEH2_YIELD(return _SEH2_GetExceptionCode());
4217 /* Make sure the allocation isn't past the VAD area */
4218 if (PBaseAddress
>= MM_HIGHEST_VAD_ADDRESS
)
4220 DPRINT1("Virtual allocation base above User Space\n");
4221 return STATUS_INVALID_PARAMETER_2
;
4224 /* Make sure the allocation wouldn't overflow past the VAD area */
4225 if ((((ULONG_PTR
)MM_HIGHEST_VAD_ADDRESS
+ 1) - (ULONG_PTR
)PBaseAddress
) < PRegionSize
)
4227 DPRINT1("Region size would overflow into kernel-memory\n");
4228 return STATUS_INVALID_PARAMETER_4
;
4231 /* Make sure there's a size specified */
4234 DPRINT1("Region size is invalid (zero)\n");
4235 return STATUS_INVALID_PARAMETER_4
;
4239 // If this is for the current process, just use PsGetCurrentProcess
4241 if (ProcessHandle
== NtCurrentProcess())
4243 Process
= CurrentProcess
;
4248 // Otherwise, reference the process with VM rights and attach to it if
4249 // this isn't the current process. We must attach because we'll be touching
4250 // PTEs and PDEs that belong to user-mode memory, and also touching the
4251 // Working Set which is stored in Hyperspace.
4253 Status
= ObReferenceObjectByHandle(ProcessHandle
,
4254 PROCESS_VM_OPERATION
,
4259 if (!NT_SUCCESS(Status
)) return Status
;
4260 if (CurrentProcess
!= Process
)
4262 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
4268 // Check for large page allocations and make sure that the required privilege
4269 // is being held, before attempting to handle them.
4271 if ((AllocationType
& MEM_LARGE_PAGES
) &&
4272 !(SeSinglePrivilegeCheck(SeLockMemoryPrivilege
, PreviousMode
)))
4274 /* Fail without it */
4275 DPRINT1("Privilege not held for MEM_LARGE_PAGES\n");
4276 Status
= STATUS_PRIVILEGE_NOT_HELD
;
4277 goto FailPathNoLock
;
4281 // Fail on the things we don't yet support
4285 DPRINT1("Zero bits not supported\n");
4286 Status
= STATUS_INVALID_PARAMETER
;
4287 goto FailPathNoLock
;
4289 if ((AllocationType
& MEM_LARGE_PAGES
) == MEM_LARGE_PAGES
)
4291 DPRINT1("MEM_LARGE_PAGES not supported\n");
4292 Status
= STATUS_INVALID_PARAMETER
;
4293 goto FailPathNoLock
;
4295 if ((AllocationType
& MEM_PHYSICAL
) == MEM_PHYSICAL
)
4297 DPRINT1("MEM_PHYSICAL not supported\n");
4298 Status
= STATUS_INVALID_PARAMETER
;
4299 goto FailPathNoLock
;
4301 if ((AllocationType
& MEM_WRITE_WATCH
) == MEM_WRITE_WATCH
)
4303 DPRINT1("MEM_WRITE_WATCH not supported\n");
4304 Status
= STATUS_INVALID_PARAMETER
;
4305 goto FailPathNoLock
;
4307 if ((AllocationType
& MEM_TOP_DOWN
) == MEM_TOP_DOWN
)
4309 DPRINT1("MEM_TOP_DOWN not supported\n");
4310 AllocationType
&= ~MEM_TOP_DOWN
;
4313 if (Process
->VmTopDown
== 1)
4315 DPRINT1("VmTopDown not supported\n");
4316 Status
= STATUS_INVALID_PARAMETER
;
4317 goto FailPathNoLock
;
4321 // Check if the caller is reserving memory, or committing memory and letting
4322 // us pick the base address
4324 if (!(PBaseAddress
) || (AllocationType
& MEM_RESERVE
))
4327 // Do not allow COPY_ON_WRITE through this API
4329 if ((Protect
& PAGE_WRITECOPY
) || (Protect
& PAGE_EXECUTE_WRITECOPY
))
4331 DPRINT1("Copy on write not allowed through this path\n");
4332 Status
= STATUS_INVALID_PAGE_PROTECTION
;
4333 goto FailPathNoLock
;
4337 // Does the caller have an address in mind, or is this a blind commit?
4342 // This is a blind commit, all we need is the region size
4344 PRegionSize
= ROUND_TO_PAGES(PRegionSize
);
4345 PageCount
= BYTES_TO_PAGES(PRegionSize
);
4347 StartingAddress
= 0;
4352 // This is a reservation, so compute the starting address on the
4353 // expected 64KB granularity, and see where the ending address will
4354 // fall based on the aligned address and the passed in region size
4356 StartingAddress
= ROUND_DOWN((ULONG_PTR
)PBaseAddress
, _64K
);
4357 EndingAddress
= ((ULONG_PTR
)PBaseAddress
+ PRegionSize
- 1) | (PAGE_SIZE
- 1);
4358 PageCount
= BYTES_TO_PAGES(EndingAddress
- StartingAddress
);
4362 // Allocate and initialize the VAD
4364 Vad
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(MMVAD_LONG
), 'SdaV');
4365 ASSERT(Vad
!= NULL
);
4366 Vad
->u
.LongFlags
= 0;
4367 if (AllocationType
& MEM_COMMIT
) Vad
->u
.VadFlags
.MemCommit
= 1;
4368 Vad
->u
.VadFlags
.Protection
= ProtectionMask
;
4369 Vad
->u
.VadFlags
.PrivateMemory
= 1;
4370 Vad
->u
.VadFlags
.CommitCharge
= AllocationType
& MEM_COMMIT
? PageCount
: 0;
4373 // Lock the address space and make sure the process isn't already dead
4375 AddressSpace
= MmGetCurrentAddressSpace();
4376 MmLockAddressSpace(AddressSpace
);
4377 if (Process
->VmDeleted
)
4379 Status
= STATUS_PROCESS_IS_TERMINATING
;
4384 // Did we have a base address? If no, find a valid address that is 64KB
4385 // aligned in the VAD tree. Otherwise, make sure that the address range
4386 // which was passed in isn't already conflicting with an existing address
4391 /* Which way should we search? */
4392 if (AllocationType
& MEM_TOP_DOWN
)
4394 /* Find an address top-down */
4395 Result
= MiFindEmptyAddressRangeDownTree(PRegionSize
,
4396 (ULONG_PTR
)MM_HIGHEST_VAD_ADDRESS
,
4404 /* Find an address bottom-up */
4405 Result
= MiFindEmptyAddressRangeInTree(PRegionSize
,
4412 if (Result
== TableFoundNode
)
4414 Status
= STATUS_NO_MEMORY
;
4419 // Now we know where the allocation ends. Make sure it doesn't end up
4420 // somewhere in kernel mode.
4422 NT_ASSERT(StartingAddress
!= 0);
4423 EndingAddress
= (StartingAddress
+ PRegionSize
- 1) | (PAGE_SIZE
- 1);
4424 if ((PVOID
)EndingAddress
> MM_HIGHEST_VAD_ADDRESS
)
4426 Status
= STATUS_NO_MEMORY
;
4432 /* Make sure it doesn't conflict with an existing allocation */
4433 Result
= MiCheckForConflictingNode(StartingAddress
>> PAGE_SHIFT
,
4434 EndingAddress
>> PAGE_SHIFT
,
4437 if (Result
== TableFoundNode
)
4440 // The address specified is in conflict!
4442 Status
= STATUS_CONFLICTING_ADDRESSES
;
4448 // Write out the VAD fields for this allocation
4450 Vad
->StartingVpn
= (ULONG_PTR
)StartingAddress
>> PAGE_SHIFT
;
4451 Vad
->EndingVpn
= (ULONG_PTR
)EndingAddress
>> PAGE_SHIFT
;
4454 // FIXME: Should setup VAD bitmap
4456 Status
= STATUS_SUCCESS
;
4459 // Lock the working set and insert the VAD into the process VAD tree
4461 MiLockProcessWorkingSetUnsafe(Process
, CurrentThread
);
4462 Vad
->ControlArea
= NULL
; // For Memory-Area hack
4463 Process
->VadRoot
.NodeHint
= Vad
;
4464 MiInsertNode(&Process
->VadRoot
, (PVOID
)Vad
, Parent
, Result
);
4465 MiUnlockProcessWorkingSetUnsafe(Process
, CurrentThread
);
4468 // Update the virtual size of the process, and if this is now the highest
4469 // virtual size we have ever seen, update the peak virtual size to reflect
4472 Process
->VirtualSize
+= PRegionSize
;
4473 if (Process
->VirtualSize
> Process
->PeakVirtualSize
)
4475 Process
->PeakVirtualSize
= Process
->VirtualSize
;
4479 // Release address space and detach and dereference the target process if
4480 // it was different from the current process
4482 MmUnlockAddressSpace(AddressSpace
);
4483 if (Attached
) KeUnstackDetachProcess(&ApcState
);
4484 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
4487 // Use SEH to write back the base address and the region size. In the case
4488 // of an exception, we do not return back the exception code, as the memory
4489 // *has* been allocated. The caller would now have to call VirtualQuery
4490 // or do some other similar trick to actually find out where its memory
4491 // allocation ended up
4495 *URegionSize
= PRegionSize
;
4496 *UBaseAddress
= (PVOID
)StartingAddress
;
4498 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
4502 return STATUS_SUCCESS
;
4506 // This is a MEM_COMMIT on top of an existing address which must have been
4507 // MEM_RESERVED already. Compute the start and ending base addresses based
4508 // on the user input, and then compute the actual region size once all the
4509 // alignments have been done.
4511 StartingAddress
= (ULONG_PTR
)PAGE_ALIGN(PBaseAddress
);
4512 EndingAddress
= (((ULONG_PTR
)PBaseAddress
+ PRegionSize
- 1) | (PAGE_SIZE
- 1));
4513 PRegionSize
= EndingAddress
- StartingAddress
+ 1;
4516 // Lock the address space and make sure the process isn't already dead
4518 AddressSpace
= MmGetCurrentAddressSpace();
4519 MmLockAddressSpace(AddressSpace
);
4520 if (Process
->VmDeleted
)
4522 DPRINT1("Process is dying\n");
4523 Status
= STATUS_PROCESS_IS_TERMINATING
;
4528 // Get the VAD for this address range, and make sure it exists
4530 Result
= MiCheckForConflictingNode(StartingAddress
>> PAGE_SHIFT
,
4531 EndingAddress
>> PAGE_SHIFT
,
4533 (PMMADDRESS_NODE
*)&FoundVad
);
4534 if (Result
!= TableFoundNode
)
4536 DPRINT1("Could not find a VAD for this allocation\n");
4537 Status
= STATUS_CONFLICTING_ADDRESSES
;
4541 if ((AllocationType
& MEM_RESET
) == MEM_RESET
)
4543 /// @todo HACK: pretend success
4544 DPRINT("MEM_RESET not supported\n");
4545 Status
= STATUS_SUCCESS
;
4550 // These kinds of VADs are illegal for this Windows function when trying to
4551 // commit an existing range
4553 if ((FoundVad
->u
.VadFlags
.VadType
== VadAwe
) ||
4554 (FoundVad
->u
.VadFlags
.VadType
== VadDevicePhysicalMemory
) ||
4555 (FoundVad
->u
.VadFlags
.VadType
== VadLargePages
))
4557 DPRINT1("Illegal VAD for attempting a MEM_COMMIT\n");
4558 Status
= STATUS_CONFLICTING_ADDRESSES
;
4563 // Make sure that this address range actually fits within the VAD for it
4565 if (((StartingAddress
>> PAGE_SHIFT
) < FoundVad
->StartingVpn
) ||
4566 ((EndingAddress
>> PAGE_SHIFT
) > FoundVad
->EndingVpn
))
4568 DPRINT1("Address range does not fit into the VAD\n");
4569 Status
= STATUS_CONFLICTING_ADDRESSES
;
4574 // Make sure this is an ARM3 section
4576 MemoryArea
= MmLocateMemoryAreaByAddress(AddressSpace
, (PVOID
)PAGE_ROUND_DOWN(PBaseAddress
));
4577 if (MemoryArea
->Type
!= MEMORY_AREA_OWNED_BY_ARM3
)
4579 DPRINT1("Illegal commit of non-ARM3 section!\n");
4580 Status
= STATUS_ALREADY_COMMITTED
;
4584 // Is this a previously reserved section being committed? If so, enter the
4585 // special section path
4587 if (FoundVad
->u
.VadFlags
.PrivateMemory
== FALSE
)
4590 // You cannot commit large page sections through this API
4592 if (FoundVad
->u
.VadFlags
.VadType
== VadLargePageSection
)
4594 DPRINT1("Large page sections cannot be VirtualAlloc'd\n");
4595 Status
= STATUS_INVALID_PAGE_PROTECTION
;
4600 // You can only use caching flags on a rotate VAD
4602 if ((Protect
& (PAGE_NOCACHE
| PAGE_WRITECOMBINE
)) &&
4603 (FoundVad
->u
.VadFlags
.VadType
!= VadRotatePhysical
))
4605 DPRINT1("Cannot use caching flags with anything but rotate VADs\n");
4606 Status
= STATUS_INVALID_PAGE_PROTECTION
;
4611 // We should make sure that the section's permissions aren't being
4614 if (FoundVad
->u
.VadFlags
.NoChange
)
4617 // Make sure it's okay to touch it
4619 Status
= MiCheckSecuredVad(FoundVad
,
4623 if (!NT_SUCCESS(Status
))
4625 DPRINT1("Secured VAD being messed around with\n");
4631 // ARM3 does not support file-backed sections, only shared memory
4633 ASSERT(FoundVad
->ControlArea
->FilePointer
== NULL
);
4636 // Rotate VADs cannot be guard pages or inaccessible, nor copy on write
4638 if ((FoundVad
->u
.VadFlags
.VadType
== VadRotatePhysical
) &&
4639 (Protect
& (PAGE_WRITECOPY
| PAGE_EXECUTE_WRITECOPY
| PAGE_NOACCESS
| PAGE_GUARD
)))
4641 DPRINT1("Invalid page protection for rotate VAD\n");
4642 Status
= STATUS_INVALID_PAGE_PROTECTION
;
4647 // Compute PTE addresses and the quota charge, then grab the commit lock
4649 PointerPte
= MI_GET_PROTOTYPE_PTE_FOR_VPN(FoundVad
, StartingAddress
>> PAGE_SHIFT
);
4650 LastPte
= MI_GET_PROTOTYPE_PTE_FOR_VPN(FoundVad
, EndingAddress
>> PAGE_SHIFT
);
4651 QuotaCharge
= (ULONG
)(LastPte
- PointerPte
+ 1);
4652 KeAcquireGuardedMutexUnsafe(&MmSectionCommitMutex
);
4655 // Get the segment template PTE and start looping each page
4657 TempPte
= FoundVad
->ControlArea
->Segment
->SegmentPteTemplate
;
4658 ASSERT(TempPte
.u
.Long
!= 0);
4659 while (PointerPte
<= LastPte
)
4662 // For each non-already-committed page, write the invalid template PTE
4664 if (PointerPte
->u
.Long
== 0)
4666 MI_WRITE_INVALID_PTE(PointerPte
, TempPte
);
4676 // Now do the commit accounting and release the lock
4678 ASSERT(QuotaCharge
>= QuotaFree
);
4679 QuotaCharge
-= QuotaFree
;
4680 FoundVad
->ControlArea
->Segment
->NumberOfCommittedPages
+= QuotaCharge
;
4681 KeReleaseGuardedMutexUnsafe(&MmSectionCommitMutex
);
4684 // We are done with committing the section pages
4686 Status
= STATUS_SUCCESS
;
4691 // This is a specific ReactOS check because we only use normal VADs
4693 ASSERT(FoundVad
->u
.VadFlags
.VadType
== VadNone
);
4696 // While this is an actual Windows check
4698 ASSERT(FoundVad
->u
.VadFlags
.VadType
!= VadRotatePhysical
);
4701 // Throw out attempts to use copy-on-write through this API path
4703 if ((Protect
& PAGE_WRITECOPY
) || (Protect
& PAGE_EXECUTE_WRITECOPY
))
4705 DPRINT1("Write copy attempted when not allowed\n");
4706 Status
= STATUS_INVALID_PAGE_PROTECTION
;
4711 // Initialize a demand-zero PTE
4714 TempPte
.u
.Soft
.Protection
= ProtectionMask
;
4715 NT_ASSERT(TempPte
.u
.Long
!= 0);
4718 // Get the PTE, PDE and the last PTE for this address range
4720 PointerPde
= MiAddressToPde(StartingAddress
);
4721 PointerPte
= MiAddressToPte(StartingAddress
);
4722 LastPte
= MiAddressToPte(EndingAddress
);
4725 // Update the commit charge in the VAD as well as in the process, and check
4726 // if this commit charge was now higher than the last recorded peak, in which
4727 // case we also update the peak
4729 FoundVad
->u
.VadFlags
.CommitCharge
+= (1 + LastPte
- PointerPte
);
4730 Process
->CommitCharge
+= (1 + LastPte
- PointerPte
);
4731 if (Process
->CommitCharge
> Process
->CommitChargePeak
)
4733 Process
->CommitChargePeak
= Process
->CommitCharge
;
4737 // Lock the working set while we play with user pages and page tables
4739 MiLockProcessWorkingSetUnsafe(Process
, CurrentThread
);
4742 // Make the current page table valid, and then loop each page within it
4744 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
4745 while (PointerPte
<= LastPte
)
4748 // Have we crossed into a new page table?
4750 if (MiIsPteOnPdeBoundary(PointerPte
))
4753 // Get the PDE and now make it valid too
4755 PointerPde
= MiAddressToPte(PointerPte
);
4756 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
4760 // Is this a zero PTE as expected?
4762 if (PointerPte
->u
.Long
== 0)
4765 // First increment the count of pages in the page table for this
4768 MiIncrementPageTableReferences(MiPteToAddress(PointerPte
));
4771 // And now write the invalid demand-zero PTE as requested
4773 MI_WRITE_INVALID_PTE(PointerPte
, TempPte
);
4775 else if (PointerPte
->u
.Long
== MmDecommittedPte
.u
.Long
)
4778 // If the PTE was already decommitted, there is nothing else to do
4779 // but to write the new demand-zero PTE
4781 MI_WRITE_INVALID_PTE(PointerPte
, TempPte
);
4783 else if (!(ChangeProtection
) && (Protect
!= MiGetPageProtection(PointerPte
)))
4786 // We don't handle these scenarios yet
4788 if (PointerPte
->u
.Soft
.Valid
== 0)
4790 ASSERT(PointerPte
->u
.Soft
.Prototype
== 0);
4791 ASSERT(PointerPte
->u
.Soft
.PageFileHigh
== 0);
4795 // There's a change in protection, remember this for later, but do
4796 // not yet handle it.
4798 ChangeProtection
= TRUE
;
4802 // Move to the next PTE
4808 // Release the working set lock, unlock the address space, and detach from
4809 // the target process if it was not the current process. Also dereference the
4810 // target process if this wasn't the case.
4812 MiUnlockProcessWorkingSetUnsafe(Process
, CurrentThread
);
4813 Status
= STATUS_SUCCESS
;
4815 MmUnlockAddressSpace(AddressSpace
);
4818 // Check if we need to update the protection
4820 if (ChangeProtection
)
4822 PVOID ProtectBaseAddress
= (PVOID
)StartingAddress
;
4823 SIZE_T ProtectSize
= PRegionSize
;
4824 ULONG OldProtection
;
4827 // Change the protection of the region
4829 MiProtectVirtualMemory(Process
,
4830 &ProtectBaseAddress
,
4837 if (Attached
) KeUnstackDetachProcess(&ApcState
);
4838 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
4841 // Use SEH to write back the base address and the region size. In the case
4842 // of an exception, we strangely do return back the exception code, even
4843 // though the memory *has* been allocated. This mimics Windows behavior and
4844 // there is not much we can do about it.
4848 *URegionSize
= PRegionSize
;
4849 *UBaseAddress
= (PVOID
)StartingAddress
;
4851 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
4853 Status
= _SEH2_GetExceptionCode();
4864 NtFreeVirtualMemory(IN HANDLE ProcessHandle
,
4865 IN PVOID
* UBaseAddress
,
4866 IN PSIZE_T URegionSize
,
4869 PMEMORY_AREA MemoryArea
;
4872 LONG_PTR CommitReduction
= 0;
4873 ULONG_PTR StartingAddress
, EndingAddress
;
4877 PMMSUPPORT AddressSpace
;
4878 PETHREAD CurrentThread
= PsGetCurrentThread();
4879 PEPROCESS CurrentProcess
= PsGetCurrentProcess();
4880 KPROCESSOR_MODE PreviousMode
= KeGetPreviousMode();
4881 KAPC_STATE ApcState
;
4882 BOOLEAN Attached
= FALSE
;
4886 // Only two flags are supported
4888 if (!(FreeType
& (MEM_RELEASE
| MEM_DECOMMIT
)))
4890 DPRINT1("Invalid FreeType\n");
4891 return STATUS_INVALID_PARAMETER_4
;
4895 // Check if no flag was used, or if both flags were used
4897 if (!((FreeType
& (MEM_DECOMMIT
| MEM_RELEASE
))) ||
4898 ((FreeType
& (MEM_DECOMMIT
| MEM_RELEASE
)) == (MEM_DECOMMIT
| MEM_RELEASE
)))
4900 DPRINT1("Invalid FreeType combination\n");
4901 return STATUS_INVALID_PARAMETER_4
;
4905 // Enter SEH for probe and capture. On failure, return back to the caller
4906 // with an exception violation.
4911 // Check for user-mode parameters and make sure that they are writeable
4913 if (PreviousMode
!= KernelMode
)
4915 ProbeForWritePointer(UBaseAddress
);
4916 ProbeForWriteUlong(URegionSize
);
4920 // Capture the current values
4922 PBaseAddress
= *UBaseAddress
;
4923 PRegionSize
= *URegionSize
;
4925 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
4927 _SEH2_YIELD(return _SEH2_GetExceptionCode());
4932 // Make sure the allocation isn't past the user area
4934 if (PBaseAddress
>= MM_HIGHEST_USER_ADDRESS
)
4936 DPRINT1("Virtual free base above User Space\n");
4937 return STATUS_INVALID_PARAMETER_2
;
4941 // Make sure the allocation wouldn't overflow past the user area
4943 if (((ULONG_PTR
)MM_HIGHEST_USER_ADDRESS
- (ULONG_PTR
)PBaseAddress
) < PRegionSize
)
4945 DPRINT1("Region size would overflow into kernel-memory\n");
4946 return STATUS_INVALID_PARAMETER_3
;
4950 // If this is for the current process, just use PsGetCurrentProcess
4952 if (ProcessHandle
== NtCurrentProcess())
4954 Process
= CurrentProcess
;
4959 // Otherwise, reference the process with VM rights and attach to it if
4960 // this isn't the current process. We must attach because we'll be touching
4961 // PTEs and PDEs that belong to user-mode memory, and also touching the
4962 // Working Set which is stored in Hyperspace.
4964 Status
= ObReferenceObjectByHandle(ProcessHandle
,
4965 PROCESS_VM_OPERATION
,
4970 if (!NT_SUCCESS(Status
)) return Status
;
4971 if (CurrentProcess
!= Process
)
4973 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
4979 // Lock the address space
4981 AddressSpace
= MmGetCurrentAddressSpace();
4982 MmLockAddressSpace(AddressSpace
);
4985 // If the address space is being deleted, fail the de-allocation since it's
4986 // too late to do anything about it
4988 if (Process
->VmDeleted
)
4990 DPRINT1("Process is dead\n");
4991 Status
= STATUS_PROCESS_IS_TERMINATING
;
4996 // Compute start and end addresses, and locate the VAD
4998 StartingAddress
= (ULONG_PTR
)PAGE_ALIGN(PBaseAddress
);
4999 EndingAddress
= ((ULONG_PTR
)PBaseAddress
+ PRegionSize
- 1) | (PAGE_SIZE
- 1);
5000 Vad
= MiLocateAddress((PVOID
)StartingAddress
);
5003 DPRINT1("Unable to find VAD for address 0x%p\n", StartingAddress
);
5004 Status
= STATUS_MEMORY_NOT_ALLOCATED
;
5009 // If the range exceeds the VAD's ending VPN, fail this request
5011 if (Vad
->EndingVpn
< (EndingAddress
>> PAGE_SHIFT
))
5013 DPRINT1("Address 0x%p is beyond the VAD\n", EndingAddress
);
5014 Status
= STATUS_UNABLE_TO_FREE_VM
;
5019 // Only private memory (except rotate VADs) can be freed through here */
5021 if ((!(Vad
->u
.VadFlags
.PrivateMemory
) &&
5022 (Vad
->u
.VadFlags
.VadType
!= VadRotatePhysical
)) ||
5023 (Vad
->u
.VadFlags
.VadType
== VadDevicePhysicalMemory
))
5025 DPRINT1("Attempt to free section memory\n");
5026 Status
= STATUS_UNABLE_TO_DELETE_SECTION
;
5031 // ARM3 does not yet handle protected VM
5033 ASSERT(Vad
->u
.VadFlags
.NoChange
== 0);
5036 // Finally, make sure there is a ReactOS Mm MEMORY_AREA for this allocation
5037 // and that is is an ARM3 memory area, and not a section view, as we currently
5038 // don't support freeing those though this interface.
5040 MemoryArea
= MmLocateMemoryAreaByAddress(AddressSpace
, (PVOID
)StartingAddress
);
5042 ASSERT(MemoryArea
->Type
== MEMORY_AREA_OWNED_BY_ARM3
);
5045 // Now we can try the operation. First check if this is a RELEASE or a DECOMMIT
5047 if (FreeType
& MEM_RELEASE
)
5050 // ARM3 only supports this VAD in this path
5052 ASSERT(Vad
->u
.VadFlags
.VadType
== VadNone
);
5055 // Is the caller trying to remove the whole VAD, or remove only a portion
5056 // of it? If no region size is specified, then the assumption is that the
5057 // whole VAD is to be destroyed
5062 // The caller must specify the base address identically to the range
5063 // that is stored in the VAD.
5065 if (((ULONG_PTR
)PBaseAddress
>> PAGE_SHIFT
) != Vad
->StartingVpn
)
5067 DPRINT1("Address 0x%p does not match the VAD\n", PBaseAddress
);
5068 Status
= STATUS_FREE_VM_NOT_AT_BASE
;
5073 // Now compute the actual start/end addresses based on the VAD
5075 StartingAddress
= Vad
->StartingVpn
<< PAGE_SHIFT
;
5076 EndingAddress
= (Vad
->EndingVpn
<< PAGE_SHIFT
) | (PAGE_SIZE
- 1);
5079 // Finally lock the working set and remove the VAD from the VAD tree
5081 MiLockProcessWorkingSetUnsafe(Process
, CurrentThread
);
5082 ASSERT(Process
->VadRoot
.NumberGenericTableElements
>= 1);
5083 MiRemoveNode((PMMADDRESS_NODE
)Vad
, &Process
->VadRoot
);
5088 // This means the caller wants to release a specific region within
5089 // the range. We have to find out which range this is -- the following
5090 // possibilities exist plus their union (CASE D):
5092 // STARTING ADDRESS ENDING ADDRESS
5093 // [<========][========================================][=========>]
5094 // CASE A CASE B CASE C
5097 // First, check for case A or D
5099 if ((StartingAddress
>> PAGE_SHIFT
) == Vad
->StartingVpn
)
5104 if ((EndingAddress
>> PAGE_SHIFT
) == Vad
->EndingVpn
)
5107 // This is the easiest one to handle -- it is identical to
5108 // the code path above when the caller sets a zero region size
5109 // and the whole VAD is destroyed
5111 MiLockProcessWorkingSetUnsafe(Process
, CurrentThread
);
5112 ASSERT(Process
->VadRoot
.NumberGenericTableElements
>= 1);
5113 MiRemoveNode((PMMADDRESS_NODE
)Vad
, &Process
->VadRoot
);
5118 // This case is pretty easy too -- we compute a bunch of
5119 // pages to decommit, and then push the VAD's starting address
5120 // a bit further down, then decrement the commit charge
5122 // NOT YET IMPLEMENTED IN ARM3.
5124 DPRINT1("Case A not handled\n");
5125 Status
= STATUS_FREE_VM_NOT_AT_BASE
;
5129 // After analyzing the VAD, set it to NULL so that we don't
5130 // free it in the exit path
5138 // This is case B or case C. First check for case C
5140 if ((EndingAddress
>> PAGE_SHIFT
) == Vad
->EndingVpn
)
5142 PMEMORY_AREA MemoryArea
;
5145 // This is pretty easy and similar to case A. We compute the
5146 // amount of pages to decommit, update the VAD's commit charge
5147 // and then change the ending address of the VAD to be a bit
5150 MiLockProcessWorkingSetUnsafe(Process
, CurrentThread
);
5151 CommitReduction
= MiCalculatePageCommitment(StartingAddress
,
5155 Vad
->u
.VadFlags
.CommitCharge
-= CommitReduction
;
5156 // For ReactOS: shrink the corresponding memory area
5157 MemoryArea
= MmLocateMemoryAreaByAddress(AddressSpace
, (PVOID
)StartingAddress
);
5158 ASSERT(Vad
->StartingVpn
<< PAGE_SHIFT
== (ULONG_PTR
)MemoryArea
->StartingAddress
);
5159 ASSERT((Vad
->EndingVpn
+ 1) << PAGE_SHIFT
== (ULONG_PTR
)MemoryArea
->EndingAddress
);
5160 Vad
->EndingVpn
= ((ULONG_PTR
)StartingAddress
- 1) >> PAGE_SHIFT
;
5161 MemoryArea
->EndingAddress
= (PVOID
)(((Vad
->EndingVpn
+ 1) << PAGE_SHIFT
) - 1);
5166 // This is case B and the hardest one. Because we are removing
5167 // a chunk of memory from the very middle of the VAD, we must
5168 // actually split the VAD into two new VADs and compute the
5169 // commit charges for each of them, and reinsert new charges.
5171 // NOT YET IMPLEMENTED IN ARM3.
5173 DPRINT1("Case B not handled\n");
5174 Status
= STATUS_FREE_VM_NOT_AT_BASE
;
5179 // After analyzing the VAD, set it to NULL so that we don't
5180 // free it in the exit path
5187 // Now we have a range of pages to dereference, so call the right API
5188 // to do that and then release the working set, since we're done messing
5189 // around with process pages.
5191 MiDeleteVirtualAddresses(StartingAddress
, EndingAddress
, NULL
);
5192 MiUnlockProcessWorkingSetUnsafe(Process
, CurrentThread
);
5193 Status
= STATUS_SUCCESS
;
5197 // Update the process counters
5199 PRegionSize
= EndingAddress
- StartingAddress
+ 1;
5200 Process
->CommitCharge
-= CommitReduction
;
5201 if (FreeType
& MEM_RELEASE
) Process
->VirtualSize
-= PRegionSize
;
5204 // Unlock the address space and free the VAD in failure cases. Next,
5205 // detach from the target process so we can write the region size and the
5206 // base address to the correct source process, and dereference the target
5209 MmUnlockAddressSpace(AddressSpace
);
5210 if (Vad
) ExFreePool(Vad
);
5211 if (Attached
) KeUnstackDetachProcess(&ApcState
);
5212 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
5215 // Use SEH to safely return the region size and the base address of the
5216 // deallocation. If we get an access violation, don't return a failure code
5217 // as the deallocation *has* happened. The caller will just have to figure
5218 // out another way to find out where it is (such as VirtualQuery).
5222 *URegionSize
= PRegionSize
;
5223 *UBaseAddress
= (PVOID
)StartingAddress
;
5225 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
5233 // This is the decommit path. You cannot decommit from the following VADs in
5234 // Windows, so fail the vall
5236 if ((Vad
->u
.VadFlags
.VadType
== VadAwe
) ||
5237 (Vad
->u
.VadFlags
.VadType
== VadLargePages
) ||
5238 (Vad
->u
.VadFlags
.VadType
== VadRotatePhysical
))
5240 DPRINT1("Trying to decommit from invalid VAD\n");
5241 Status
= STATUS_MEMORY_NOT_ALLOCATED
;
5246 // If the caller did not specify a region size, first make sure that this
5247 // region is actually committed. If it is, then compute the ending address
5248 // based on the VAD.
5252 if (((ULONG_PTR
)PBaseAddress
>> PAGE_SHIFT
) != Vad
->StartingVpn
)
5254 DPRINT1("Decomitting non-committed memory\n");
5255 Status
= STATUS_FREE_VM_NOT_AT_BASE
;
5258 EndingAddress
= (Vad
->EndingVpn
<< PAGE_SHIFT
) | (PAGE_SIZE
- 1);
5262 // Decommit the PTEs for the range plus the actual backing pages for the
5263 // range, then reduce that amount from the commit charge in the VAD
5265 CommitReduction
= MiAddressToPte(EndingAddress
) -
5266 MiAddressToPte(StartingAddress
) +
5268 MiDecommitPages((PVOID
)StartingAddress
,
5269 MiAddressToPte(EndingAddress
),
5272 ASSERT(CommitReduction
>= 0);
5273 Vad
->u
.VadFlags
.CommitCharge
-= CommitReduction
;
5274 ASSERT(Vad
->u
.VadFlags
.CommitCharge
>= 0);
5277 // We are done, go to the exit path without freeing the VAD as it remains
5278 // valid since we have not released the allocation.
5281 Status
= STATUS_SUCCESS
;
5285 // In the failure path, we detach and derefernece the target process, and
5286 // return whatever failure code was sent.
5289 MmUnlockAddressSpace(AddressSpace
);
5290 if (Attached
) KeUnstackDetachProcess(&ApcState
);
5291 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
5298 MmGetPhysicalAddress(PVOID Address
)
5300 PHYSICAL_ADDRESS PhysicalAddress
;
5304 /* Check if the PXE/PPE/PDE is valid */
5306 #if (_MI_PAGING_LEVELS == 4)
5307 (MiAddressToPxe(Address
)->u
.Hard
.Valid
) &&
5309 #if (_MI_PAGING_LEVELS >= 3)
5310 (MiAddressToPpe(Address
)->u
.Hard
.Valid
) &&
5312 (MiAddressToPde(Address
)->u
.Hard
.Valid
))
5314 /* Check for large pages */
5315 TempPde
= *MiAddressToPde(Address
);
5316 if (TempPde
.u
.Hard
.LargePage
)
5318 /* Physical address is base page + large page offset */
5319 PhysicalAddress
.QuadPart
= (ULONG64
)TempPde
.u
.Hard
.PageFrameNumber
<< PAGE_SHIFT
;
5320 PhysicalAddress
.QuadPart
+= ((ULONG_PTR
)Address
& (PAGE_SIZE
* PTE_PER_PAGE
- 1));
5321 return PhysicalAddress
;
5324 /* Check if the PTE is valid */
5325 TempPte
= *MiAddressToPte(Address
);
5326 if (TempPte
.u
.Hard
.Valid
)
5328 /* Physical address is base page + page offset */
5329 PhysicalAddress
.QuadPart
= (ULONG64
)TempPte
.u
.Hard
.PageFrameNumber
<< PAGE_SHIFT
;
5330 PhysicalAddress
.QuadPart
+= ((ULONG_PTR
)Address
& (PAGE_SIZE
- 1));
5331 return PhysicalAddress
;
5335 KeRosDumpStackFrames(NULL
, 20);
5336 DPRINT1("MM:MmGetPhysicalAddressFailed base address was %p\n", Address
);
5337 PhysicalAddress
.QuadPart
= 0;
5338 return PhysicalAddress
;