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 PointerPte
->u
.Long
= 0;
356 /* Actual legitimate pages */
362 * The only other ARM3 possibility is a demand zero page, which would
363 * mean freeing some of the paged pool pages that haven't even been
364 * touched yet, as part of a larger allocation.
366 * Right now, we shouldn't expect any page file information in the PTE
368 ASSERT(PointerPte
->u
.Soft
.PageFileHigh
== 0);
370 /* Destroy the PTE */
371 PointerPte
->u
.Long
= 0;
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 PointerPte
->u
.Long
= 0;
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
;
506 PUSHORT UsedPageTableEntries
;
508 /* Get out if this is a fake VAD, RosMm will free the marea pages */
509 if ((Vad
) && (Vad
->u
.VadFlags
.Spare
== 1)) return;
511 /* Grab the process and PTE/PDE for the address being deleted */
512 CurrentProcess
= PsGetCurrentProcess();
513 PointerPde
= MiAddressToPde(Va
);
514 PointerPte
= MiAddressToPte(Va
);
516 /* Check if this is a section VAD or a VM VAD */
517 if (!(Vad
) || (Vad
->u
.VadFlags
.PrivateMemory
) || !(Vad
->FirstPrototypePte
))
519 /* Don't worry about prototypes */
520 PrototypePte
= LastPrototypePte
= NULL
;
524 /* Get the prototype PTE */
525 PrototypePte
= Vad
->FirstPrototypePte
;
526 LastPrototypePte
= Vad
->FirstPrototypePte
+ 1;
529 /* In all cases, we don't support fork() yet */
530 ASSERT(CurrentProcess
->CloneRoot
== NULL
);
532 /* Loop the PTE for each VA */
535 /* First keep going until we find a valid PDE */
536 while (!PointerPde
->u
.Long
)
538 /* There are gaps in the address space */
541 /* Still no valid PDE, try the next 4MB (or whatever) */
544 /* Update the PTE on this new boundary */
545 PointerPte
= MiPteToAddress(PointerPde
);
547 /* Check if all the PDEs are invalid, so there's nothing to free */
548 Va
= (ULONG_PTR
)MiPteToAddress(PointerPte
);
549 if (Va
> EndingAddress
) return;
552 /* Now check if the PDE is mapped in */
553 if (!PointerPde
->u
.Hard
.Valid
)
555 /* It isn't, so map it in */
556 PointerPte
= MiPteToAddress(PointerPde
);
557 MiMakeSystemAddressValid(PointerPte
, CurrentProcess
);
560 /* Now we should have a valid PDE, mapped in, and still have some VA */
561 ASSERT(PointerPde
->u
.Hard
.Valid
== 1);
562 ASSERT(Va
<= EndingAddress
);
563 UsedPageTableEntries
= &MmWorkingSetList
->UsedPageTableEntries
[MiGetPdeOffset(Va
)];
565 /* Check if this is a section VAD with gaps in it */
566 if ((AddressGap
) && (LastPrototypePte
))
568 /* We need to skip to the next correct prototype PTE */
569 PrototypePte
= MI_GET_PROTOTYPE_PTE_FOR_VPN(Vad
, Va
>> PAGE_SHIFT
);
571 /* And we need the subsection to skip to the next last prototype PTE */
572 Subsection
= MiLocateSubsection(Vad
, Va
>> PAGE_SHIFT
);
576 LastPrototypePte
= &Subsection
->SubsectionBase
[Subsection
->PtesInSubsection
];
580 /* No more subsections, we are done with prototype PTEs */
585 /* Lock the PFN Database while we delete the PTEs */
586 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
589 /* Capture the PDE and make sure it exists */
590 TempPte
= *PointerPte
;
593 *UsedPageTableEntries
-= 1;
594 ASSERT((*UsedPageTableEntries
) < PTE_COUNT
);
596 /* Check if the PTE is actually mapped in */
597 if (TempPte
.u
.Long
& 0xFFFFFC01)
599 /* Are we dealing with section VAD? */
600 if ((LastPrototypePte
) && (PrototypePte
> LastPrototypePte
))
602 /* We need to skip to the next correct prototype PTE */
603 PrototypePte
= MI_GET_PROTOTYPE_PTE_FOR_VPN(Vad
, Va
>> PAGE_SHIFT
);
605 /* And we need the subsection to skip to the next last prototype PTE */
606 Subsection
= MiLocateSubsection(Vad
, Va
>> PAGE_SHIFT
);
610 LastPrototypePte
= &Subsection
->SubsectionBase
[Subsection
->PtesInSubsection
];
614 /* No more subsections, we are done with prototype PTEs */
619 /* Check for prototype PTE */
620 if ((TempPte
.u
.Hard
.Valid
== 0) &&
621 (TempPte
.u
.Soft
.Prototype
== 1))
624 PointerPte
->u
.Long
= 0;
628 /* Delete the PTE proper */
629 MiDeletePte(PointerPte
,
637 /* The PTE was never mapped, just nuke it here */
638 PointerPte
->u
.Long
= 0;
642 /* Update the address and PTE for it */
647 /* Making sure the PDE is still valid */
648 ASSERT(PointerPde
->u
.Hard
.Valid
== 1);
650 while ((Va
& (PDE_MAPPED_VA
- 1)) && (Va
<= EndingAddress
));
652 /* The PDE should still be valid at this point */
653 ASSERT(PointerPde
->u
.Hard
.Valid
== 1);
655 if (*UsedPageTableEntries
== 0)
657 if (PointerPde
->u
.Long
!= 0)
659 /* Delete the PTE proper */
660 MiDeletePte(PointerPde
,
661 MiPteToAddress(PointerPde
),
667 /* Release the lock and get out if we're done */
668 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
669 if (Va
> EndingAddress
) return;
671 /* Otherwise, we exited because we hit a new PDE boundary, so start over */
672 PointerPde
= MiAddressToPde(Va
);
678 MiGetExceptionInfo(IN PEXCEPTION_POINTERS ExceptionInfo
,
679 OUT PBOOLEAN HaveBadAddress
,
680 OUT PULONG_PTR BadAddress
)
682 PEXCEPTION_RECORD ExceptionRecord
;
688 *HaveBadAddress
= FALSE
;
691 // Get the exception record
693 ExceptionRecord
= ExceptionInfo
->ExceptionRecord
;
696 // Look at the exception code
698 if ((ExceptionRecord
->ExceptionCode
== STATUS_ACCESS_VIOLATION
) ||
699 (ExceptionRecord
->ExceptionCode
== STATUS_GUARD_PAGE_VIOLATION
) ||
700 (ExceptionRecord
->ExceptionCode
== STATUS_IN_PAGE_ERROR
))
703 // We can tell the address if we have more than one parameter
705 if (ExceptionRecord
->NumberParameters
> 1)
708 // Return the address
710 *HaveBadAddress
= TRUE
;
711 *BadAddress
= ExceptionRecord
->ExceptionInformation
[1];
716 // Continue executing the next handler
718 return EXCEPTION_EXECUTE_HANDLER
;
723 MiDoMappedCopy(IN PEPROCESS SourceProcess
,
724 IN PVOID SourceAddress
,
725 IN PEPROCESS TargetProcess
,
726 OUT PVOID TargetAddress
,
727 IN SIZE_T BufferSize
,
728 IN KPROCESSOR_MODE PreviousMode
,
729 OUT PSIZE_T ReturnSize
)
731 PFN_NUMBER MdlBuffer
[(sizeof(MDL
) / sizeof(PFN_NUMBER
)) + MI_MAPPED_COPY_PAGES
+ 1];
732 PMDL Mdl
= (PMDL
)MdlBuffer
;
733 SIZE_T TotalSize
, CurrentSize
, RemainingSize
;
734 volatile BOOLEAN FailedInProbe
= FALSE
, FailedInMapping
= FALSE
, FailedInMoving
;
735 volatile BOOLEAN PagesLocked
;
736 PVOID CurrentAddress
= SourceAddress
, CurrentTargetAddress
= TargetAddress
;
737 volatile PVOID MdlAddress
;
739 BOOLEAN HaveBadAddress
;
740 ULONG_PTR BadAddress
;
741 NTSTATUS Status
= STATUS_SUCCESS
;
745 // Calculate the maximum amount of data to move
747 TotalSize
= MI_MAPPED_COPY_PAGES
* PAGE_SIZE
;
748 if (BufferSize
<= TotalSize
) TotalSize
= BufferSize
;
749 CurrentSize
= TotalSize
;
750 RemainingSize
= BufferSize
;
753 // Loop as long as there is still data
755 while (RemainingSize
> 0)
758 // Check if this transfer will finish everything off
760 if (RemainingSize
< CurrentSize
) CurrentSize
= RemainingSize
;
763 // Attach to the source address space
765 KeStackAttachProcess(&SourceProcess
->Pcb
, &ApcState
);
768 // Reset state for this pass
772 FailedInMoving
= FALSE
;
773 ASSERT(FailedInProbe
== FALSE
);
776 // Protect user-mode copy
781 // If this is our first time, probe the buffer
783 if ((CurrentAddress
== SourceAddress
) && (PreviousMode
!= KernelMode
))
786 // Catch a failure here
788 FailedInProbe
= TRUE
;
793 ProbeForRead(SourceAddress
, BufferSize
, sizeof(CHAR
));
798 FailedInProbe
= FALSE
;
802 // Initialize and probe and lock the MDL
804 MmInitializeMdl(Mdl
, CurrentAddress
, CurrentSize
);
805 MmProbeAndLockPages(Mdl
, PreviousMode
, IoReadAccess
);
811 MdlAddress
= MmMapLockedPagesSpecifyCache(Mdl
,
820 // Use our SEH handler to pick this up
822 FailedInMapping
= TRUE
;
823 ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES
);
827 // Now let go of the source and grab to the target process
829 KeUnstackDetachProcess(&ApcState
);
830 KeStackAttachProcess(&TargetProcess
->Pcb
, &ApcState
);
833 // Check if this is our first time through
835 if ((CurrentAddress
== SourceAddress
) && (PreviousMode
!= KernelMode
))
838 // Catch a failure here
840 FailedInProbe
= TRUE
;
845 ProbeForWrite(TargetAddress
, BufferSize
, sizeof(CHAR
));
850 FailedInProbe
= FALSE
;
854 // Now do the actual move
856 FailedInMoving
= TRUE
;
857 RtlCopyMemory(CurrentTargetAddress
, MdlAddress
, CurrentSize
);
859 _SEH2_EXCEPT(MiGetExceptionInfo(_SEH2_GetExceptionInformation(),
864 // Detach from whoever we may be attached to
866 KeUnstackDetachProcess(&ApcState
);
869 // Check if we had mapped the pages
871 if (MdlAddress
) MmUnmapLockedPages(MdlAddress
, Mdl
);
874 // Check if we had locked the pages
876 if (PagesLocked
) MmUnlockPages(Mdl
);
879 // Check if we hit working set quota
881 if (_SEH2_GetExceptionCode() == STATUS_WORKING_SET_QUOTA
)
886 _SEH2_YIELD(return STATUS_WORKING_SET_QUOTA
);
890 // Check if we failed during the probe or mapping
892 if ((FailedInProbe
) || (FailedInMapping
))
897 Status
= _SEH2_GetExceptionCode();
898 _SEH2_YIELD(return Status
);
902 // Otherwise, we failed probably during the move
904 *ReturnSize
= BufferSize
- RemainingSize
;
908 // Check if we know exactly where we stopped copying
913 // Return the exact number of bytes copied
915 *ReturnSize
= BadAddress
- (ULONG_PTR
)SourceAddress
;
920 // Return partial copy
922 Status
= STATUS_PARTIAL_COPY
;
927 // Check for SEH status
929 if (Status
!= STATUS_SUCCESS
) return Status
;
932 // Detach from target
934 KeUnstackDetachProcess(&ApcState
);
939 MmUnmapLockedPages(MdlAddress
, Mdl
);
943 // Update location and size
945 RemainingSize
-= CurrentSize
;
946 CurrentAddress
= (PVOID
)((ULONG_PTR
)CurrentAddress
+ CurrentSize
);
947 CurrentTargetAddress
= (PVOID
)((ULONG_PTR
)CurrentTargetAddress
+ CurrentSize
);
953 *ReturnSize
= BufferSize
;
954 return STATUS_SUCCESS
;
959 MiDoPoolCopy(IN PEPROCESS SourceProcess
,
960 IN PVOID SourceAddress
,
961 IN PEPROCESS TargetProcess
,
962 OUT PVOID TargetAddress
,
963 IN SIZE_T BufferSize
,
964 IN KPROCESSOR_MODE PreviousMode
,
965 OUT PSIZE_T ReturnSize
)
967 UCHAR StackBuffer
[MI_POOL_COPY_BYTES
];
968 SIZE_T TotalSize
, CurrentSize
, RemainingSize
;
969 volatile BOOLEAN FailedInProbe
= FALSE
, FailedInMoving
, HavePoolAddress
= FALSE
;
970 PVOID CurrentAddress
= SourceAddress
, CurrentTargetAddress
= TargetAddress
;
973 BOOLEAN HaveBadAddress
;
974 ULONG_PTR BadAddress
;
975 NTSTATUS Status
= STATUS_SUCCESS
;
979 // Calculate the maximum amount of data to move
981 TotalSize
= MI_MAX_TRANSFER_SIZE
;
982 if (BufferSize
<= MI_MAX_TRANSFER_SIZE
) TotalSize
= BufferSize
;
983 CurrentSize
= TotalSize
;
984 RemainingSize
= BufferSize
;
987 // Check if we can use the stack
989 if (BufferSize
<= MI_POOL_COPY_BYTES
)
994 PoolAddress
= (PVOID
)StackBuffer
;
1001 PoolAddress
= ExAllocatePoolWithTag(NonPagedPool
, TotalSize
, 'VmRw');
1002 if (!PoolAddress
) ASSERT(FALSE
);
1003 HavePoolAddress
= TRUE
;
1007 // Loop as long as there is still data
1009 while (RemainingSize
> 0)
1012 // Check if this transfer will finish everything off
1014 if (RemainingSize
< CurrentSize
) CurrentSize
= RemainingSize
;
1017 // Attach to the source address space
1019 KeStackAttachProcess(&SourceProcess
->Pcb
, &ApcState
);
1022 // Reset state for this pass
1024 FailedInMoving
= FALSE
;
1025 ASSERT(FailedInProbe
== FALSE
);
1028 // Protect user-mode copy
1033 // If this is our first time, probe the buffer
1035 if ((CurrentAddress
== SourceAddress
) && (PreviousMode
!= KernelMode
))
1038 // Catch a failure here
1040 FailedInProbe
= TRUE
;
1045 ProbeForRead(SourceAddress
, BufferSize
, sizeof(CHAR
));
1050 FailedInProbe
= FALSE
;
1056 RtlCopyMemory(PoolAddress
, CurrentAddress
, CurrentSize
);
1059 // Now let go of the source and grab to the target process
1061 KeUnstackDetachProcess(&ApcState
);
1062 KeStackAttachProcess(&TargetProcess
->Pcb
, &ApcState
);
1065 // Check if this is our first time through
1067 if ((CurrentAddress
== SourceAddress
) && (PreviousMode
!= KernelMode
))
1070 // Catch a failure here
1072 FailedInProbe
= TRUE
;
1077 ProbeForWrite(TargetAddress
, BufferSize
, sizeof(CHAR
));
1082 FailedInProbe
= FALSE
;
1086 // Now do the actual move
1088 FailedInMoving
= TRUE
;
1089 RtlCopyMemory(CurrentTargetAddress
, PoolAddress
, CurrentSize
);
1091 _SEH2_EXCEPT(MiGetExceptionInfo(_SEH2_GetExceptionInformation(),
1096 // Detach from whoever we may be attached to
1098 KeUnstackDetachProcess(&ApcState
);
1101 // Check if we had allocated pool
1103 if (HavePoolAddress
) ExFreePoolWithTag(PoolAddress
, 'VmRw');
1106 // Check if we failed during the probe
1113 Status
= _SEH2_GetExceptionCode();
1114 _SEH2_YIELD(return Status
);
1118 // Otherwise, we failed, probably during the move
1120 *ReturnSize
= BufferSize
- RemainingSize
;
1124 // Check if we know exactly where we stopped copying
1129 // Return the exact number of bytes copied
1131 *ReturnSize
= BadAddress
- (ULONG_PTR
)SourceAddress
;
1136 // Return partial copy
1138 Status
= STATUS_PARTIAL_COPY
;
1143 // Check for SEH status
1145 if (Status
!= STATUS_SUCCESS
) return Status
;
1148 // Detach from target
1150 KeUnstackDetachProcess(&ApcState
);
1153 // Update location and size
1155 RemainingSize
-= CurrentSize
;
1156 CurrentAddress
= (PVOID
)((ULONG_PTR
)CurrentAddress
+ CurrentSize
);
1157 CurrentTargetAddress
= (PVOID
)((ULONG_PTR
)CurrentTargetAddress
+
1162 // Check if we had allocated pool
1164 if (HavePoolAddress
) ExFreePoolWithTag(PoolAddress
, 'VmRw');
1169 *ReturnSize
= BufferSize
;
1170 return STATUS_SUCCESS
;
1175 MmCopyVirtualMemory(IN PEPROCESS SourceProcess
,
1176 IN PVOID SourceAddress
,
1177 IN PEPROCESS TargetProcess
,
1178 OUT PVOID TargetAddress
,
1179 IN SIZE_T BufferSize
,
1180 IN KPROCESSOR_MODE PreviousMode
,
1181 OUT PSIZE_T ReturnSize
)
1184 PEPROCESS Process
= SourceProcess
;
1187 // Don't accept zero-sized buffers
1189 if (!BufferSize
) return STATUS_SUCCESS
;
1192 // If we are copying from ourselves, lock the target instead
1194 if (SourceProcess
== PsGetCurrentProcess()) Process
= TargetProcess
;
1197 // Acquire rundown protection
1199 if (!ExAcquireRundownProtection(&Process
->RundownProtect
))
1204 return STATUS_PROCESS_IS_TERMINATING
;
1208 // See if we should use the pool copy
1210 if (BufferSize
> MI_POOL_COPY_BYTES
)
1215 Status
= MiDoMappedCopy(SourceProcess
,
1228 Status
= MiDoPoolCopy(SourceProcess
,
1240 ExReleaseRundownProtection(&Process
->RundownProtect
);
1246 MmFlushVirtualMemory(IN PEPROCESS Process
,
1247 IN OUT PVOID
*BaseAddress
,
1248 IN OUT PSIZE_T RegionSize
,
1249 OUT PIO_STATUS_BLOCK IoStatusBlock
)
1257 return STATUS_SUCCESS
;
1262 MiGetPageProtection(IN PMMPTE PointerPte
)
1268 /* Copy this PTE's contents */
1269 TempPte
= *PointerPte
;
1271 /* Assure it's not totally zero */
1272 ASSERT(TempPte
.u
.Long
);
1274 /* Check for a special prototype format */
1275 if (TempPte
.u
.Soft
.Valid
== 0 &&
1276 TempPte
.u
.Soft
.Prototype
== 1)
1278 /* Unsupported now */
1283 /* In the easy case of transition or demand zero PTE just return its protection */
1284 if (!TempPte
.u
.Hard
.Valid
) return MmProtectToValue
[TempPte
.u
.Soft
.Protection
];
1286 /* If we get here, the PTE is valid, so look up the page in PFN database */
1287 Pfn
= MiGetPfnEntry(TempPte
.u
.Hard
.PageFrameNumber
);
1288 if (!Pfn
->u3
.e1
.PrototypePte
)
1290 /* Return protection of the original pte */
1291 ASSERT(Pfn
->u4
.AweAllocation
== 0);
1292 return MmProtectToValue
[Pfn
->OriginalPte
.u
.Soft
.Protection
];
1295 /* This is software PTE */
1296 DPRINT1("Prototype PTE: %lx %p\n", TempPte
.u
.Hard
.PageFrameNumber
, Pfn
);
1297 DPRINT1("VA: %p\n", MiPteToAddress(&TempPte
));
1298 DPRINT1("Mask: %lx\n", TempPte
.u
.Soft
.Protection
);
1299 DPRINT1("Mask2: %lx\n", Pfn
->OriginalPte
.u
.Soft
.Protection
);
1300 return MmProtectToValue
[TempPte
.u
.Soft
.Protection
];
1305 MiQueryAddressState(IN PVOID Va
,
1307 IN PEPROCESS TargetProcess
,
1308 OUT PULONG ReturnedProtect
,
1312 PMMPTE PointerPte
, ProtoPte
;
1314 MMPTE TempPte
, TempProtoPte
;
1315 BOOLEAN DemandZeroPte
= TRUE
, ValidPte
= FALSE
;
1316 ULONG State
= MEM_RESERVE
, Protect
= 0;
1317 ASSERT((Vad
->StartingVpn
<= ((ULONG_PTR
)Va
>> PAGE_SHIFT
)) &&
1318 (Vad
->EndingVpn
>= ((ULONG_PTR
)Va
>> PAGE_SHIFT
)));
1320 /* Only normal VADs supported */
1321 ASSERT(Vad
->u
.VadFlags
.VadType
== VadNone
);
1323 /* Get the PDE and PTE for the address */
1324 PointerPde
= MiAddressToPde(Va
);
1325 PointerPte
= MiAddressToPte(Va
);
1327 /* Return the next range */
1328 *NextVa
= (PVOID
)((ULONG_PTR
)Va
+ PAGE_SIZE
);
1330 /* Is the PDE demand-zero? */
1331 if (PointerPde
->u
.Long
!= 0)
1333 /* It is not. Is it valid? */
1334 if (PointerPde
->u
.Hard
.Valid
== 0)
1336 /* Is isn't, fault it in */
1337 PointerPte
= MiPteToAddress(PointerPde
);
1338 MiMakeSystemAddressValid(PointerPte
, TargetProcess
);
1344 /* It is, skip it and move to the next PDE */
1345 *NextVa
= MiPdeToAddress(PointerPde
+ 1);
1348 /* Is it safe to try reading the PTE? */
1351 /* FIXME: watch out for large pages */
1352 ASSERT(PointerPde
->u
.Hard
.LargePage
== FALSE
);
1354 /* Capture the PTE */
1355 TempPte
= *PointerPte
;
1356 if (TempPte
.u
.Long
!= 0)
1358 /* The PTE is valid, so it's not zeroed out */
1359 DemandZeroPte
= FALSE
;
1361 /* Is it a decommited, invalid, or faulted PTE? */
1362 if ((TempPte
.u
.Soft
.Protection
== MM_DECOMMIT
) &&
1363 (TempPte
.u
.Hard
.Valid
== 0) &&
1364 ((TempPte
.u
.Soft
.Prototype
== 0) ||
1365 (TempPte
.u
.Soft
.PageFileHigh
== MI_PTE_LOOKUP_NEEDED
)))
1367 /* Otherwise our defaults should hold */
1368 ASSERT(Protect
== 0);
1369 ASSERT(State
== MEM_RESERVE
);
1373 /* This means it's committed */
1376 /* We don't support these */
1377 ASSERT(Vad
->u
.VadFlags
.VadType
!= VadDevicePhysicalMemory
);
1378 ASSERT(Vad
->u
.VadFlags
.VadType
!= VadRotatePhysical
);
1379 ASSERT(Vad
->u
.VadFlags
.VadType
!= VadAwe
);
1381 /* Get protection state of this page */
1382 Protect
= MiGetPageProtection(PointerPte
);
1384 /* Check if this is an image-backed VAD */
1385 if ((TempPte
.u
.Soft
.Valid
== 0) &&
1386 (TempPte
.u
.Soft
.Prototype
== 1) &&
1387 (Vad
->u
.VadFlags
.PrivateMemory
== 0) &&
1390 DPRINT1("Not supported\n");
1397 /* Check if this was a demand-zero PTE, since we need to find the state */
1400 /* Not yet handled */
1401 ASSERT(Vad
->u
.VadFlags
.VadType
!= VadDevicePhysicalMemory
);
1402 ASSERT(Vad
->u
.VadFlags
.VadType
!= VadAwe
);
1404 /* Check if this is private commited memory, or an section-backed VAD */
1405 if ((Vad
->u
.VadFlags
.PrivateMemory
== 0) && (Vad
->ControlArea
))
1407 /* Tell caller about the next range */
1408 *NextVa
= (PVOID
)((ULONG_PTR
)Va
+ PAGE_SIZE
);
1410 /* Get the prototype PTE for this VAD */
1411 ProtoPte
= MI_GET_PROTOTYPE_PTE_FOR_VPN(Vad
,
1412 (ULONG_PTR
)Va
>> PAGE_SHIFT
);
1415 /* We should unlock the working set, but it's not being held! */
1417 /* Is the prototype PTE actually valid (committed)? */
1418 TempProtoPte
= *ProtoPte
;
1419 if (TempProtoPte
.u
.Long
)
1421 /* Unless this is a memory-mapped file, handle it like private VAD */
1423 ASSERT(Vad
->u
.VadFlags
.VadType
!= VadImageMap
);
1424 Protect
= MmProtectToValue
[Vad
->u
.VadFlags
.Protection
];
1427 /* We should re-lock the working set */
1430 else if (Vad
->u
.VadFlags
.MemCommit
)
1432 /* This is committed memory */
1435 /* Convert the protection */
1436 Protect
= MmProtectToValue
[Vad
->u
.VadFlags
.Protection
];
1440 /* Return the protection code */
1441 *ReturnedProtect
= Protect
;
1447 MiQueryMemoryBasicInformation(IN HANDLE ProcessHandle
,
1448 IN PVOID BaseAddress
,
1449 OUT PVOID MemoryInformation
,
1450 IN SIZE_T MemoryInformationLength
,
1451 OUT PSIZE_T ReturnLength
)
1453 PEPROCESS TargetProcess
;
1454 NTSTATUS Status
= STATUS_SUCCESS
;
1456 PVOID Address
, NextAddress
;
1457 BOOLEAN Found
= FALSE
;
1458 ULONG NewProtect
, NewState
;
1460 MEMORY_BASIC_INFORMATION MemoryInfo
;
1461 KAPC_STATE ApcState
;
1462 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
1463 PMEMORY_AREA MemoryArea
;
1464 SIZE_T ResultLength
;
1466 /* Check for illegal addresses in user-space, or the shared memory area */
1467 if ((BaseAddress
> MM_HIGHEST_VAD_ADDRESS
) ||
1468 (PAGE_ALIGN(BaseAddress
) == (PVOID
)MM_SHARED_USER_DATA_VA
))
1470 Address
= PAGE_ALIGN(BaseAddress
);
1472 /* Make up an info structure describing this range */
1473 MemoryInfo
.BaseAddress
= Address
;
1474 MemoryInfo
.AllocationProtect
= PAGE_READONLY
;
1475 MemoryInfo
.Type
= MEM_PRIVATE
;
1477 /* Special case for shared data */
1478 if (Address
== (PVOID
)MM_SHARED_USER_DATA_VA
)
1480 MemoryInfo
.AllocationBase
= (PVOID
)MM_SHARED_USER_DATA_VA
;
1481 MemoryInfo
.State
= MEM_COMMIT
;
1482 MemoryInfo
.Protect
= PAGE_READONLY
;
1483 MemoryInfo
.RegionSize
= PAGE_SIZE
;
1487 MemoryInfo
.AllocationBase
= (PCHAR
)MM_HIGHEST_VAD_ADDRESS
+ 1;
1488 MemoryInfo
.State
= MEM_RESERVE
;
1489 MemoryInfo
.Protect
= PAGE_NOACCESS
;
1490 MemoryInfo
.RegionSize
= (ULONG_PTR
)MM_HIGHEST_USER_ADDRESS
+ 1 - (ULONG_PTR
)Address
;
1493 /* Return the data, NtQueryInformation already probed it*/
1494 if (PreviousMode
!= KernelMode
)
1498 *(PMEMORY_BASIC_INFORMATION
)MemoryInformation
= MemoryInfo
;
1499 if (ReturnLength
) *ReturnLength
= sizeof(MEMORY_BASIC_INFORMATION
);
1501 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1503 Status
= _SEH2_GetExceptionCode();
1509 *(PMEMORY_BASIC_INFORMATION
)MemoryInformation
= MemoryInfo
;
1510 if (ReturnLength
) *ReturnLength
= sizeof(MEMORY_BASIC_INFORMATION
);
1516 /* Check if this is for a local or remote process */
1517 if (ProcessHandle
== NtCurrentProcess())
1519 TargetProcess
= PsGetCurrentProcess();
1523 /* Reference the target process */
1524 Status
= ObReferenceObjectByHandle(ProcessHandle
,
1525 PROCESS_QUERY_INFORMATION
,
1527 ExGetPreviousMode(),
1528 (PVOID
*)&TargetProcess
,
1530 if (!NT_SUCCESS(Status
)) return Status
;
1532 /* Attach to it now */
1533 KeStackAttachProcess(&TargetProcess
->Pcb
, &ApcState
);
1536 /* Lock the address space and make sure the process isn't already dead */
1537 MmLockAddressSpace(&TargetProcess
->Vm
);
1538 if (TargetProcess
->VmDeleted
)
1540 /* Unlock the address space of the process */
1541 MmUnlockAddressSpace(&TargetProcess
->Vm
);
1543 /* Check if we were attached */
1544 if (ProcessHandle
!= NtCurrentProcess())
1546 /* Detach and dereference the process */
1547 KeUnstackDetachProcess(&ApcState
);
1548 ObDereferenceObject(TargetProcess
);
1552 DPRINT1("Process is dying\n");
1553 return STATUS_PROCESS_IS_TERMINATING
;
1557 ASSERT(TargetProcess
->VadRoot
.NumberGenericTableElements
);
1558 if (TargetProcess
->VadRoot
.NumberGenericTableElements
)
1560 /* Scan on the right */
1561 Vad
= (PMMVAD
)TargetProcess
->VadRoot
.BalancedRoot
.RightChild
;
1562 BaseVpn
= (ULONG_PTR
)BaseAddress
>> PAGE_SHIFT
;
1565 /* Check if this VAD covers the allocation range */
1566 if ((BaseVpn
>= Vad
->StartingVpn
) &&
1567 (BaseVpn
<= Vad
->EndingVpn
))
1574 /* Check if this VAD is too high */
1575 if (BaseVpn
< Vad
->StartingVpn
)
1577 /* Stop if there is no left child */
1578 if (!Vad
->LeftChild
) break;
1580 /* Search on the left next */
1581 Vad
= Vad
->LeftChild
;
1585 /* Then this VAD is too low, keep searching on the right */
1586 ASSERT(BaseVpn
> Vad
->EndingVpn
);
1588 /* Stop if there is no right child */
1589 if (!Vad
->RightChild
) break;
1591 /* Search on the right next */
1592 Vad
= Vad
->RightChild
;
1597 /* Was a VAD found? */
1600 Address
= PAGE_ALIGN(BaseAddress
);
1602 /* Calculate region size */
1605 if (Vad
->StartingVpn
>= BaseVpn
)
1607 /* Region size is the free space till the start of that VAD */
1608 MemoryInfo
.RegionSize
= (ULONG_PTR
)(Vad
->StartingVpn
<< PAGE_SHIFT
) - (ULONG_PTR
)Address
;
1612 /* Get the next VAD */
1613 Vad
= (PMMVAD
)MiGetNextNode((PMMADDRESS_NODE
)Vad
);
1616 /* Region size is the free space till the start of that VAD */
1617 MemoryInfo
.RegionSize
= (ULONG_PTR
)(Vad
->StartingVpn
<< PAGE_SHIFT
) - (ULONG_PTR
)Address
;
1621 /* Maximum possible region size with that base address */
1622 MemoryInfo
.RegionSize
= (PCHAR
)MM_HIGHEST_VAD_ADDRESS
+ 1 - (PCHAR
)Address
;
1628 /* Maximum possible region size with that base address */
1629 MemoryInfo
.RegionSize
= (PCHAR
)MM_HIGHEST_VAD_ADDRESS
+ 1 - (PCHAR
)Address
;
1632 /* Unlock the address space of the process */
1633 MmUnlockAddressSpace(&TargetProcess
->Vm
);
1635 /* Check if we were attached */
1636 if (ProcessHandle
!= NtCurrentProcess())
1638 /* Detach and derefernece the process */
1639 KeUnstackDetachProcess(&ApcState
);
1640 ObDereferenceObject(TargetProcess
);
1643 /* Build the rest of the initial information block */
1644 MemoryInfo
.BaseAddress
= Address
;
1645 MemoryInfo
.AllocationBase
= NULL
;
1646 MemoryInfo
.AllocationProtect
= 0;
1647 MemoryInfo
.State
= MEM_FREE
;
1648 MemoryInfo
.Protect
= PAGE_NOACCESS
;
1649 MemoryInfo
.Type
= 0;
1651 /* Return the data, NtQueryInformation already probed it*/
1652 if (PreviousMode
!= KernelMode
)
1656 *(PMEMORY_BASIC_INFORMATION
)MemoryInformation
= MemoryInfo
;
1657 if (ReturnLength
) *ReturnLength
= sizeof(MEMORY_BASIC_INFORMATION
);
1659 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1661 Status
= _SEH2_GetExceptionCode();
1667 *(PMEMORY_BASIC_INFORMATION
)MemoryInformation
= MemoryInfo
;
1668 if (ReturnLength
) *ReturnLength
= sizeof(MEMORY_BASIC_INFORMATION
);
1674 /* Set the correct memory type based on what kind of VAD this is */
1675 if ((Vad
->u
.VadFlags
.PrivateMemory
) ||
1676 (Vad
->u
.VadFlags
.VadType
== VadRotatePhysical
))
1678 MemoryInfo
.Type
= MEM_PRIVATE
;
1680 else if (Vad
->u
.VadFlags
.VadType
== VadImageMap
)
1682 MemoryInfo
.Type
= MEM_IMAGE
;
1686 MemoryInfo
.Type
= MEM_MAPPED
;
1689 /* Find the memory area the specified address belongs to */
1690 MemoryArea
= MmLocateMemoryAreaByAddress(&TargetProcess
->Vm
, BaseAddress
);
1691 ASSERT(MemoryArea
!= NULL
);
1693 /* Determine information dependent on the memory area type */
1694 if (MemoryArea
->Type
== MEMORY_AREA_SECTION_VIEW
)
1696 Status
= MmQuerySectionView(MemoryArea
, BaseAddress
, &MemoryInfo
, &ResultLength
);
1697 ASSERT(NT_SUCCESS(Status
));
1701 /* Build the initial information block */
1702 Address
= PAGE_ALIGN(BaseAddress
);
1703 MemoryInfo
.BaseAddress
= Address
;
1704 MemoryInfo
.AllocationBase
= (PVOID
)(Vad
->StartingVpn
<< PAGE_SHIFT
);
1705 MemoryInfo
.AllocationProtect
= MmProtectToValue
[Vad
->u
.VadFlags
.Protection
];
1706 MemoryInfo
.Type
= MEM_PRIVATE
;
1708 /* Find the largest chunk of memory which has the same state and protection mask */
1709 MemoryInfo
.State
= MiQueryAddressState(Address
,
1712 &MemoryInfo
.Protect
,
1714 Address
= NextAddress
;
1715 while (((ULONG_PTR
)Address
>> PAGE_SHIFT
) <= Vad
->EndingVpn
)
1717 /* Keep going unless the state or protection mask changed */
1718 NewState
= MiQueryAddressState(Address
, Vad
, TargetProcess
, &NewProtect
, &NextAddress
);
1719 if ((NewState
!= MemoryInfo
.State
) || (NewProtect
!= MemoryInfo
.Protect
)) break;
1720 Address
= NextAddress
;
1723 /* Now that we know the last VA address, calculate the region size */
1724 MemoryInfo
.RegionSize
= ((ULONG_PTR
)Address
- (ULONG_PTR
)MemoryInfo
.BaseAddress
);
1727 /* Unlock the address space of the process */
1728 MmUnlockAddressSpace(&TargetProcess
->Vm
);
1730 /* Check if we were attached */
1731 if (ProcessHandle
!= NtCurrentProcess())
1733 /* Detach and derefernece the process */
1734 KeUnstackDetachProcess(&ApcState
);
1735 ObDereferenceObject(TargetProcess
);
1738 /* Return the data, NtQueryInformation already probed it*/
1739 if (PreviousMode
!= KernelMode
)
1743 *(PMEMORY_BASIC_INFORMATION
)MemoryInformation
= MemoryInfo
;
1744 if (ReturnLength
) *ReturnLength
= sizeof(MEMORY_BASIC_INFORMATION
);
1746 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
1748 Status
= _SEH2_GetExceptionCode();
1754 *(PMEMORY_BASIC_INFORMATION
)MemoryInformation
= MemoryInfo
;
1755 if (ReturnLength
) *ReturnLength
= sizeof(MEMORY_BASIC_INFORMATION
);
1759 DPRINT("Base: %p AllocBase: %p AllocProtect: %lx Protect: %lx "
1760 "State: %lx Type: %lx Size: %lx\n",
1761 MemoryInfo
.BaseAddress
, MemoryInfo
.AllocationBase
,
1762 MemoryInfo
.AllocationProtect
, MemoryInfo
.Protect
,
1763 MemoryInfo
.State
, MemoryInfo
.Type
, MemoryInfo
.RegionSize
);
1770 MiIsEntireRangeCommitted(IN ULONG_PTR StartingAddress
,
1771 IN ULONG_PTR EndingAddress
,
1773 IN PEPROCESS Process
)
1775 PMMPTE PointerPte
, LastPte
, PointerPde
;
1776 BOOLEAN OnBoundary
= TRUE
;
1779 /* Get the PDE and PTE addresses */
1780 PointerPde
= MiAddressToPde(StartingAddress
);
1781 PointerPte
= MiAddressToPte(StartingAddress
);
1782 LastPte
= MiAddressToPte(EndingAddress
);
1784 /* Loop all the PTEs */
1785 while (PointerPte
<= LastPte
)
1787 /* Check if we've hit an new PDE boundary */
1790 /* Is this PDE demand zero? */
1791 PointerPde
= MiAddressToPte(PointerPte
);
1792 if (PointerPde
->u
.Long
!= 0)
1794 /* It isn't -- is it valid? */
1795 if (PointerPde
->u
.Hard
.Valid
== 0)
1797 /* Nope, fault it in */
1798 PointerPte
= MiPteToAddress(PointerPde
);
1799 MiMakeSystemAddressValid(PointerPte
, Process
);
1804 /* The PTE was already valid, so move to the next one */
1806 PointerPte
= MiPteToAddress(PointerPde
);
1808 /* Is the entire VAD committed? If not, fail */
1809 if (!Vad
->u
.VadFlags
.MemCommit
) return FALSE
;
1811 /* Everything is committed so far past the range, return true */
1812 if (PointerPte
> LastPte
) return TRUE
;
1816 /* Is the PTE demand zero? */
1817 if (PointerPte
->u
.Long
== 0)
1819 /* Is the entire VAD committed? If not, fail */
1820 if (!Vad
->u
.VadFlags
.MemCommit
) return FALSE
;
1824 /* It isn't -- is it a decommited, invalid, or faulted PTE? */
1825 if ((PointerPte
->u
.Soft
.Protection
== MM_DECOMMIT
) &&
1826 (PointerPte
->u
.Hard
.Valid
== 0) &&
1827 ((PointerPte
->u
.Soft
.Prototype
== 0) ||
1828 (PointerPte
->u
.Soft
.PageFileHigh
== MI_PTE_LOOKUP_NEEDED
)))
1830 /* Then part of the range is decommitted, so fail */
1835 /* Move to the next PTE */
1837 OnBoundary
= MiIsPteOnPdeBoundary(PointerPte
);
1840 /* All PTEs seem valid, and no VAD checks failed, the range is okay */
1846 MiRosProtectVirtualMemory(IN PEPROCESS Process
,
1847 IN OUT PVOID
*BaseAddress
,
1848 IN OUT PSIZE_T NumberOfBytesToProtect
,
1849 IN ULONG NewAccessProtection
,
1850 OUT PULONG OldAccessProtection OPTIONAL
)
1852 PMEMORY_AREA MemoryArea
;
1853 PMMSUPPORT AddressSpace
;
1854 ULONG OldAccessProtection_
;
1857 *NumberOfBytesToProtect
= PAGE_ROUND_UP((ULONG_PTR
)(*BaseAddress
) + (*NumberOfBytesToProtect
)) - PAGE_ROUND_DOWN(*BaseAddress
);
1858 *BaseAddress
= (PVOID
)PAGE_ROUND_DOWN(*BaseAddress
);
1860 AddressSpace
= &Process
->Vm
;
1861 MmLockAddressSpace(AddressSpace
);
1862 MemoryArea
= MmLocateMemoryAreaByAddress(AddressSpace
, *BaseAddress
);
1863 if (MemoryArea
== NULL
|| MemoryArea
->DeleteInProgress
)
1865 MmUnlockAddressSpace(AddressSpace
);
1866 return STATUS_UNSUCCESSFUL
;
1869 if (OldAccessProtection
== NULL
) OldAccessProtection
= &OldAccessProtection_
;
1871 ASSERT(MemoryArea
->Type
== MEMORY_AREA_SECTION_VIEW
);
1872 Status
= MmProtectSectionView(AddressSpace
,
1875 *NumberOfBytesToProtect
,
1876 NewAccessProtection
,
1877 OldAccessProtection
);
1879 MmUnlockAddressSpace(AddressSpace
);
1886 MiProtectVirtualMemory(IN PEPROCESS Process
,
1887 IN OUT PVOID
*BaseAddress
,
1888 IN OUT PSIZE_T NumberOfBytesToProtect
,
1889 IN ULONG NewAccessProtection
,
1890 OUT PULONG OldAccessProtection OPTIONAL
)
1892 PMEMORY_AREA MemoryArea
;
1894 PMMSUPPORT AddressSpace
;
1895 ULONG_PTR StartingAddress
, EndingAddress
;
1896 PMMPTE PointerPde
, PointerPte
, LastPte
;
1899 ULONG ProtectionMask
, OldProtect
;
1901 NTSTATUS Status
= STATUS_SUCCESS
;
1902 PETHREAD Thread
= PsGetCurrentThread();
1904 /* Calculate base address for the VAD */
1905 StartingAddress
= (ULONG_PTR
)PAGE_ALIGN((*BaseAddress
));
1906 EndingAddress
= (((ULONG_PTR
)*BaseAddress
+ *NumberOfBytesToProtect
- 1) | (PAGE_SIZE
- 1));
1908 /* Calculate the protection mask and make sure it's valid */
1909 ProtectionMask
= MiMakeProtectionMask(NewAccessProtection
);
1910 if (ProtectionMask
== MM_INVALID_PROTECTION
)
1912 DPRINT1("Invalid protection mask\n");
1913 return STATUS_INVALID_PAGE_PROTECTION
;
1916 /* Check for ROS specific memory area */
1917 MemoryArea
= MmLocateMemoryAreaByAddress(&Process
->Vm
, *BaseAddress
);
1918 if ((MemoryArea
) && (MemoryArea
->Type
== MEMORY_AREA_SECTION_VIEW
))
1921 return MiRosProtectVirtualMemory(Process
,
1923 NumberOfBytesToProtect
,
1924 NewAccessProtection
,
1925 OldAccessProtection
);
1928 /* Lock the address space and make sure the process isn't already dead */
1929 AddressSpace
= MmGetCurrentAddressSpace();
1930 MmLockAddressSpace(AddressSpace
);
1931 if (Process
->VmDeleted
)
1933 DPRINT1("Process is dying\n");
1934 Status
= STATUS_PROCESS_IS_TERMINATING
;
1938 /* Get the VAD for this address range, and make sure it exists */
1939 Vad
= (PMMVAD
)MiCheckForConflictingNode(StartingAddress
>> PAGE_SHIFT
,
1940 EndingAddress
>> PAGE_SHIFT
,
1944 DPRINT("Could not find a VAD for this allocation\n");
1945 Status
= STATUS_CONFLICTING_ADDRESSES
;
1949 /* Make sure the address is within this VAD's boundaries */
1950 if ((((ULONG_PTR
)StartingAddress
>> PAGE_SHIFT
) < Vad
->StartingVpn
) ||
1951 (((ULONG_PTR
)EndingAddress
>> PAGE_SHIFT
) > Vad
->EndingVpn
))
1953 Status
= STATUS_CONFLICTING_ADDRESSES
;
1957 /* These kinds of VADs are not supported atm */
1958 if ((Vad
->u
.VadFlags
.VadType
== VadAwe
) ||
1959 (Vad
->u
.VadFlags
.VadType
== VadDevicePhysicalMemory
) ||
1960 (Vad
->u
.VadFlags
.VadType
== VadLargePages
))
1962 DPRINT1("Illegal VAD for attempting to set protection\n");
1963 Status
= STATUS_CONFLICTING_ADDRESSES
;
1967 /* Check for a VAD whose protection can't be changed */
1968 if (Vad
->u
.VadFlags
.NoChange
== 1)
1970 DPRINT1("Trying to change protection of a NoChange VAD\n");
1971 Status
= STATUS_INVALID_PAGE_PROTECTION
;
1975 /* Is this section, or private memory? */
1976 if (Vad
->u
.VadFlags
.PrivateMemory
== 0)
1978 /* Not yet supported */
1979 if (Vad
->u
.VadFlags
.VadType
== VadLargePageSection
)
1981 DPRINT1("Illegal VAD for attempting to set protection\n");
1982 Status
= STATUS_CONFLICTING_ADDRESSES
;
1986 /* Rotate VADs are not yet supported */
1987 if (Vad
->u
.VadFlags
.VadType
== VadRotatePhysical
)
1989 DPRINT1("Illegal VAD for attempting to set protection\n");
1990 Status
= STATUS_CONFLICTING_ADDRESSES
;
1994 /* Not valid on section files */
1995 if (NewAccessProtection
& (PAGE_NOCACHE
| PAGE_WRITECOMBINE
))
1998 DPRINT1("Invalid protection flags for section\n");
1999 Status
= STATUS_INVALID_PARAMETER_4
;
2003 /* Check if data or page file mapping protection PTE is compatible */
2004 if (!Vad
->ControlArea
->u
.Flags
.Image
)
2007 DPRINT1("Fixme: Not checking for valid protection\n");
2010 /* This is a section, and this is not yet supported */
2011 DPRINT1("Section protection not yet supported\n");
2016 /* Private memory, check protection flags */
2017 if ((NewAccessProtection
& PAGE_WRITECOPY
) ||
2018 (NewAccessProtection
& PAGE_EXECUTE_WRITECOPY
))
2020 DPRINT1("Invalid protection flags for private memory\n");
2021 Status
= STATUS_INVALID_PARAMETER_4
;
2025 /* Lock the working set */
2026 MiLockProcessWorkingSetUnsafe(Process
, Thread
);
2028 /* Check if all pages in this range are committed */
2029 Committed
= MiIsEntireRangeCommitted(StartingAddress
,
2036 DPRINT1("The entire range is not committed\n");
2037 Status
= STATUS_NOT_COMMITTED
;
2038 MiUnlockProcessWorkingSetUnsafe(Process
, Thread
);
2042 /* Compute starting and ending PTE and PDE addresses */
2043 PointerPde
= MiAddressToPde(StartingAddress
);
2044 PointerPte
= MiAddressToPte(StartingAddress
);
2045 LastPte
= MiAddressToPte(EndingAddress
);
2047 /* Make this PDE valid */
2048 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
2050 /* Save protection of the first page */
2051 if (PointerPte
->u
.Long
!= 0)
2053 /* Capture the page protection and make the PDE valid */
2054 OldProtect
= MiGetPageProtection(PointerPte
);
2055 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
2059 /* Grab the old protection from the VAD itself */
2060 OldProtect
= MmProtectToValue
[Vad
->u
.VadFlags
.Protection
];
2063 /* Loop all the PTEs now */
2064 while (PointerPte
<= LastPte
)
2066 /* Check if we've crossed a PDE boundary and make the new PDE valid too */
2067 if (MiIsPteOnPdeBoundary(PointerPte
))
2069 PointerPde
= MiAddressToPte(PointerPte
);
2070 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
2073 /* Capture the PTE and check if it was empty */
2074 PteContents
= *PointerPte
;
2075 if (PteContents
.u
.Long
== 0)
2077 /* This used to be a zero PTE and it no longer is, so we must add a
2078 reference to the pagetable. */
2079 MiIncrementPageTableReferences(MiPteToAddress(PointerPte
));
2082 /* Check what kind of PTE we are dealing with */
2083 if (PteContents
.u
.Hard
.Valid
== 1)
2085 /* Get the PFN entry */
2086 Pfn1
= MiGetPfnEntry(PFN_FROM_PTE(&PteContents
));
2088 /* We don't support this yet */
2089 ASSERT(Pfn1
->u3
.e1
.PrototypePte
== 0);
2091 /* Check if the page should not be accessible at all */
2092 if ((NewAccessProtection
& PAGE_NOACCESS
) ||
2093 (NewAccessProtection
& PAGE_GUARD
))
2095 /* The page should be in the WS and we should make it transition now */
2096 DPRINT1("Making valid page invalid is not yet supported!\n");
2097 Status
= STATUS_NOT_IMPLEMENTED
;
2098 /* Unlock the working set */
2099 MiUnlockProcessWorkingSetUnsafe(Process
, Thread
);
2103 /* Write the protection mask and write it with a TLB flush */
2104 Pfn1
->OriginalPte
.u
.Soft
.Protection
= ProtectionMask
;
2105 MiFlushTbAndCapture(Vad
,
2113 /* We don't support these cases yet */
2114 ASSERT(PteContents
.u
.Soft
.Prototype
== 0);
2115 ASSERT(PteContents
.u
.Soft
.Transition
== 0);
2117 /* The PTE is already demand-zero, just update the protection mask */
2118 PointerPte
->u
.Soft
.Protection
= ProtectionMask
;
2119 ASSERT(PointerPte
->u
.Long
!= 0);
2122 /* Move to the next PTE */
2126 /* Unlock the working set */
2127 MiUnlockProcessWorkingSetUnsafe(Process
, Thread
);
2130 /* Unlock the address space */
2131 MmUnlockAddressSpace(AddressSpace
);
2133 /* Return parameters and success */
2134 *NumberOfBytesToProtect
= EndingAddress
- StartingAddress
+ 1;
2135 *BaseAddress
= (PVOID
)StartingAddress
;
2136 *OldAccessProtection
= OldProtect
;
2137 return STATUS_SUCCESS
;
2140 /* Unlock the address space and return the failure code */
2141 MmUnlockAddressSpace(AddressSpace
);
2147 MiMakePdeExistAndMakeValid(IN PMMPTE PointerPde
,
2148 IN PEPROCESS TargetProcess
,
2151 PMMPTE PointerPte
, PointerPpe
, PointerPxe
;
2154 // Sanity checks. The latter is because we only use this function with the
2155 // PFN lock not held, so it may go away in the future.
2157 ASSERT(KeAreAllApcsDisabled() == TRUE
);
2158 ASSERT(OldIrql
== MM_NOIRQL
);
2161 // Also get the PPE and PXE. This is okay not to #ifdef because they will
2162 // return the same address as the PDE on 2-level page table systems.
2164 // If everything is already valid, there is nothing to do.
2166 PointerPpe
= MiAddressToPte(PointerPde
);
2167 PointerPxe
= MiAddressToPde(PointerPde
);
2168 if ((PointerPxe
->u
.Hard
.Valid
) &&
2169 (PointerPpe
->u
.Hard
.Valid
) &&
2170 (PointerPde
->u
.Hard
.Valid
))
2176 // At least something is invalid, so begin by getting the PTE for the PDE itself
2177 // and then lookup each additional level. We must do it in this precise order
2178 // because the pagfault.c code (as well as in Windows) depends that the next
2179 // level up (higher) must be valid when faulting a lower level
2181 PointerPte
= MiPteToAddress(PointerPde
);
2185 // Make sure APCs continued to be disabled
2187 ASSERT(KeAreAllApcsDisabled() == TRUE
);
2190 // First, make the PXE valid if needed
2192 if (!PointerPxe
->u
.Hard
.Valid
)
2194 MiMakeSystemAddressValid(PointerPpe
, TargetProcess
);
2195 ASSERT(PointerPxe
->u
.Hard
.Valid
== 1);
2201 if (!PointerPpe
->u
.Hard
.Valid
)
2203 MiMakeSystemAddressValid(PointerPde
, TargetProcess
);
2204 ASSERT(PointerPpe
->u
.Hard
.Valid
== 1);
2208 // And finally, make the PDE itself valid.
2210 MiMakeSystemAddressValid(PointerPte
, TargetProcess
);
2213 // This should've worked the first time so the loop is really just for
2214 // show -- ASSERT that we're actually NOT going to be looping.
2216 ASSERT(PointerPxe
->u
.Hard
.Valid
== 1);
2217 ASSERT(PointerPpe
->u
.Hard
.Valid
== 1);
2218 ASSERT(PointerPde
->u
.Hard
.Valid
== 1);
2219 } while (!(PointerPxe
->u
.Hard
.Valid
) ||
2220 !(PointerPpe
->u
.Hard
.Valid
) ||
2221 !(PointerPde
->u
.Hard
.Valid
));
2226 MiProcessValidPteList(IN PMMPTE
*ValidPteList
,
2232 PFN_NUMBER PageFrameIndex
;
2236 // Acquire the PFN lock and loop all the PTEs in the list
2238 OldIrql
= KeAcquireQueuedSpinLock(LockQueuePfnLock
);
2239 for (i
= 0; i
!= Count
; i
++)
2242 // The PTE must currently be valid
2244 TempPte
= *ValidPteList
[i
];
2245 ASSERT(TempPte
.u
.Hard
.Valid
== 1);
2248 // Get the PFN entry for the page itself, and then for its page table
2250 PageFrameIndex
= PFN_FROM_PTE(&TempPte
);
2251 Pfn1
= MiGetPfnEntry(PageFrameIndex
);
2252 Pfn2
= MiGetPfnEntry(Pfn1
->u4
.PteFrame
);
2255 // Decrement the share count on the page table, and then on the page
2258 MiDecrementShareCount(Pfn2
, Pfn1
->u4
.PteFrame
);
2259 MI_SET_PFN_DELETED(Pfn1
);
2260 MiDecrementShareCount(Pfn1
, PageFrameIndex
);
2263 // Make the page decommitted
2265 MI_WRITE_INVALID_PTE(ValidPteList
[i
], MmDecommittedPte
);
2269 // All the PTEs have been dereferenced and made invalid, flush the TLB now
2270 // and then release the PFN lock
2273 KeReleaseQueuedSpinLock(LockQueuePfnLock
, OldIrql
);
2278 MiDecommitPages(IN PVOID StartingAddress
,
2279 IN PMMPTE EndingPte
,
2280 IN PEPROCESS Process
,
2283 PMMPTE PointerPde
, PointerPte
, CommitPte
= NULL
;
2284 ULONG CommitReduction
= 0;
2285 PMMPTE ValidPteList
[256];
2289 PETHREAD CurrentThread
= PsGetCurrentThread();
2292 // Get the PTE and PTE for the address, and lock the working set
2293 // If this was a VAD for a MEM_COMMIT allocation, also figure out where the
2294 // commited range ends so that we can do the right accounting.
2296 PointerPde
= MiAddressToPde(StartingAddress
);
2297 PointerPte
= MiAddressToPte(StartingAddress
);
2298 if (Vad
->u
.VadFlags
.MemCommit
) CommitPte
= MiAddressToPte(Vad
->EndingVpn
<< PAGE_SHIFT
);
2299 MiLockProcessWorkingSetUnsafe(Process
, CurrentThread
);
2302 // Make the PDE valid, and now loop through each page's worth of data
2304 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
2305 while (PointerPte
<= EndingPte
)
2308 // Check if we've crossed a PDE boundary
2310 if (MiIsPteOnPdeBoundary(PointerPte
))
2313 // Get the new PDE and flush the valid PTEs we had built up until
2314 // now. This helps reduce the amount of TLB flushing we have to do.
2315 // Note that Windows does a much better job using timestamps and
2316 // such, and does not flush the entire TLB all the time, but right
2317 // now we have bigger problems to worry about than TLB flushing.
2319 PointerPde
= MiAddressToPde(StartingAddress
);
2322 MiProcessValidPteList(ValidPteList
, PteCount
);
2327 // Make this PDE valid
2329 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
2333 // Read this PTE. It might be active or still demand-zero.
2335 PteContents
= *PointerPte
;
2336 if (PteContents
.u
.Long
)
2339 // The PTE is active. It might be valid and in a working set, or
2340 // it might be a prototype PTE or paged out or even in transition.
2342 if (PointerPte
->u
.Long
== MmDecommittedPte
.u
.Long
)
2345 // It's already decommited, so there's nothing for us to do here
2352 // Remove it from the counters, and check if it was valid or not
2354 //Process->NumberOfPrivatePages--;
2355 if (PteContents
.u
.Hard
.Valid
)
2358 // It's valid. At this point make sure that it is not a ROS
2359 // PFN. Also, we don't support ProtoPTEs in this code path.
2361 Pfn1
= MiGetPfnEntry(PteContents
.u
.Hard
.PageFrameNumber
);
2362 ASSERT(MI_IS_ROS_PFN(Pfn1
) == FALSE
);
2363 ASSERT(Pfn1
->u3
.e1
.PrototypePte
== FALSE
);
2366 // Flush any pending PTEs that we had not yet flushed, if our
2367 // list has gotten too big, then add this PTE to the flush list.
2369 if (PteCount
== 256)
2371 MiProcessValidPteList(ValidPteList
, PteCount
);
2374 ValidPteList
[PteCount
++] = PointerPte
;
2379 // We do not support any of these other scenarios at the moment
2381 ASSERT(PteContents
.u
.Soft
.Prototype
== 0);
2382 ASSERT(PteContents
.u
.Soft
.Transition
== 0);
2383 ASSERT(PteContents
.u
.Soft
.PageFileHigh
== 0);
2386 // So the only other possibility is that it is still a demand
2387 // zero PTE, in which case we undo the accounting we did
2388 // earlier and simply make the page decommitted.
2390 //Process->NumberOfPrivatePages++;
2391 MI_WRITE_INVALID_PTE(PointerPte
, MmDecommittedPte
);
2398 // This used to be a zero PTE and it no longer is, so we must add a
2399 // reference to the pagetable.
2401 MiIncrementPageTableReferences(StartingAddress
);
2404 // Next, we account for decommitted PTEs and make the PTE as such
2406 if (PointerPte
> CommitPte
) CommitReduction
++;
2407 MI_WRITE_INVALID_PTE(PointerPte
, MmDecommittedPte
);
2411 // Move to the next PTE and the next address
2414 StartingAddress
= (PVOID
)((ULONG_PTR
)StartingAddress
+ PAGE_SIZE
);
2418 // Flush any dangling PTEs from the loop in the last page table, and then
2419 // release the working set and return the commit reduction accounting.
2421 if (PteCount
) MiProcessValidPteList(ValidPteList
, PteCount
);
2422 MiUnlockProcessWorkingSetUnsafe(Process
, CurrentThread
);
2423 return CommitReduction
;
2426 /* PUBLIC FUNCTIONS ***********************************************************/
2433 MmGetVirtualForPhysical(IN PHYSICAL_ADDRESS PhysicalAddress
)
2444 MmSecureVirtualMemory(IN PVOID Address
,
2448 static BOOLEAN Warn
; if (!Warn
++) UNIMPLEMENTED
;
2457 MmUnsecureVirtualMemory(IN PVOID SecureMem
)
2459 static BOOLEAN Warn
; if (!Warn
++) UNIMPLEMENTED
;
2462 /* SYSTEM CALLS ***************************************************************/
2466 NtReadVirtualMemory(IN HANDLE ProcessHandle
,
2467 IN PVOID BaseAddress
,
2469 IN SIZE_T NumberOfBytesToRead
,
2470 OUT PSIZE_T NumberOfBytesRead OPTIONAL
)
2472 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
2474 NTSTATUS Status
= STATUS_SUCCESS
;
2475 SIZE_T BytesRead
= 0;
2479 // Check if we came from user mode
2481 if (PreviousMode
!= KernelMode
)
2484 // Validate the read addresses
2486 if ((((ULONG_PTR
)BaseAddress
+ NumberOfBytesToRead
) < (ULONG_PTR
)BaseAddress
) ||
2487 (((ULONG_PTR
)Buffer
+ NumberOfBytesToRead
) < (ULONG_PTR
)Buffer
) ||
2488 (((ULONG_PTR
)BaseAddress
+ NumberOfBytesToRead
) > MmUserProbeAddress
) ||
2489 (((ULONG_PTR
)Buffer
+ NumberOfBytesToRead
) > MmUserProbeAddress
))
2492 // Don't allow to write into kernel space
2494 return STATUS_ACCESS_VIOLATION
;
2498 // Enter SEH for probe
2503 // Probe the output value
2505 if (NumberOfBytesRead
) ProbeForWriteSize_t(NumberOfBytesRead
);
2507 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2510 // Get exception code
2512 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2518 // Don't do zero-byte transfers
2520 if (NumberOfBytesToRead
)
2523 // Reference the process
2525 Status
= ObReferenceObjectByHandle(ProcessHandle
,
2531 if (NT_SUCCESS(Status
))
2536 Status
= MmCopyVirtualMemory(Process
,
2538 PsGetCurrentProcess(),
2540 NumberOfBytesToRead
,
2545 // Dereference the process
2547 ObDereferenceObject(Process
);
2552 // Check if the caller sent this parameter
2554 if (NumberOfBytesRead
)
2557 // Enter SEH to guard write
2562 // Return the number of bytes read
2564 *NumberOfBytesRead
= BytesRead
;
2566 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2580 NtWriteVirtualMemory(IN HANDLE ProcessHandle
,
2581 IN PVOID BaseAddress
,
2583 IN SIZE_T NumberOfBytesToWrite
,
2584 OUT PSIZE_T NumberOfBytesWritten OPTIONAL
)
2586 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
2588 NTSTATUS Status
= STATUS_SUCCESS
;
2589 SIZE_T BytesWritten
= 0;
2593 // Check if we came from user mode
2595 if (PreviousMode
!= KernelMode
)
2598 // Validate the read addresses
2600 if ((((ULONG_PTR
)BaseAddress
+ NumberOfBytesToWrite
) < (ULONG_PTR
)BaseAddress
) ||
2601 (((ULONG_PTR
)Buffer
+ NumberOfBytesToWrite
) < (ULONG_PTR
)Buffer
) ||
2602 (((ULONG_PTR
)BaseAddress
+ NumberOfBytesToWrite
) > MmUserProbeAddress
) ||
2603 (((ULONG_PTR
)Buffer
+ NumberOfBytesToWrite
) > MmUserProbeAddress
))
2606 // Don't allow to write into kernel space
2608 return STATUS_ACCESS_VIOLATION
;
2612 // Enter SEH for probe
2617 // Probe the output value
2619 if (NumberOfBytesWritten
) ProbeForWriteSize_t(NumberOfBytesWritten
);
2621 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2624 // Get exception code
2626 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2632 // Don't do zero-byte transfers
2634 if (NumberOfBytesToWrite
)
2637 // Reference the process
2639 Status
= ObReferenceObjectByHandle(ProcessHandle
,
2645 if (NT_SUCCESS(Status
))
2650 Status
= MmCopyVirtualMemory(PsGetCurrentProcess(),
2654 NumberOfBytesToWrite
,
2659 // Dereference the process
2661 ObDereferenceObject(Process
);
2666 // Check if the caller sent this parameter
2668 if (NumberOfBytesWritten
)
2671 // Enter SEH to guard write
2676 // Return the number of bytes written
2678 *NumberOfBytesWritten
= BytesWritten
;
2680 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2694 NtProtectVirtualMemory(IN HANDLE ProcessHandle
,
2695 IN OUT PVOID
*UnsafeBaseAddress
,
2696 IN OUT SIZE_T
*UnsafeNumberOfBytesToProtect
,
2697 IN ULONG NewAccessProtection
,
2698 OUT PULONG UnsafeOldAccessProtection
)
2701 ULONG OldAccessProtection
;
2703 PEPROCESS CurrentProcess
= PsGetCurrentProcess();
2704 PVOID BaseAddress
= NULL
;
2705 SIZE_T NumberOfBytesToProtect
= 0;
2706 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
2708 BOOLEAN Attached
= FALSE
;
2709 KAPC_STATE ApcState
;
2713 // Check for valid protection flags
2715 Protection
= NewAccessProtection
& ~(PAGE_GUARD
|PAGE_NOCACHE
);
2716 if (Protection
!= PAGE_NOACCESS
&&
2717 Protection
!= PAGE_READONLY
&&
2718 Protection
!= PAGE_READWRITE
&&
2719 Protection
!= PAGE_WRITECOPY
&&
2720 Protection
!= PAGE_EXECUTE
&&
2721 Protection
!= PAGE_EXECUTE_READ
&&
2722 Protection
!= PAGE_EXECUTE_READWRITE
&&
2723 Protection
!= PAGE_EXECUTE_WRITECOPY
)
2728 return STATUS_INVALID_PAGE_PROTECTION
;
2732 // Check if we came from user mode
2734 if (PreviousMode
!= KernelMode
)
2737 // Enter SEH for probing
2742 // Validate all outputs
2744 ProbeForWritePointer(UnsafeBaseAddress
);
2745 ProbeForWriteSize_t(UnsafeNumberOfBytesToProtect
);
2746 ProbeForWriteUlong(UnsafeOldAccessProtection
);
2751 BaseAddress
= *UnsafeBaseAddress
;
2752 NumberOfBytesToProtect
= *UnsafeNumberOfBytesToProtect
;
2754 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2757 // Get exception code
2759 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2768 BaseAddress
= *UnsafeBaseAddress
;
2769 NumberOfBytesToProtect
= *UnsafeNumberOfBytesToProtect
;
2773 // Catch illegal base address
2775 if (BaseAddress
> MM_HIGHEST_USER_ADDRESS
) return STATUS_INVALID_PARAMETER_2
;
2778 // Catch illegal region size
2780 if ((MmUserProbeAddress
- (ULONG_PTR
)BaseAddress
) < NumberOfBytesToProtect
)
2785 return STATUS_INVALID_PARAMETER_3
;
2789 // 0 is also illegal
2791 if (!NumberOfBytesToProtect
) return STATUS_INVALID_PARAMETER_3
;
2794 // Get a reference to the process
2796 Status
= ObReferenceObjectByHandle(ProcessHandle
,
2797 PROCESS_VM_OPERATION
,
2802 if (!NT_SUCCESS(Status
)) return Status
;
2805 // Check if we should attach
2807 if (CurrentProcess
!= Process
)
2812 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
2817 // Do the actual work
2819 Status
= MiProtectVirtualMemory(Process
,
2821 &NumberOfBytesToProtect
,
2822 NewAccessProtection
,
2823 &OldAccessProtection
);
2828 if (Attached
) KeUnstackDetachProcess(&ApcState
);
2831 // Release reference
2833 ObDereferenceObject(Process
);
2836 // Enter SEH to return data
2841 // Return data to user
2843 *UnsafeOldAccessProtection
= OldAccessProtection
;
2844 *UnsafeBaseAddress
= BaseAddress
;
2845 *UnsafeNumberOfBytesToProtect
= NumberOfBytesToProtect
;
2847 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2860 NtLockVirtualMemory(IN HANDLE ProcessHandle
,
2861 IN OUT PVOID
*BaseAddress
,
2862 IN OUT PSIZE_T NumberOfBytesToLock
,
2866 PEPROCESS CurrentProcess
= PsGetCurrentProcess();
2868 BOOLEAN Attached
= FALSE
;
2869 KAPC_STATE ApcState
;
2870 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
2871 PVOID CapturedBaseAddress
;
2872 SIZE_T CapturedBytesToLock
;
2878 if ((MapType
& ~(MAP_PROCESS
| MAP_SYSTEM
)))
2881 // Invalid set of flags
2883 return STATUS_INVALID_PARAMETER
;
2887 // At least one flag must be specified
2889 if (!(MapType
& (MAP_PROCESS
| MAP_SYSTEM
)))
2894 return STATUS_INVALID_PARAMETER
;
2898 // Enter SEH for probing
2903 // Validate output data
2905 ProbeForWritePointer(BaseAddress
);
2906 ProbeForWriteSize_t(NumberOfBytesToLock
);
2911 CapturedBaseAddress
= *BaseAddress
;
2912 CapturedBytesToLock
= *NumberOfBytesToLock
;
2914 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
2917 // Get exception code
2919 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2924 // Catch illegal base address
2926 if (CapturedBaseAddress
> MM_HIGHEST_USER_ADDRESS
) return STATUS_INVALID_PARAMETER
;
2929 // Catch illegal region size
2931 if ((MmUserProbeAddress
- (ULONG_PTR
)CapturedBaseAddress
) < CapturedBytesToLock
)
2936 return STATUS_INVALID_PARAMETER
;
2940 // 0 is also illegal
2942 if (!CapturedBytesToLock
) return STATUS_INVALID_PARAMETER
;
2945 // Get a reference to the process
2947 Status
= ObReferenceObjectByHandle(ProcessHandle
,
2948 PROCESS_VM_OPERATION
,
2953 if (!NT_SUCCESS(Status
)) return Status
;
2956 // Check if this is is system-mapped
2958 if (MapType
& MAP_SYSTEM
)
2961 // Check for required privilege
2963 if (!SeSinglePrivilegeCheck(SeLockMemoryPrivilege
, PreviousMode
))
2966 // Fail: Don't have it
2968 ObDereferenceObject(Process
);
2969 return STATUS_PRIVILEGE_NOT_HELD
;
2974 // Check if we should attach
2976 if (CurrentProcess
!= Process
)
2981 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
2993 if (Attached
) KeUnstackDetachProcess(&ApcState
);
2996 // Release reference
2998 ObDereferenceObject(Process
);
3001 // Enter SEH to return data
3006 // Return data to user
3008 *BaseAddress
= CapturedBaseAddress
;
3009 *NumberOfBytesToLock
= 0;
3011 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3014 // Get exception code
3016 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3023 return STATUS_SUCCESS
;
3028 NtUnlockVirtualMemory(IN HANDLE ProcessHandle
,
3029 IN OUT PVOID
*BaseAddress
,
3030 IN OUT PSIZE_T NumberOfBytesToUnlock
,
3034 PEPROCESS CurrentProcess
= PsGetCurrentProcess();
3036 BOOLEAN Attached
= FALSE
;
3037 KAPC_STATE ApcState
;
3038 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
3039 PVOID CapturedBaseAddress
;
3040 SIZE_T CapturedBytesToUnlock
;
3046 if ((MapType
& ~(MAP_PROCESS
| MAP_SYSTEM
)))
3049 // Invalid set of flags
3051 return STATUS_INVALID_PARAMETER
;
3055 // At least one flag must be specified
3057 if (!(MapType
& (MAP_PROCESS
| MAP_SYSTEM
)))
3062 return STATUS_INVALID_PARAMETER
;
3066 // Enter SEH for probing
3071 // Validate output data
3073 ProbeForWritePointer(BaseAddress
);
3074 ProbeForWriteSize_t(NumberOfBytesToUnlock
);
3079 CapturedBaseAddress
= *BaseAddress
;
3080 CapturedBytesToUnlock
= *NumberOfBytesToUnlock
;
3082 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3085 // Get exception code
3087 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3092 // Catch illegal base address
3094 if (CapturedBaseAddress
> MM_HIGHEST_USER_ADDRESS
) return STATUS_INVALID_PARAMETER
;
3097 // Catch illegal region size
3099 if ((MmUserProbeAddress
- (ULONG_PTR
)CapturedBaseAddress
) < CapturedBytesToUnlock
)
3104 return STATUS_INVALID_PARAMETER
;
3108 // 0 is also illegal
3110 if (!CapturedBytesToUnlock
) return STATUS_INVALID_PARAMETER
;
3113 // Get a reference to the process
3115 Status
= ObReferenceObjectByHandle(ProcessHandle
,
3116 PROCESS_VM_OPERATION
,
3121 if (!NT_SUCCESS(Status
)) return Status
;
3124 // Check if this is is system-mapped
3126 if (MapType
& MAP_SYSTEM
)
3129 // Check for required privilege
3131 if (!SeSinglePrivilegeCheck(SeLockMemoryPrivilege
, PreviousMode
))
3134 // Fail: Don't have it
3136 ObDereferenceObject(Process
);
3137 return STATUS_PRIVILEGE_NOT_HELD
;
3142 // Check if we should attach
3144 if (CurrentProcess
!= Process
)
3149 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
3161 if (Attached
) KeUnstackDetachProcess(&ApcState
);
3164 // Release reference
3166 ObDereferenceObject(Process
);
3169 // Enter SEH to return data
3174 // Return data to user
3176 *BaseAddress
= PAGE_ALIGN(CapturedBaseAddress
);
3177 *NumberOfBytesToUnlock
= 0;
3179 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3182 // Get exception code
3184 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3191 return STATUS_SUCCESS
;
3196 NtFlushVirtualMemory(IN HANDLE ProcessHandle
,
3197 IN OUT PVOID
*BaseAddress
,
3198 IN OUT PSIZE_T NumberOfBytesToFlush
,
3199 OUT PIO_STATUS_BLOCK IoStatusBlock
)
3203 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
3204 PVOID CapturedBaseAddress
;
3205 SIZE_T CapturedBytesToFlush
;
3206 IO_STATUS_BLOCK LocalStatusBlock
;
3210 // Check if we came from user mode
3212 if (PreviousMode
!= KernelMode
)
3215 // Enter SEH for probing
3220 // Validate all outputs
3222 ProbeForWritePointer(BaseAddress
);
3223 ProbeForWriteSize_t(NumberOfBytesToFlush
);
3224 ProbeForWriteIoStatusBlock(IoStatusBlock
);
3229 CapturedBaseAddress
= *BaseAddress
;
3230 CapturedBytesToFlush
= *NumberOfBytesToFlush
;
3232 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3235 // Get exception code
3237 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3246 CapturedBaseAddress
= *BaseAddress
;
3247 CapturedBytesToFlush
= *NumberOfBytesToFlush
;
3251 // Catch illegal base address
3253 if (CapturedBaseAddress
> MM_HIGHEST_USER_ADDRESS
) return STATUS_INVALID_PARAMETER
;
3256 // Catch illegal region size
3258 if ((MmUserProbeAddress
- (ULONG_PTR
)CapturedBaseAddress
) < CapturedBytesToFlush
)
3263 return STATUS_INVALID_PARAMETER
;
3267 // Get a reference to the process
3269 Status
= ObReferenceObjectByHandle(ProcessHandle
,
3270 PROCESS_VM_OPERATION
,
3275 if (!NT_SUCCESS(Status
)) return Status
;
3280 Status
= MmFlushVirtualMemory(Process
,
3281 &CapturedBaseAddress
,
3282 &CapturedBytesToFlush
,
3286 // Release reference
3288 ObDereferenceObject(Process
);
3291 // Enter SEH to return data
3296 // Return data to user
3298 *BaseAddress
= PAGE_ALIGN(CapturedBaseAddress
);
3299 *NumberOfBytesToFlush
= 0;
3300 *IoStatusBlock
= LocalStatusBlock
;
3302 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3318 NtGetWriteWatch(IN HANDLE ProcessHandle
,
3320 IN PVOID BaseAddress
,
3321 IN SIZE_T RegionSize
,
3322 IN PVOID
*UserAddressArray
,
3323 OUT PULONG_PTR EntriesInUserAddressArray
,
3324 OUT PULONG Granularity
)
3329 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
3330 ULONG_PTR CapturedEntryCount
;
3334 // Check if we came from user mode
3336 if (PreviousMode
!= KernelMode
)
3339 // Enter SEH for probing
3344 // Catch illegal base address
3346 if (BaseAddress
> MM_HIGHEST_USER_ADDRESS
) _SEH2_YIELD(return STATUS_INVALID_PARAMETER_2
);
3349 // Catch illegal region size
3351 if ((MmUserProbeAddress
- (ULONG_PTR
)BaseAddress
) < RegionSize
)
3356 _SEH2_YIELD(return STATUS_INVALID_PARAMETER_3
);
3360 // Validate all data
3362 ProbeForWriteSize_t(EntriesInUserAddressArray
);
3363 ProbeForWriteUlong(Granularity
);
3368 CapturedEntryCount
= *EntriesInUserAddressArray
;
3371 // Must have a count
3373 if (CapturedEntryCount
== 0) _SEH2_YIELD(return STATUS_INVALID_PARAMETER_5
);
3376 // Can't be larger than the maximum
3378 if (CapturedEntryCount
> (MAXULONG_PTR
/ sizeof(ULONG_PTR
)))
3383 _SEH2_YIELD(return STATUS_INVALID_PARAMETER_5
);
3387 // Probe the actual array
3389 ProbeForWrite(UserAddressArray
,
3390 CapturedEntryCount
* sizeof(PVOID
),
3393 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3396 // Get exception code
3398 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3407 CapturedEntryCount
= *EntriesInUserAddressArray
;
3408 ASSERT(CapturedEntryCount
!= 0);
3412 // Check if this is a local request
3414 if (ProcessHandle
== NtCurrentProcess())
3417 // No need to reference the process
3419 Process
= PsGetCurrentProcess();
3424 // Reference the target
3426 Status
= ObReferenceObjectByHandle(ProcessHandle
,
3427 PROCESS_VM_OPERATION
,
3432 if (!NT_SUCCESS(Status
)) return Status
;
3436 // Compute the last address and validate it
3438 EndAddress
= (PVOID
)((ULONG_PTR
)BaseAddress
+ RegionSize
- 1);
3439 if (BaseAddress
> EndAddress
)
3444 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
3445 return STATUS_INVALID_PARAMETER_4
;
3454 // Dereference if needed
3456 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
3459 // Enter SEH to return data
3464 // Return data to user
3466 *EntriesInUserAddressArray
= 0;
3467 *Granularity
= PAGE_SIZE
;
3469 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3472 // Get exception code
3474 Status
= _SEH2_GetExceptionCode();
3481 return STATUS_SUCCESS
;
3489 NtResetWriteWatch(IN HANDLE ProcessHandle
,
3490 IN PVOID BaseAddress
,
3491 IN SIZE_T RegionSize
)
3496 KPROCESSOR_MODE PreviousMode
= ExGetPreviousMode();
3497 ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL
);
3500 // Catch illegal base address
3502 if (BaseAddress
> MM_HIGHEST_USER_ADDRESS
) return STATUS_INVALID_PARAMETER_2
;
3505 // Catch illegal region size
3507 if ((MmUserProbeAddress
- (ULONG_PTR
)BaseAddress
) < RegionSize
)
3512 return STATUS_INVALID_PARAMETER_3
;
3516 // Check if this is a local request
3518 if (ProcessHandle
== NtCurrentProcess())
3521 // No need to reference the process
3523 Process
= PsGetCurrentProcess();
3528 // Reference the target
3530 Status
= ObReferenceObjectByHandle(ProcessHandle
,
3531 PROCESS_VM_OPERATION
,
3536 if (!NT_SUCCESS(Status
)) return Status
;
3540 // Compute the last address and validate it
3542 EndAddress
= (PVOID
)((ULONG_PTR
)BaseAddress
+ RegionSize
- 1);
3543 if (BaseAddress
> EndAddress
)
3548 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
3549 return STATUS_INVALID_PARAMETER_3
;
3558 // Dereference if needed
3560 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
3565 return STATUS_SUCCESS
;
3570 NtQueryVirtualMemory(IN HANDLE ProcessHandle
,
3571 IN PVOID BaseAddress
,
3572 IN MEMORY_INFORMATION_CLASS MemoryInformationClass
,
3573 OUT PVOID MemoryInformation
,
3574 IN SIZE_T MemoryInformationLength
,
3575 OUT PSIZE_T ReturnLength
)
3577 NTSTATUS Status
= STATUS_SUCCESS
;
3578 KPROCESSOR_MODE PreviousMode
;
3580 DPRINT("Querying class %d about address: %p\n", MemoryInformationClass
, BaseAddress
);
3582 /* Bail out if the address is invalid */
3583 if (BaseAddress
> MM_HIGHEST_USER_ADDRESS
) return STATUS_INVALID_PARAMETER
;
3585 /* Probe return buffer */
3586 PreviousMode
= ExGetPreviousMode();
3587 if (PreviousMode
!= KernelMode
)
3591 ProbeForWrite(MemoryInformation
,
3592 MemoryInformationLength
,
3595 if (ReturnLength
) ProbeForWriteSize_t(ReturnLength
);
3597 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3599 Status
= _SEH2_GetExceptionCode();
3603 if (!NT_SUCCESS(Status
))
3609 switch(MemoryInformationClass
)
3611 case MemoryBasicInformation
:
3612 /* Validate the size information of the class */
3613 if (MemoryInformationLength
< sizeof(MEMORY_BASIC_INFORMATION
))
3615 /* The size is invalid */
3616 return STATUS_INFO_LENGTH_MISMATCH
;
3618 Status
= MiQueryMemoryBasicInformation(ProcessHandle
,
3621 MemoryInformationLength
,
3625 case MemorySectionName
:
3626 /* Validate the size information of the class */
3627 if (MemoryInformationLength
< sizeof(MEMORY_SECTION_NAME
))
3629 /* The size is invalid */
3630 return STATUS_INFO_LENGTH_MISMATCH
;
3632 Status
= MiQueryMemorySectionName(ProcessHandle
,
3635 MemoryInformationLength
,
3638 case MemoryWorkingSetList
:
3639 case MemoryBasicVlmInformation
:
3641 DPRINT1("Unhandled memory information class %d\n", MemoryInformationClass
);
3653 NtAllocateVirtualMemory(IN HANDLE ProcessHandle
,
3654 IN OUT PVOID
* UBaseAddress
,
3655 IN ULONG_PTR ZeroBits
,
3656 IN OUT PSIZE_T URegionSize
,
3657 IN ULONG AllocationType
,
3661 PMEMORY_AREA MemoryArea
;
3662 PFN_NUMBER PageCount
;
3663 PMMVAD Vad
, FoundVad
;
3665 PMMSUPPORT AddressSpace
;
3667 ULONG_PTR PRegionSize
, StartingAddress
, EndingAddress
;
3668 PEPROCESS CurrentProcess
= PsGetCurrentProcess();
3669 KPROCESSOR_MODE PreviousMode
= KeGetPreviousMode();
3670 PETHREAD CurrentThread
= PsGetCurrentThread();
3671 KAPC_STATE ApcState
;
3672 ULONG ProtectionMask
, QuotaCharge
= 0, QuotaFree
= 0;
3673 BOOLEAN Attached
= FALSE
, ChangeProtection
= FALSE
;
3675 PMMPTE PointerPte
, PointerPde
, LastPte
;
3678 /* Check for valid Zero bits */
3681 DPRINT1("Too many zero bits\n");
3682 return STATUS_INVALID_PARAMETER_3
;
3685 /* Check for valid Allocation Types */
3686 if ((AllocationType
& ~(MEM_COMMIT
| MEM_RESERVE
| MEM_RESET
| MEM_PHYSICAL
|
3687 MEM_TOP_DOWN
| MEM_WRITE_WATCH
)))
3689 DPRINT1("Invalid Allocation Type\n");
3690 return STATUS_INVALID_PARAMETER_5
;
3693 /* Check for at least one of these Allocation Types to be set */
3694 if (!(AllocationType
& (MEM_COMMIT
| MEM_RESERVE
| MEM_RESET
)))
3696 DPRINT1("No memory allocation base type\n");
3697 return STATUS_INVALID_PARAMETER_5
;
3700 /* MEM_RESET is an exclusive flag, make sure that is valid too */
3701 if ((AllocationType
& MEM_RESET
) && (AllocationType
!= MEM_RESET
))
3703 DPRINT1("Invalid use of MEM_RESET\n");
3704 return STATUS_INVALID_PARAMETER_5
;
3707 /* Check if large pages are being used */
3708 if (AllocationType
& MEM_LARGE_PAGES
)
3710 /* Large page allocations MUST be committed */
3711 if (!(AllocationType
& MEM_COMMIT
))
3713 DPRINT1("Must supply MEM_COMMIT with MEM_LARGE_PAGES\n");
3714 return STATUS_INVALID_PARAMETER_5
;
3717 /* These flags are not allowed with large page allocations */
3718 if (AllocationType
& (MEM_PHYSICAL
| MEM_RESET
| MEM_WRITE_WATCH
))
3720 DPRINT1("Using illegal flags with MEM_LARGE_PAGES\n");
3721 return STATUS_INVALID_PARAMETER_5
;
3725 /* MEM_WRITE_WATCH can only be used if MEM_RESERVE is also used */
3726 if ((AllocationType
& MEM_WRITE_WATCH
) && !(AllocationType
& MEM_RESERVE
))
3728 DPRINT1("MEM_WRITE_WATCH used without MEM_RESERVE\n");
3729 return STATUS_INVALID_PARAMETER_5
;
3732 /* MEM_PHYSICAL can only be used if MEM_RESERVE is also used */
3733 if ((AllocationType
& MEM_PHYSICAL
) && !(AllocationType
& MEM_RESERVE
))
3735 DPRINT1("MEM_WRITE_WATCH used without MEM_RESERVE\n");
3736 return STATUS_INVALID_PARAMETER_5
;
3739 /* Check for valid MEM_PHYSICAL usage */
3740 if (AllocationType
& MEM_PHYSICAL
)
3742 /* Only these flags are allowed with MEM_PHYSIAL */
3743 if (AllocationType
& ~(MEM_RESERVE
| MEM_TOP_DOWN
| MEM_PHYSICAL
))
3745 DPRINT1("Using illegal flags with MEM_PHYSICAL\n");
3746 return STATUS_INVALID_PARAMETER_5
;
3749 /* Then make sure PAGE_READWRITE is used */
3750 if (Protect
!= PAGE_READWRITE
)
3752 DPRINT1("MEM_PHYSICAL used without PAGE_READWRITE\n");
3753 return STATUS_INVALID_PARAMETER_6
;
3757 /* Calculate the protection mask and make sure it's valid */
3758 ProtectionMask
= MiMakeProtectionMask(Protect
);
3759 if (ProtectionMask
== MM_INVALID_PROTECTION
)
3761 DPRINT1("Invalid protection mask\n");
3762 return STATUS_INVALID_PAGE_PROTECTION
;
3768 /* Check for user-mode parameters */
3769 if (PreviousMode
!= KernelMode
)
3771 /* Make sure they are writable */
3772 ProbeForWritePointer(UBaseAddress
);
3773 ProbeForWriteUlong(URegionSize
);
3776 /* Capture their values */
3777 PBaseAddress
= *UBaseAddress
;
3778 PRegionSize
= *URegionSize
;
3780 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
3782 /* Return the exception code */
3783 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3787 /* Make sure the allocation isn't past the VAD area */
3788 if (PBaseAddress
>= MM_HIGHEST_VAD_ADDRESS
)
3790 DPRINT1("Virtual allocation base above User Space\n");
3791 return STATUS_INVALID_PARAMETER_2
;
3794 /* Make sure the allocation wouldn't overflow past the VAD area */
3795 if ((((ULONG_PTR
)MM_HIGHEST_VAD_ADDRESS
+ 1) - (ULONG_PTR
)PBaseAddress
) < PRegionSize
)
3797 DPRINT1("Region size would overflow into kernel-memory\n");
3798 return STATUS_INVALID_PARAMETER_4
;
3801 /* Make sure there's a size specified */
3804 DPRINT1("Region size is invalid (zero)\n");
3805 return STATUS_INVALID_PARAMETER_4
;
3809 // If this is for the current process, just use PsGetCurrentProcess
3811 if (ProcessHandle
== NtCurrentProcess())
3813 Process
= CurrentProcess
;
3818 // Otherwise, reference the process with VM rights and attach to it if
3819 // this isn't the current process. We must attach because we'll be touching
3820 // PTEs and PDEs that belong to user-mode memory, and also touching the
3821 // Working Set which is stored in Hyperspace.
3823 Status
= ObReferenceObjectByHandle(ProcessHandle
,
3824 PROCESS_VM_OPERATION
,
3829 if (!NT_SUCCESS(Status
)) return Status
;
3830 if (CurrentProcess
!= Process
)
3832 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
3838 // Check for large page allocations and make sure that the required privilege
3839 // is being held, before attempting to handle them.
3841 if ((AllocationType
& MEM_LARGE_PAGES
) &&
3842 !(SeSinglePrivilegeCheck(SeLockMemoryPrivilege
, PreviousMode
)))
3844 /* Fail without it */
3845 DPRINT1("Privilege not held for MEM_LARGE_PAGES\n");
3846 Status
= STATUS_PRIVILEGE_NOT_HELD
;
3847 goto FailPathNoLock
;
3851 // Fail on the things we don't yet support
3855 DPRINT1("Zero bits not supported\n");
3856 Status
= STATUS_INVALID_PARAMETER
;
3857 goto FailPathNoLock
;
3859 if ((AllocationType
& MEM_LARGE_PAGES
) == MEM_LARGE_PAGES
)
3861 DPRINT1("MEM_LARGE_PAGES not supported\n");
3862 Status
= STATUS_INVALID_PARAMETER
;
3863 goto FailPathNoLock
;
3865 if ((AllocationType
& MEM_PHYSICAL
) == MEM_PHYSICAL
)
3867 DPRINT1("MEM_PHYSICAL not supported\n");
3868 Status
= STATUS_INVALID_PARAMETER
;
3869 goto FailPathNoLock
;
3871 if ((AllocationType
& MEM_WRITE_WATCH
) == MEM_WRITE_WATCH
)
3873 DPRINT1("MEM_WRITE_WATCH not supported\n");
3874 Status
= STATUS_INVALID_PARAMETER
;
3875 goto FailPathNoLock
;
3877 if ((AllocationType
& MEM_TOP_DOWN
) == MEM_TOP_DOWN
)
3879 DPRINT1("MEM_TOP_DOWN not supported\n");
3880 AllocationType
&= ~MEM_TOP_DOWN
;
3883 if (Process
->VmTopDown
== 1)
3885 DPRINT1("VmTopDown not supported\n");
3886 Status
= STATUS_INVALID_PARAMETER
;
3887 goto FailPathNoLock
;
3891 // Check if the caller is reserving memory, or committing memory and letting
3892 // us pick the base address
3894 if (!(PBaseAddress
) || (AllocationType
& MEM_RESERVE
))
3897 // Do not allow COPY_ON_WRITE through this API
3899 if ((Protect
& PAGE_WRITECOPY
) || (Protect
& PAGE_EXECUTE_WRITECOPY
))
3901 DPRINT1("Copy on write not allowed through this path\n");
3902 Status
= STATUS_INVALID_PAGE_PROTECTION
;
3903 goto FailPathNoLock
;
3907 // Does the caller have an address in mind, or is this a blind commit?
3912 // This is a blind commit, all we need is the region size
3914 PRegionSize
= ROUND_TO_PAGES(PRegionSize
);
3915 PageCount
= BYTES_TO_PAGES(PRegionSize
);
3917 StartingAddress
= 0;
3922 // This is a reservation, so compute the starting address on the
3923 // expected 64KB granularity, and see where the ending address will
3924 // fall based on the aligned address and the passed in region size
3926 StartingAddress
= ROUND_DOWN((ULONG_PTR
)PBaseAddress
, _64K
);
3927 EndingAddress
= ((ULONG_PTR
)PBaseAddress
+ PRegionSize
- 1) | (PAGE_SIZE
- 1);
3928 PageCount
= BYTES_TO_PAGES(EndingAddress
- StartingAddress
);
3932 // Allocate and initialize the VAD
3934 Vad
= ExAllocatePoolWithTag(NonPagedPool
, sizeof(MMVAD_LONG
), 'SdaV');
3935 ASSERT(Vad
!= NULL
);
3936 Vad
->u
.LongFlags
= 0;
3937 if (AllocationType
& MEM_COMMIT
) Vad
->u
.VadFlags
.MemCommit
= 1;
3938 Vad
->u
.VadFlags
.Protection
= ProtectionMask
;
3939 Vad
->u
.VadFlags
.PrivateMemory
= 1;
3940 Vad
->u
.VadFlags
.CommitCharge
= AllocationType
& MEM_COMMIT
? PageCount
: 0;
3943 // Lock the address space and make sure the process isn't already dead
3945 AddressSpace
= MmGetCurrentAddressSpace();
3946 MmLockAddressSpace(AddressSpace
);
3947 if (Process
->VmDeleted
)
3949 Status
= STATUS_PROCESS_IS_TERMINATING
;
3954 // Did we have a base address? If no, find a valid address that is 64KB
3955 // aligned in the VAD tree. Otherwise, make sure that the address range
3956 // which was passed in isn't already conflicting with an existing address
3961 Status
= MiFindEmptyAddressRangeInTree(PRegionSize
,
3964 (PMMADDRESS_NODE
*)&Process
->VadFreeHint
,
3966 if (!NT_SUCCESS(Status
)) goto FailPath
;
3969 // Now we know where the allocation ends. Make sure it doesn't end up
3970 // somewhere in kernel mode.
3972 EndingAddress
= ((ULONG_PTR
)StartingAddress
+ PRegionSize
- 1) | (PAGE_SIZE
- 1);
3973 if ((PVOID
)EndingAddress
> MM_HIGHEST_VAD_ADDRESS
)
3975 Status
= STATUS_NO_MEMORY
;
3979 else if (MiCheckForConflictingNode(StartingAddress
>> PAGE_SHIFT
,
3980 EndingAddress
>> PAGE_SHIFT
,
3984 // The address specified is in conflict!
3986 Status
= STATUS_CONFLICTING_ADDRESSES
;
3991 // Write out the VAD fields for this allocation
3993 Vad
->StartingVpn
= (ULONG_PTR
)StartingAddress
>> PAGE_SHIFT
;
3994 Vad
->EndingVpn
= (ULONG_PTR
)EndingAddress
>> PAGE_SHIFT
;
3997 // FIXME: Should setup VAD bitmap
3999 Status
= STATUS_SUCCESS
;
4002 // Lock the working set and insert the VAD into the process VAD tree
4004 MiLockProcessWorkingSetUnsafe(Process
, CurrentThread
);
4005 Vad
->ControlArea
= NULL
; // For Memory-Area hack
4006 MiInsertVad(Vad
, Process
);
4007 MiUnlockProcessWorkingSetUnsafe(Process
, CurrentThread
);
4010 // Update the virtual size of the process, and if this is now the highest
4011 // virtual size we have ever seen, update the peak virtual size to reflect
4014 Process
->VirtualSize
+= PRegionSize
;
4015 if (Process
->VirtualSize
> Process
->PeakVirtualSize
)
4017 Process
->PeakVirtualSize
= Process
->VirtualSize
;
4021 // Release address space and detach and dereference the target process if
4022 // it was different from the current process
4024 MmUnlockAddressSpace(AddressSpace
);
4025 if (Attached
) KeUnstackDetachProcess(&ApcState
);
4026 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
4029 // Use SEH to write back the base address and the region size. In the case
4030 // of an exception, we do not return back the exception code, as the memory
4031 // *has* been allocated. The caller would now have to call VirtualQuery
4032 // or do some other similar trick to actually find out where its memory
4033 // allocation ended up
4037 *URegionSize
= PRegionSize
;
4038 *UBaseAddress
= (PVOID
)StartingAddress
;
4040 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
4044 return STATUS_SUCCESS
;
4048 // This is a MEM_COMMIT on top of an existing address which must have been
4049 // MEM_RESERVED already. Compute the start and ending base addresses based
4050 // on the user input, and then compute the actual region size once all the
4051 // alignments have been done.
4053 StartingAddress
= (ULONG_PTR
)PAGE_ALIGN(PBaseAddress
);
4054 EndingAddress
= (((ULONG_PTR
)PBaseAddress
+ PRegionSize
- 1) | (PAGE_SIZE
- 1));
4055 PRegionSize
= EndingAddress
- StartingAddress
+ 1;
4058 // Lock the address space and make sure the process isn't already dead
4060 AddressSpace
= MmGetCurrentAddressSpace();
4061 MmLockAddressSpace(AddressSpace
);
4062 if (Process
->VmDeleted
)
4064 DPRINT1("Process is dying\n");
4065 Status
= STATUS_PROCESS_IS_TERMINATING
;
4070 // Get the VAD for this address range, and make sure it exists
4072 FoundVad
= (PMMVAD
)MiCheckForConflictingNode(StartingAddress
>> PAGE_SHIFT
,
4073 EndingAddress
>> PAGE_SHIFT
,
4077 DPRINT1("Could not find a VAD for this allocation\n");
4078 Status
= STATUS_CONFLICTING_ADDRESSES
;
4082 if ((AllocationType
& MEM_RESET
) == MEM_RESET
)
4084 /// @todo HACK: pretend success
4085 DPRINT("MEM_RESET not supported\n");
4086 Status
= STATUS_SUCCESS
;
4091 // These kinds of VADs are illegal for this Windows function when trying to
4092 // commit an existing range
4094 if ((FoundVad
->u
.VadFlags
.VadType
== VadAwe
) ||
4095 (FoundVad
->u
.VadFlags
.VadType
== VadDevicePhysicalMemory
) ||
4096 (FoundVad
->u
.VadFlags
.VadType
== VadLargePages
))
4098 DPRINT1("Illegal VAD for attempting a MEM_COMMIT\n");
4099 Status
= STATUS_CONFLICTING_ADDRESSES
;
4104 // Make sure that this address range actually fits within the VAD for it
4106 if (((StartingAddress
>> PAGE_SHIFT
) < FoundVad
->StartingVpn
) ||
4107 ((EndingAddress
>> PAGE_SHIFT
) > FoundVad
->EndingVpn
))
4109 DPRINT1("Address range does not fit into the VAD\n");
4110 Status
= STATUS_CONFLICTING_ADDRESSES
;
4115 // Make sure this is an ARM3 section
4117 MemoryArea
= MmLocateMemoryAreaByAddress(AddressSpace
, (PVOID
)PAGE_ROUND_DOWN(PBaseAddress
));
4118 if (MemoryArea
->Type
!= MEMORY_AREA_OWNED_BY_ARM3
)
4120 DPRINT1("Illegal commit of non-ARM3 section!\n");
4121 Status
= STATUS_ALREADY_COMMITTED
;
4125 // Is this a previously reserved section being committed? If so, enter the
4126 // special section path
4128 if (FoundVad
->u
.VadFlags
.PrivateMemory
== FALSE
)
4131 // You cannot commit large page sections through this API
4133 if (FoundVad
->u
.VadFlags
.VadType
== VadLargePageSection
)
4135 DPRINT1("Large page sections cannot be VirtualAlloc'd\n");
4136 Status
= STATUS_INVALID_PAGE_PROTECTION
;
4141 // You can only use caching flags on a rotate VAD
4143 if ((Protect
& (PAGE_NOCACHE
| PAGE_WRITECOMBINE
)) &&
4144 (FoundVad
->u
.VadFlags
.VadType
!= VadRotatePhysical
))
4146 DPRINT1("Cannot use caching flags with anything but rotate VADs\n");
4147 Status
= STATUS_INVALID_PAGE_PROTECTION
;
4152 // We should make sure that the section's permissions aren't being
4155 if (FoundVad
->u
.VadFlags
.NoChange
)
4158 // Make sure it's okay to touch it
4160 Status
= MiCheckSecuredVad(FoundVad
,
4164 if (!NT_SUCCESS(Status
))
4166 DPRINT1("Secured VAD being messed around with\n");
4172 // ARM3 does not support file-backed sections, only shared memory
4174 ASSERT(FoundVad
->ControlArea
->FilePointer
== NULL
);
4177 // Rotate VADs cannot be guard pages or inaccessible, nor copy on write
4179 if ((FoundVad
->u
.VadFlags
.VadType
== VadRotatePhysical
) &&
4180 (Protect
& (PAGE_WRITECOPY
| PAGE_EXECUTE_WRITECOPY
| PAGE_NOACCESS
| PAGE_GUARD
)))
4182 DPRINT1("Invalid page protection for rotate VAD\n");
4183 Status
= STATUS_INVALID_PAGE_PROTECTION
;
4188 // Compute PTE addresses and the quota charge, then grab the commit lock
4190 PointerPte
= MI_GET_PROTOTYPE_PTE_FOR_VPN(FoundVad
, StartingAddress
>> PAGE_SHIFT
);
4191 LastPte
= MI_GET_PROTOTYPE_PTE_FOR_VPN(FoundVad
, EndingAddress
>> PAGE_SHIFT
);
4192 QuotaCharge
= (ULONG
)(LastPte
- PointerPte
+ 1);
4193 KeAcquireGuardedMutexUnsafe(&MmSectionCommitMutex
);
4196 // Get the segment template PTE and start looping each page
4198 TempPte
= FoundVad
->ControlArea
->Segment
->SegmentPteTemplate
;
4199 ASSERT(TempPte
.u
.Long
!= 0);
4200 while (PointerPte
<= LastPte
)
4203 // For each non-already-committed page, write the invalid template PTE
4205 if (PointerPte
->u
.Long
== 0)
4207 MI_WRITE_INVALID_PTE(PointerPte
, TempPte
);
4217 // Now do the commit accounting and release the lock
4219 ASSERT(QuotaCharge
>= QuotaFree
);
4220 QuotaCharge
-= QuotaFree
;
4221 FoundVad
->ControlArea
->Segment
->NumberOfCommittedPages
+= QuotaCharge
;
4222 KeReleaseGuardedMutexUnsafe(&MmSectionCommitMutex
);
4225 // We are done with committing the section pages
4227 Status
= STATUS_SUCCESS
;
4232 // This is a specific ReactOS check because we only use normal VADs
4234 ASSERT(FoundVad
->u
.VadFlags
.VadType
== VadNone
);
4237 // While this is an actual Windows check
4239 ASSERT(FoundVad
->u
.VadFlags
.VadType
!= VadRotatePhysical
);
4242 // Throw out attempts to use copy-on-write through this API path
4244 if ((Protect
& PAGE_WRITECOPY
) || (Protect
& PAGE_EXECUTE_WRITECOPY
))
4246 DPRINT1("Write copy attempted when not allowed\n");
4247 Status
= STATUS_INVALID_PAGE_PROTECTION
;
4252 // Initialize a demand-zero PTE
4255 TempPte
.u
.Soft
.Protection
= ProtectionMask
;
4258 // Get the PTE, PDE and the last PTE for this address range
4260 PointerPde
= MiAddressToPde(StartingAddress
);
4261 PointerPte
= MiAddressToPte(StartingAddress
);
4262 LastPte
= MiAddressToPte(EndingAddress
);
4265 // Update the commit charge in the VAD as well as in the process, and check
4266 // if this commit charge was now higher than the last recorded peak, in which
4267 // case we also update the peak
4269 FoundVad
->u
.VadFlags
.CommitCharge
+= (1 + LastPte
- PointerPte
);
4270 Process
->CommitCharge
+= (1 + LastPte
- PointerPte
);
4271 if (Process
->CommitCharge
> Process
->CommitChargePeak
)
4273 Process
->CommitChargePeak
= Process
->CommitCharge
;
4277 // Lock the working set while we play with user pages and page tables
4279 MiLockProcessWorkingSetUnsafe(Process
, CurrentThread
);
4282 // Make the current page table valid, and then loop each page within it
4284 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
4285 while (PointerPte
<= LastPte
)
4288 // Have we crossed into a new page table?
4290 if (MiIsPteOnPdeBoundary(PointerPte
))
4293 // Get the PDE and now make it valid too
4295 PointerPde
= MiAddressToPte(PointerPte
);
4296 MiMakePdeExistAndMakeValid(PointerPde
, Process
, MM_NOIRQL
);
4300 // Is this a zero PTE as expected?
4302 if (PointerPte
->u
.Long
== 0)
4305 // First increment the count of pages in the page table for this
4308 MiIncrementPageTableReferences(MiPteToAddress(PointerPte
));
4311 // And now write the invalid demand-zero PTE as requested
4313 MI_WRITE_INVALID_PTE(PointerPte
, TempPte
);
4315 else if (PointerPte
->u
.Long
== MmDecommittedPte
.u
.Long
)
4318 // If the PTE was already decommitted, there is nothing else to do
4319 // but to write the new demand-zero PTE
4321 MI_WRITE_INVALID_PTE(PointerPte
, TempPte
);
4323 else if (!(ChangeProtection
) && (Protect
!= MiGetPageProtection(PointerPte
)))
4326 // We don't handle these scenarios yet
4328 if (PointerPte
->u
.Soft
.Valid
== 0)
4330 ASSERT(PointerPte
->u
.Soft
.Prototype
== 0);
4331 ASSERT(PointerPte
->u
.Soft
.PageFileHigh
== 0);
4335 // There's a change in protection, remember this for later, but do
4336 // not yet handle it.
4338 ChangeProtection
= TRUE
;
4342 // Move to the next PTE
4348 // Release the working set lock, unlock the address space, and detach from
4349 // the target process if it was not the current process. Also dereference the
4350 // target process if this wasn't the case.
4352 MiUnlockProcessWorkingSetUnsafe(Process
, CurrentThread
);
4353 Status
= STATUS_SUCCESS
;
4355 MmUnlockAddressSpace(AddressSpace
);
4358 // Check if we need to update the protection
4360 if (ChangeProtection
)
4362 PVOID ProtectBaseAddress
= (PVOID
)StartingAddress
;
4363 SIZE_T ProtectSize
= PRegionSize
;
4364 ULONG OldProtection
;
4367 // Change the protection of the region
4369 MiProtectVirtualMemory(Process
,
4370 &ProtectBaseAddress
,
4377 if (Attached
) KeUnstackDetachProcess(&ApcState
);
4378 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
4381 // Use SEH to write back the base address and the region size. In the case
4382 // of an exception, we strangely do return back the exception code, even
4383 // though the memory *has* been allocated. This mimics Windows behavior and
4384 // there is not much we can do about it.
4388 *URegionSize
= PRegionSize
;
4389 *UBaseAddress
= (PVOID
)StartingAddress
;
4391 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
4393 Status
= _SEH2_GetExceptionCode();
4404 NtFreeVirtualMemory(IN HANDLE ProcessHandle
,
4405 IN PVOID
* UBaseAddress
,
4406 IN PSIZE_T URegionSize
,
4409 PMEMORY_AREA MemoryArea
;
4412 ULONG_PTR CommitReduction
= 0;
4413 ULONG_PTR StartingAddress
, EndingAddress
;
4417 PMMSUPPORT AddressSpace
;
4418 PETHREAD CurrentThread
= PsGetCurrentThread();
4419 PEPROCESS CurrentProcess
= PsGetCurrentProcess();
4420 KPROCESSOR_MODE PreviousMode
= KeGetPreviousMode();
4421 KAPC_STATE ApcState
;
4422 BOOLEAN Attached
= FALSE
;
4426 // Only two flags are supported
4428 if (!(FreeType
& (MEM_RELEASE
| MEM_DECOMMIT
)))
4430 DPRINT1("Invalid FreeType\n");
4431 return STATUS_INVALID_PARAMETER_4
;
4435 // Check if no flag was used, or if both flags were used
4437 if (!((FreeType
& (MEM_DECOMMIT
| MEM_RELEASE
))) ||
4438 ((FreeType
& (MEM_DECOMMIT
| MEM_RELEASE
)) == (MEM_DECOMMIT
| MEM_RELEASE
)))
4440 DPRINT1("Invalid FreeType combination\n");
4441 return STATUS_INVALID_PARAMETER_4
;
4445 // Enter SEH for probe and capture. On failure, return back to the caller
4446 // with an exception violation.
4451 // Check for user-mode parameters and make sure that they are writeable
4453 if (PreviousMode
!= KernelMode
)
4455 ProbeForWritePointer(UBaseAddress
);
4456 ProbeForWriteUlong(URegionSize
);
4460 // Capture the current values
4462 PBaseAddress
= *UBaseAddress
;
4463 PRegionSize
= *URegionSize
;
4465 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
4467 _SEH2_YIELD(return _SEH2_GetExceptionCode());
4472 // Make sure the allocation isn't past the user area
4474 if (PBaseAddress
>= MM_HIGHEST_USER_ADDRESS
)
4476 DPRINT1("Virtual free base above User Space\n");
4477 return STATUS_INVALID_PARAMETER_2
;
4481 // Make sure the allocation wouldn't overflow past the user area
4483 if (((ULONG_PTR
)MM_HIGHEST_USER_ADDRESS
- (ULONG_PTR
)PBaseAddress
) < PRegionSize
)
4485 DPRINT1("Region size would overflow into kernel-memory\n");
4486 return STATUS_INVALID_PARAMETER_3
;
4490 // If this is for the current process, just use PsGetCurrentProcess
4492 if (ProcessHandle
== NtCurrentProcess())
4494 Process
= CurrentProcess
;
4499 // Otherwise, reference the process with VM rights and attach to it if
4500 // this isn't the current process. We must attach because we'll be touching
4501 // PTEs and PDEs that belong to user-mode memory, and also touching the
4502 // Working Set which is stored in Hyperspace.
4504 Status
= ObReferenceObjectByHandle(ProcessHandle
,
4505 PROCESS_VM_OPERATION
,
4510 if (!NT_SUCCESS(Status
)) return Status
;
4511 if (CurrentProcess
!= Process
)
4513 KeStackAttachProcess(&Process
->Pcb
, &ApcState
);
4519 // Lock the address space
4521 AddressSpace
= MmGetCurrentAddressSpace();
4522 MmLockAddressSpace(AddressSpace
);
4525 // If the address space is being deleted, fail the de-allocation since it's
4526 // too late to do anything about it
4528 if (Process
->VmDeleted
)
4530 DPRINT1("Process is dead\n");
4531 Status
= STATUS_PROCESS_IS_TERMINATING
;
4536 // Compute start and end addresses, and locate the VAD
4538 StartingAddress
= (ULONG_PTR
)PAGE_ALIGN(PBaseAddress
);
4539 EndingAddress
= ((ULONG_PTR
)PBaseAddress
+ PRegionSize
- 1) | (PAGE_SIZE
- 1);
4540 Vad
= MiLocateAddress((PVOID
)StartingAddress
);
4543 DPRINT1("Unable to find VAD for address 0x%p\n", StartingAddress
);
4544 Status
= STATUS_MEMORY_NOT_ALLOCATED
;
4549 // If the range exceeds the VAD's ending VPN, fail this request
4551 if (Vad
->EndingVpn
< (EndingAddress
>> PAGE_SHIFT
))
4553 DPRINT1("Address 0x%p is beyond the VAD\n", EndingAddress
);
4554 Status
= STATUS_UNABLE_TO_FREE_VM
;
4559 // Only private memory (except rotate VADs) can be freed through here */
4561 if ((!(Vad
->u
.VadFlags
.PrivateMemory
) &&
4562 (Vad
->u
.VadFlags
.VadType
!= VadRotatePhysical
)) ||
4563 (Vad
->u
.VadFlags
.VadType
== VadDevicePhysicalMemory
))
4565 DPRINT1("Attempt to free section memory\n");
4566 Status
= STATUS_UNABLE_TO_DELETE_SECTION
;
4571 // ARM3 does not yet handle protected VM
4573 ASSERT(Vad
->u
.VadFlags
.NoChange
== 0);
4576 // Finally, make sure there is a ReactOS Mm MEMORY_AREA for this allocation
4577 // and that is is an ARM3 memory area, and not a section view, as we currently
4578 // don't support freeing those though this interface.
4580 MemoryArea
= MmLocateMemoryAreaByAddress(AddressSpace
, (PVOID
)StartingAddress
);
4582 ASSERT(MemoryArea
->Type
== MEMORY_AREA_OWNED_BY_ARM3
);
4585 // Now we can try the operation. First check if this is a RELEASE or a DECOMMIT
4587 if (FreeType
& MEM_RELEASE
)
4590 // ARM3 only supports this VAD in this path
4592 ASSERT(Vad
->u
.VadFlags
.VadType
== VadNone
);
4595 // Is the caller trying to remove the whole VAD, or remove only a portion
4596 // of it? If no region size is specified, then the assumption is that the
4597 // whole VAD is to be destroyed
4602 // The caller must specify the base address identically to the range
4603 // that is stored in the VAD.
4605 if (((ULONG_PTR
)PBaseAddress
>> PAGE_SHIFT
) != Vad
->StartingVpn
)
4607 DPRINT1("Address 0x%p does not match the VAD\n", PBaseAddress
);
4608 Status
= STATUS_FREE_VM_NOT_AT_BASE
;
4613 // Now compute the actual start/end addresses based on the VAD
4615 StartingAddress
= Vad
->StartingVpn
<< PAGE_SHIFT
;
4616 EndingAddress
= (Vad
->EndingVpn
<< PAGE_SHIFT
) | (PAGE_SIZE
- 1);
4619 // Finally lock the working set and remove the VAD from the VAD tree
4621 MiLockProcessWorkingSetUnsafe(Process
, CurrentThread
);
4622 ASSERT(Process
->VadRoot
.NumberGenericTableElements
>= 1);
4623 MiRemoveNode((PMMADDRESS_NODE
)Vad
, &Process
->VadRoot
);
4628 // This means the caller wants to release a specific region within
4629 // the range. We have to find out which range this is -- the following
4630 // possibilities exist plus their union (CASE D):
4632 // STARTING ADDRESS ENDING ADDRESS
4633 // [<========][========================================][=========>]
4634 // CASE A CASE B CASE C
4637 // First, check for case A or D
4639 if ((StartingAddress
>> PAGE_SHIFT
) == Vad
->StartingVpn
)
4644 if ((EndingAddress
>> PAGE_SHIFT
) == Vad
->EndingVpn
)
4647 // This is the easiest one to handle -- it is identical to
4648 // the code path above when the caller sets a zero region size
4649 // and the whole VAD is destroyed
4651 MiLockProcessWorkingSetUnsafe(Process
, CurrentThread
);
4652 ASSERT(Process
->VadRoot
.NumberGenericTableElements
>= 1);
4653 MiRemoveNode((PMMADDRESS_NODE
)Vad
, &Process
->VadRoot
);
4658 // This case is pretty easy too -- we compute a bunch of
4659 // pages to decommit, and then push the VAD's starting address
4660 // a bit further down, then decrement the commit charge
4662 // NOT YET IMPLEMENTED IN ARM3.
4664 DPRINT1("Case A not handled\n");
4665 Status
= STATUS_FREE_VM_NOT_AT_BASE
;
4669 // After analyzing the VAD, set it to NULL so that we don't
4670 // free it in the exit path
4678 // This is case B or case C. First check for case C
4680 if ((EndingAddress
>> PAGE_SHIFT
) == Vad
->EndingVpn
)
4682 PMEMORY_AREA MemoryArea
;
4685 // This is pretty easy and similar to case A. We compute the
4686 // amount of pages to decommit, update the VAD's commit charge
4687 // and then change the ending address of the VAD to be a bit
4690 MiLockProcessWorkingSetUnsafe(Process
, CurrentThread
);
4691 CommitReduction
= MiCalculatePageCommitment(StartingAddress
,
4695 Vad
->u
.VadFlags
.CommitCharge
-= CommitReduction
;
4696 // For ReactOS: shrink the corresponding memory area
4697 MemoryArea
= MmLocateMemoryAreaByAddress(AddressSpace
, (PVOID
)StartingAddress
);
4698 ASSERT(Vad
->StartingVpn
<< PAGE_SHIFT
== (ULONG_PTR
)MemoryArea
->StartingAddress
);
4699 ASSERT((Vad
->EndingVpn
+ 1) << PAGE_SHIFT
== (ULONG_PTR
)MemoryArea
->EndingAddress
);
4700 Vad
->EndingVpn
= ((ULONG_PTR
)StartingAddress
- 1) >> PAGE_SHIFT
;
4701 MemoryArea
->EndingAddress
= (PVOID
)(((Vad
->EndingVpn
+ 1) << PAGE_SHIFT
) - 1);
4706 // This is case B and the hardest one. Because we are removing
4707 // a chunk of memory from the very middle of the VAD, we must
4708 // actually split the VAD into two new VADs and compute the
4709 // commit charges for each of them, and reinsert new charges.
4711 // NOT YET IMPLEMENTED IN ARM3.
4713 DPRINT1("Case B not handled\n");
4714 Status
= STATUS_FREE_VM_NOT_AT_BASE
;
4719 // After analyzing the VAD, set it to NULL so that we don't
4720 // free it in the exit path
4727 // Now we have a range of pages to dereference, so call the right API
4728 // to do that and then release the working set, since we're done messing
4729 // around with process pages.
4731 MiDeleteVirtualAddresses(StartingAddress
, EndingAddress
, NULL
);
4732 MiUnlockProcessWorkingSetUnsafe(Process
, CurrentThread
);
4733 Status
= STATUS_SUCCESS
;
4737 // Update the process counters
4739 PRegionSize
= EndingAddress
- StartingAddress
+ 1;
4740 Process
->CommitCharge
-= CommitReduction
;
4741 if (FreeType
& MEM_RELEASE
) Process
->VirtualSize
-= PRegionSize
;
4744 // Unlock the address space and free the VAD in failure cases. Next,
4745 // detach from the target process so we can write the region size and the
4746 // base address to the correct source process, and dereference the target
4749 MmUnlockAddressSpace(AddressSpace
);
4750 if (Vad
) ExFreePool(Vad
);
4751 if (Attached
) KeUnstackDetachProcess(&ApcState
);
4752 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);
4755 // Use SEH to safely return the region size and the base address of the
4756 // deallocation. If we get an access violation, don't return a failure code
4757 // as the deallocation *has* happened. The caller will just have to figure
4758 // out another way to find out where it is (such as VirtualQuery).
4762 *URegionSize
= PRegionSize
;
4763 *UBaseAddress
= (PVOID
)StartingAddress
;
4765 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER
)
4773 // This is the decommit path. You cannot decommit from the following VADs in
4774 // Windows, so fail the vall
4776 if ((Vad
->u
.VadFlags
.VadType
== VadAwe
) ||
4777 (Vad
->u
.VadFlags
.VadType
== VadLargePages
) ||
4778 (Vad
->u
.VadFlags
.VadType
== VadRotatePhysical
))
4780 DPRINT1("Trying to decommit from invalid VAD\n");
4781 Status
= STATUS_MEMORY_NOT_ALLOCATED
;
4786 // If the caller did not specify a region size, first make sure that this
4787 // region is actually committed. If it is, then compute the ending address
4788 // based on the VAD.
4792 if (((ULONG_PTR
)PBaseAddress
>> PAGE_SHIFT
) != Vad
->StartingVpn
)
4794 DPRINT1("Decomitting non-committed memory\n");
4795 Status
= STATUS_FREE_VM_NOT_AT_BASE
;
4798 EndingAddress
= (Vad
->EndingVpn
<< PAGE_SHIFT
) | (PAGE_SIZE
- 1);
4802 // Decommit the PTEs for the range plus the actual backing pages for the
4803 // range, then reduce that amount from the commit charge in the VAD
4805 CommitReduction
= MiAddressToPte(EndingAddress
) -
4806 MiAddressToPte(StartingAddress
) +
4808 MiDecommitPages((PVOID
)StartingAddress
,
4809 MiAddressToPte(EndingAddress
),
4812 ASSERT(CommitReduction
>= 0);
4813 Vad
->u
.VadFlags
.CommitCharge
-= CommitReduction
;
4814 ASSERT(Vad
->u
.VadFlags
.CommitCharge
>= 0);
4817 // We are done, go to the exit path without freeing the VAD as it remains
4818 // valid since we have not released the allocation.
4821 Status
= STATUS_SUCCESS
;
4825 // In the failure path, we detach and derefernece the target process, and
4826 // return whatever failure code was sent.
4829 MmUnlockAddressSpace(AddressSpace
);
4830 if (Attached
) KeUnstackDetachProcess(&ApcState
);
4831 if (ProcessHandle
!= NtCurrentProcess()) ObDereferenceObject(Process
);