[NTOSKRNL]: Support a few more "unsupported" paths that were hitting ASSERTs before.
[reactos.git] / reactos / ntoskrnl / mm / ARM3 / virtual.c
1 /*
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
7 */
8
9 /* INCLUDES *******************************************************************/
10
11 #include <ntoskrnl.h>
12 #define NDEBUG
13 #include <debug.h>
14
15 #define MODULE_INVOLVED_IN_ARM3
16 #include "../ARM3/miarm.h"
17
18 #define MI_MAPPED_COPY_PAGES 14
19 #define MI_POOL_COPY_BYTES 512
20 #define MI_MAX_TRANSFER_SIZE 64 * 1024
21
22 NTSTATUS NTAPI
23 MiProtectVirtualMemory(IN PEPROCESS Process,
24 IN OUT PVOID *BaseAddress,
25 IN OUT PSIZE_T NumberOfBytesToProtect,
26 IN ULONG NewAccessProtection,
27 OUT PULONG OldAccessProtection OPTIONAL);
28
29 VOID
30 NTAPI
31 MiFlushTbAndCapture(IN PMMVAD FoundVad,
32 IN PMMPTE PointerPte,
33 IN ULONG ProtectionMask,
34 IN PMMPFN Pfn1,
35 IN BOOLEAN CaptureDirtyBit);
36
37
38 /* PRIVATE FUNCTIONS **********************************************************/
39
40 ULONG
41 NTAPI
42 MiCalculatePageCommitment(IN ULONG_PTR StartingAddress,
43 IN ULONG_PTR EndingAddress,
44 IN PMMVAD Vad,
45 IN PEPROCESS Process)
46 {
47 PMMPTE PointerPte, LastPte, PointerPde;
48 ULONG CommittedPages;
49
50 /* Compute starting and ending PTE and PDE addresses */
51 PointerPde = MiAddressToPde(StartingAddress);
52 PointerPte = MiAddressToPte(StartingAddress);
53 LastPte = MiAddressToPte(EndingAddress);
54
55 /* Handle commited pages first */
56 if (Vad->u.VadFlags.MemCommit == 1)
57 {
58 /* This is a committed VAD, so Assume the whole range is committed */
59 CommittedPages = BYTES_TO_PAGES(EndingAddress - StartingAddress);
60
61 /* Is the PDE demand-zero? */
62 PointerPde = MiAddressToPte(PointerPte);
63 if (PointerPde->u.Long != 0)
64 {
65 /* It is not. Is it valid? */
66 if (PointerPde->u.Hard.Valid == 0)
67 {
68 /* Fault it in */
69 PointerPte = MiPteToAddress(PointerPde);
70 MiMakeSystemAddressValid(PointerPte, Process);
71 }
72 }
73 else
74 {
75 /* It is, skip it and move to the next PDE, unless we're done */
76 PointerPde++;
77 PointerPte = MiPteToAddress(PointerPde);
78 if (PointerPte > LastPte) return CommittedPages;
79 }
80
81 /* Now loop all the PTEs in the range */
82 while (PointerPte <= LastPte)
83 {
84 /* Have we crossed a PDE boundary? */
85 if (MiIsPteOnPdeBoundary(PointerPte))
86 {
87 /* Is this PDE demand zero? */
88 PointerPde = MiAddressToPte(PointerPte);
89 if (PointerPde->u.Long != 0)
90 {
91 /* It isn't -- is it valid? */
92 if (PointerPde->u.Hard.Valid == 0)
93 {
94 /* Nope, fault it in */
95 PointerPte = MiPteToAddress(PointerPde);
96 MiMakeSystemAddressValid(PointerPte, Process);
97 }
98 }
99 else
100 {
101 /* It is, skip it and move to the next PDE */
102 PointerPde++;
103 PointerPte = MiPteToAddress(PointerPde);
104 continue;
105 }
106 }
107
108 /* Is this PTE demand zero? */
109 if (PointerPte->u.Long != 0)
110 {
111 /* It isn't -- is it a decommited, invalid, or faulted PTE? */
112 if ((PointerPte->u.Soft.Protection == MM_DECOMMIT) &&
113 (PointerPte->u.Hard.Valid == 0) &&
114 ((PointerPte->u.Soft.Prototype == 0) ||
115 (PointerPte->u.Soft.PageFileHigh == MI_PTE_LOOKUP_NEEDED)))
116 {
117 /* It is, so remove it from the count of commited pages */
118 CommittedPages--;
119 }
120 }
121
122 /* Move to the next PTE */
123 PointerPte++;
124 }
125
126 /* Return how many committed pages there still are */
127 return CommittedPages;
128 }
129
130 /* This is a non-commited VAD, so assume none of it is committed */
131 CommittedPages = 0;
132
133 /* Is the PDE demand-zero? */
134 PointerPde = MiAddressToPte(PointerPte);
135 if (PointerPde->u.Long != 0)
136 {
137 /* It isn't -- is it invalid? */
138 if (PointerPde->u.Hard.Valid == 0)
139 {
140 /* It is, so page it in */
141 PointerPte = MiPteToAddress(PointerPde);
142 MiMakeSystemAddressValid(PointerPte, Process);
143 }
144 }
145 else
146 {
147 /* It is, so skip it and move to the next PDE */
148 PointerPde++;
149 PointerPte = MiPteToAddress(PointerPde);
150 if (PointerPte > LastPte) return CommittedPages;
151 }
152
153 /* Loop all the PTEs in this PDE */
154 while (PointerPte <= LastPte)
155 {
156 /* Have we crossed a PDE boundary? */
157 if (MiIsPteOnPdeBoundary(PointerPte))
158 {
159 /* Is this new PDE demand-zero? */
160 PointerPde = MiAddressToPte(PointerPte);
161 if (PointerPde->u.Long != 0)
162 {
163 /* It isn't. Is it valid? */
164 if (PointerPde->u.Hard.Valid == 0)
165 {
166 /* It isn't, so make it valid */
167 PointerPte = MiPteToAddress(PointerPde);
168 MiMakeSystemAddressValid(PointerPte, Process);
169 }
170 }
171 else
172 {
173 /* It is, so skip it and move to the next one */
174 PointerPde++;
175 PointerPte = MiPteToAddress(PointerPde);
176 continue;
177 }
178 }
179
180 /* Is this PTE demand-zero? */
181 if (PointerPte->u.Long != 0)
182 {
183 /* Nope. Is it a valid, non-decommited, non-paged out PTE? */
184 if ((PointerPte->u.Soft.Protection != MM_DECOMMIT) ||
185 (PointerPte->u.Hard.Valid == 1) ||
186 ((PointerPte->u.Soft.Prototype == 1) &&
187 (PointerPte->u.Soft.PageFileHigh != MI_PTE_LOOKUP_NEEDED)))
188 {
189 /* It is! So we'll treat this as a committed page */
190 CommittedPages++;
191 }
192 }
193
194 /* Move to the next PTE */
195 PointerPte++;
196 }
197
198 /* Return how many committed pages we found in this VAD */
199 return CommittedPages;
200 }
201
202 ULONG
203 NTAPI
204 MiMakeSystemAddressValid(IN PVOID PageTableVirtualAddress,
205 IN PEPROCESS CurrentProcess)
206 {
207 NTSTATUS Status;
208 BOOLEAN WsWasLocked = FALSE, LockChange = FALSE;
209 PETHREAD CurrentThread = PsGetCurrentThread();
210
211 /* Must be a non-pool page table, since those are double-mapped already */
212 ASSERT(PageTableVirtualAddress > MM_HIGHEST_USER_ADDRESS);
213 ASSERT((PageTableVirtualAddress < MmPagedPoolStart) ||
214 (PageTableVirtualAddress > MmPagedPoolEnd));
215
216 /* Working set lock or PFN lock should be held */
217 ASSERT(KeAreAllApcsDisabled() == TRUE);
218
219 /* Check if the page table is valid */
220 while (!MmIsAddressValid(PageTableVirtualAddress))
221 {
222 /* Check if the WS is locked */
223 if (CurrentThread->OwnsProcessWorkingSetExclusive)
224 {
225 /* Unlock the working set and remember it was locked */
226 MiUnlockProcessWorkingSet(CurrentProcess, CurrentThread);
227 WsWasLocked = TRUE;
228 }
229
230 /* Fault it in */
231 Status = MmAccessFault(FALSE, PageTableVirtualAddress, KernelMode, NULL);
232 if (!NT_SUCCESS(Status))
233 {
234 /* This should not fail */
235 KeBugCheckEx(KERNEL_DATA_INPAGE_ERROR,
236 1,
237 Status,
238 (ULONG_PTR)CurrentProcess,
239 (ULONG_PTR)PageTableVirtualAddress);
240 }
241
242 /* Lock the working set again */
243 if (WsWasLocked) MiLockProcessWorkingSet(CurrentProcess, CurrentThread);
244
245 /* This flag will be useful later when we do better locking */
246 LockChange = TRUE;
247 }
248
249 /* Let caller know what the lock state is */
250 return LockChange;
251 }
252
253 ULONG
254 NTAPI
255 MiMakeSystemAddressValidPfn(IN PVOID VirtualAddress,
256 IN KIRQL OldIrql)
257 {
258 NTSTATUS Status;
259 BOOLEAN LockChange = FALSE;
260
261 /* Must be e kernel address */
262 ASSERT(VirtualAddress > MM_HIGHEST_USER_ADDRESS);
263
264 /* Check if the page is valid */
265 while (!MmIsAddressValid(VirtualAddress))
266 {
267 /* Release the PFN database */
268 KeReleaseQueuedSpinLock(LockQueuePfnLock, OldIrql);
269
270 /* Fault it in */
271 Status = MmAccessFault(FALSE, VirtualAddress, KernelMode, NULL);
272 if (!NT_SUCCESS(Status))
273 {
274 /* This should not fail */
275 KeBugCheckEx(KERNEL_DATA_INPAGE_ERROR,
276 3,
277 Status,
278 0,
279 (ULONG_PTR)VirtualAddress);
280 }
281
282 /* This flag will be useful later when we do better locking */
283 LockChange = TRUE;
284
285 /* Lock the PFN database */
286 OldIrql = KeAcquireQueuedSpinLock(LockQueuePfnLock);
287 }
288
289 /* Let caller know what the lock state is */
290 return LockChange;
291 }
292
293 PFN_COUNT
294 NTAPI
295 MiDeleteSystemPageableVm(IN PMMPTE PointerPte,
296 IN PFN_NUMBER PageCount,
297 IN ULONG Flags,
298 OUT PPFN_NUMBER ValidPages)
299 {
300 PFN_COUNT ActualPages = 0;
301 PETHREAD CurrentThread = PsGetCurrentThread();
302 PMMPFN Pfn1, Pfn2;
303 PFN_NUMBER PageFrameIndex, PageTableIndex;
304 KIRQL OldIrql;
305 ASSERT(KeGetCurrentIrql() <= APC_LEVEL);
306
307 /* Lock the system working set */
308 MiLockWorkingSet(CurrentThread, &MmSystemCacheWs);
309
310 /* Loop all pages */
311 while (PageCount)
312 {
313 /* Make sure there's some data about the page */
314 if (PointerPte->u.Long)
315 {
316 /* As always, only handle current ARM3 scenarios */
317 ASSERT(PointerPte->u.Soft.Prototype == 0);
318 ASSERT(PointerPte->u.Soft.Transition == 0);
319
320 /* Normally this is one possibility -- freeing a valid page */
321 if (PointerPte->u.Hard.Valid)
322 {
323 /* Get the page PFN */
324 PageFrameIndex = PFN_FROM_PTE(PointerPte);
325 Pfn1 = MiGetPfnEntry(PageFrameIndex);
326
327 /* Should not have any working set data yet */
328 ASSERT(Pfn1->u1.WsIndex == 0);
329
330 /* Actual valid, legitimate, pages */
331 if (ValidPages) (*ValidPages)++;
332
333 /* Get the page table entry */
334 PageTableIndex = Pfn1->u4.PteFrame;
335 Pfn2 = MiGetPfnEntry(PageTableIndex);
336
337 /* Lock the PFN database */
338 OldIrql = KeAcquireQueuedSpinLock(LockQueuePfnLock);
339
340 /* Delete it the page */
341 MI_SET_PFN_DELETED(Pfn1);
342 MiDecrementShareCount(Pfn1, PageFrameIndex);
343
344 /* Decrement the page table too */
345 MiDecrementShareCount(Pfn2, PageTableIndex);
346
347 /* Release the PFN database */
348 KeReleaseQueuedSpinLock(LockQueuePfnLock, OldIrql);
349
350 /* Destroy the PTE */
351 PointerPte->u.Long = 0;
352 }
353
354 /* Actual legitimate pages */
355 ActualPages++;
356 }
357 else
358 {
359 /*
360 * The only other ARM3 possibility is a demand zero page, which would
361 * mean freeing some of the paged pool pages that haven't even been
362 * touched yet, as part of a larger allocation.
363 *
364 * Right now, we shouldn't expect any page file information in the PTE
365 */
366 ASSERT(PointerPte->u.Soft.PageFileHigh == 0);
367
368 /* Destroy the PTE */
369 PointerPte->u.Long = 0;
370 }
371
372 /* Keep going */
373 PointerPte++;
374 PageCount--;
375 }
376
377 /* Release the working set */
378 MiUnlockWorkingSet(CurrentThread, &MmSystemCacheWs);
379
380 /* Flush the entire TLB */
381 KeFlushEntireTb(TRUE, TRUE);
382
383 /* Done */
384 return ActualPages;
385 }
386
387 VOID
388 NTAPI
389 MiDeletePte(IN PMMPTE PointerPte,
390 IN PVOID VirtualAddress,
391 IN PEPROCESS CurrentProcess,
392 IN PMMPTE PrototypePte)
393 {
394 PMMPFN Pfn1;
395 MMPTE TempPte;
396 PFN_NUMBER PageFrameIndex;
397 PMMPDE PointerPde;
398
399 /* PFN lock must be held */
400 ASSERT(KeGetCurrentIrql() == DISPATCH_LEVEL);
401
402 /* Capture the PTE */
403 TempPte = *PointerPte;
404
405 /* We only support valid PTEs for now */
406 ASSERT(TempPte.u.Hard.Valid == 1);
407 if (TempPte.u.Hard.Valid == 0)
408 {
409 /* Invalid PTEs not supported yet */
410 ASSERT(TempPte.u.Soft.Prototype == 0);
411 ASSERT(TempPte.u.Soft.Transition == 0);
412 }
413
414 /* Get the PFN entry */
415 PageFrameIndex = PFN_FROM_PTE(&TempPte);
416 Pfn1 = MiGetPfnEntry(PageFrameIndex);
417
418 /* Check if this is a valid, prototype PTE */
419 if (Pfn1->u3.e1.PrototypePte == 1)
420 {
421 /* Get the PDE and make sure it's faulted in */
422 PointerPde = MiPteToPde(PointerPte);
423 if (PointerPde->u.Hard.Valid == 0)
424 {
425 #if (_MI_PAGING_LEVELS == 2)
426 /* Could be paged pool access from a new process -- synchronize the page directories */
427 if (!NT_SUCCESS(MiCheckPdeForPagedPool(VirtualAddress)))
428 {
429 #endif
430 /* The PDE must be valid at this point */
431 KeBugCheckEx(MEMORY_MANAGEMENT,
432 0x61940,
433 (ULONG_PTR)PointerPte,
434 PointerPte->u.Long,
435 (ULONG_PTR)VirtualAddress);
436 }
437 #if (_MI_PAGING_LEVELS == 2)
438 }
439 #endif
440 /* Drop the share count */
441 MiDecrementShareCount(Pfn1, PageFrameIndex);
442
443 /* Either a fork, or this is the shared user data page */
444 if ((PointerPte <= MiHighestUserPte) && (PrototypePte != Pfn1->PteAddress))
445 {
446 /* If it's not the shared user page, then crash, since there's no fork() yet */
447 if ((PAGE_ALIGN(VirtualAddress) != (PVOID)USER_SHARED_DATA) ||
448 (MmHighestUserAddress <= (PVOID)USER_SHARED_DATA))
449 {
450 /* Must be some sort of memory corruption */
451 KeBugCheckEx(MEMORY_MANAGEMENT,
452 0x400,
453 (ULONG_PTR)PointerPte,
454 (ULONG_PTR)PrototypePte,
455 (ULONG_PTR)Pfn1->PteAddress);
456 }
457 }
458 }
459 else
460 {
461 /* Make sure the saved PTE address is valid */
462 if ((PMMPTE)((ULONG_PTR)Pfn1->PteAddress & ~0x1) != PointerPte)
463 {
464 /* The PFN entry is illegal, or invalid */
465 KeBugCheckEx(MEMORY_MANAGEMENT,
466 0x401,
467 (ULONG_PTR)PointerPte,
468 PointerPte->u.Long,
469 (ULONG_PTR)Pfn1->PteAddress);
470 }
471
472 /* There should only be 1 shared reference count */
473 ASSERT(Pfn1->u2.ShareCount == 1);
474
475 /* Drop the reference on the page table. */
476 MiDecrementShareCount(MiGetPfnEntry(Pfn1->u4.PteFrame), Pfn1->u4.PteFrame);
477
478 /* Mark the PFN for deletion and dereference what should be the last ref */
479 MI_SET_PFN_DELETED(Pfn1);
480 MiDecrementShareCount(Pfn1, PageFrameIndex);
481
482 /* We should eventually do this */
483 //CurrentProcess->NumberOfPrivatePages--;
484 }
485
486 /* Destroy the PTE and flush the TLB */
487 PointerPte->u.Long = 0;
488 KeFlushCurrentTb();
489 }
490
491 VOID
492 NTAPI
493 MiDeleteVirtualAddresses(IN ULONG_PTR Va,
494 IN ULONG_PTR EndingAddress,
495 IN PMMVAD Vad)
496 {
497 PMMPTE PointerPte, PrototypePte, LastPrototypePte;
498 PMMPDE PointerPde;
499 MMPTE TempPte;
500 PEPROCESS CurrentProcess;
501 KIRQL OldIrql;
502 BOOLEAN AddressGap = FALSE;
503 PSUBSECTION Subsection;
504 PUSHORT UsedPageTableEntries;
505
506 /* Get out if this is a fake VAD, RosMm will free the marea pages */
507 if ((Vad) && (Vad->u.VadFlags.Spare == 1)) return;
508
509 /* Grab the process and PTE/PDE for the address being deleted */
510 CurrentProcess = PsGetCurrentProcess();
511 PointerPde = MiAddressToPde(Va);
512 PointerPte = MiAddressToPte(Va);
513
514 /* Check if this is a section VAD or a VM VAD */
515 if (!(Vad) || (Vad->u.VadFlags.PrivateMemory) || !(Vad->FirstPrototypePte))
516 {
517 /* Don't worry about prototypes */
518 PrototypePte = LastPrototypePte = NULL;
519 }
520 else
521 {
522 /* Get the prototype PTE */
523 PrototypePte = Vad->FirstPrototypePte;
524 LastPrototypePte = Vad->FirstPrototypePte + 1;
525 }
526
527 /* In all cases, we don't support fork() yet */
528 ASSERT(CurrentProcess->CloneRoot == NULL);
529
530 /* Loop the PTE for each VA */
531 while (TRUE)
532 {
533 /* First keep going until we find a valid PDE */
534 while (!PointerPde->u.Long)
535 {
536 /* There are gaps in the address space */
537 AddressGap = TRUE;
538
539 /* Still no valid PDE, try the next 4MB (or whatever) */
540 PointerPde++;
541
542 /* Update the PTE on this new boundary */
543 PointerPte = MiPteToAddress(PointerPde);
544
545 /* Check if all the PDEs are invalid, so there's nothing to free */
546 Va = (ULONG_PTR)MiPteToAddress(PointerPte);
547 if (Va > EndingAddress) return;
548 }
549
550 /* Now check if the PDE is mapped in */
551 if (!PointerPde->u.Hard.Valid)
552 {
553 /* It isn't, so map it in */
554 PointerPte = MiPteToAddress(PointerPde);
555 MiMakeSystemAddressValid(PointerPte, CurrentProcess);
556 }
557
558 /* Now we should have a valid PDE, mapped in, and still have some VA */
559 ASSERT(PointerPde->u.Hard.Valid == 1);
560 ASSERT(Va <= EndingAddress);
561 UsedPageTableEntries = &MmWorkingSetList->UsedPageTableEntries[MiGetPdeOffset(Va)];
562
563 /* Check if this is a section VAD with gaps in it */
564 if ((AddressGap) && (LastPrototypePte))
565 {
566 /* We need to skip to the next correct prototype PTE */
567 PrototypePte = MI_GET_PROTOTYPE_PTE_FOR_VPN(Vad, Va >> PAGE_SHIFT);
568
569 /* And we need the subsection to skip to the next last prototype PTE */
570 Subsection = MiLocateSubsection(Vad, Va >> PAGE_SHIFT);
571 if (Subsection)
572 {
573 /* Found it! */
574 LastPrototypePte = &Subsection->SubsectionBase[Subsection->PtesInSubsection];
575 }
576 else
577 {
578 /* No more subsections, we are done with prototype PTEs */
579 PrototypePte = NULL;
580 }
581 }
582
583 /* Lock the PFN Database while we delete the PTEs */
584 OldIrql = KeAcquireQueuedSpinLock(LockQueuePfnLock);
585 do
586 {
587 /* Capture the PDE and make sure it exists */
588 TempPte = *PointerPte;
589 if (TempPte.u.Long)
590 {
591 DPRINT("Decrement used PTEs by address: %lx\n", Va);
592 (*UsedPageTableEntries)--;
593 ASSERT((*UsedPageTableEntries) < PTE_COUNT);
594 DPRINT("Refs: %lx\n", (*UsedPageTableEntries));
595
596 /* Check if the PTE is actually mapped in */
597 if (TempPte.u.Long & 0xFFFFFC01)
598 {
599 /* Are we dealing with section VAD? */
600 if ((LastPrototypePte) && (PrototypePte > LastPrototypePte))
601 {
602 /* We need to skip to the next correct prototype PTE */
603 PrototypePte = MI_GET_PROTOTYPE_PTE_FOR_VPN(Vad, Va >> PAGE_SHIFT);
604
605 /* And we need the subsection to skip to the next last prototype PTE */
606 Subsection = MiLocateSubsection(Vad, Va >> PAGE_SHIFT);
607 if (Subsection)
608 {
609 /* Found it! */
610 LastPrototypePte = &Subsection->SubsectionBase[Subsection->PtesInSubsection];
611 }
612 else
613 {
614 /* No more subsections, we are done with prototype PTEs */
615 PrototypePte = NULL;
616 }
617 }
618
619 /* Check for prototype PTE */
620 if ((TempPte.u.Hard.Valid == 0) &&
621 (TempPte.u.Soft.Prototype == 1))
622 {
623 /* Just nuke it */
624 PointerPte->u.Long = 0;
625 }
626 else
627 {
628 /* Delete the PTE proper */
629 MiDeletePte(PointerPte,
630 (PVOID)Va,
631 CurrentProcess,
632 PrototypePte);
633 }
634 }
635 else
636 {
637 /* The PTE was never mapped, just nuke it here */
638 PointerPte->u.Long = 0;
639 }
640 }
641
642 /* Update the address and PTE for it */
643 Va += PAGE_SIZE;
644 PointerPte++;
645 PrototypePte++;
646
647 /* Making sure the PDE is still valid */
648 ASSERT(PointerPde->u.Hard.Valid == 1);
649 }
650 while ((Va & (PDE_MAPPED_VA - 1)) && (Va <= EndingAddress));
651
652 /* The PDE should still be valid at this point */
653 ASSERT(PointerPde->u.Hard.Valid == 1);
654
655 DPRINT("Should check if handles for: %p are zero (PDE: %lx)\n", Va, PointerPde->u.Hard.PageFrameNumber);
656 if (!(*UsedPageTableEntries))
657 {
658 DPRINT("They are!\n");
659 if (PointerPde->u.Long != 0)
660 {
661 DPRINT("PDE active: %lx in %16s\n", PointerPde->u.Hard.PageFrameNumber, CurrentProcess->ImageFileName);
662
663 /* Delete the PTE proper */
664 MiDeletePte(PointerPde,
665 MiPteToAddress(PointerPde),
666 CurrentProcess,
667 NULL);
668 }
669 }
670
671 /* Release the lock and get out if we're done */
672 KeReleaseQueuedSpinLock(LockQueuePfnLock, OldIrql);
673 if (Va > EndingAddress) return;
674
675 /* Otherwise, we exited because we hit a new PDE boundary, so start over */
676 PointerPde = MiAddressToPde(Va);
677 AddressGap = FALSE;
678 }
679 }
680
681 LONG
682 MiGetExceptionInfo(IN PEXCEPTION_POINTERS ExceptionInfo,
683 OUT PBOOLEAN HaveBadAddress,
684 OUT PULONG_PTR BadAddress)
685 {
686 PEXCEPTION_RECORD ExceptionRecord;
687 PAGED_CODE();
688
689 //
690 // Assume default
691 //
692 *HaveBadAddress = FALSE;
693
694 //
695 // Get the exception record
696 //
697 ExceptionRecord = ExceptionInfo->ExceptionRecord;
698
699 //
700 // Look at the exception code
701 //
702 if ((ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION) ||
703 (ExceptionRecord->ExceptionCode == STATUS_GUARD_PAGE_VIOLATION) ||
704 (ExceptionRecord->ExceptionCode == STATUS_IN_PAGE_ERROR))
705 {
706 //
707 // We can tell the address if we have more than one parameter
708 //
709 if (ExceptionRecord->NumberParameters > 1)
710 {
711 //
712 // Return the address
713 //
714 *HaveBadAddress = TRUE;
715 *BadAddress = ExceptionRecord->ExceptionInformation[1];
716 }
717 }
718
719 //
720 // Continue executing the next handler
721 //
722 return EXCEPTION_EXECUTE_HANDLER;
723 }
724
725 NTSTATUS
726 NTAPI
727 MiDoMappedCopy(IN PEPROCESS SourceProcess,
728 IN PVOID SourceAddress,
729 IN PEPROCESS TargetProcess,
730 OUT PVOID TargetAddress,
731 IN SIZE_T BufferSize,
732 IN KPROCESSOR_MODE PreviousMode,
733 OUT PSIZE_T ReturnSize)
734 {
735 PFN_NUMBER MdlBuffer[(sizeof(MDL) / sizeof(PFN_NUMBER)) + MI_MAPPED_COPY_PAGES + 1];
736 PMDL Mdl = (PMDL)MdlBuffer;
737 SIZE_T TotalSize, CurrentSize, RemainingSize;
738 volatile BOOLEAN FailedInProbe = FALSE, FailedInMapping = FALSE, FailedInMoving;
739 volatile BOOLEAN PagesLocked;
740 PVOID CurrentAddress = SourceAddress, CurrentTargetAddress = TargetAddress;
741 volatile PVOID MdlAddress;
742 KAPC_STATE ApcState;
743 BOOLEAN HaveBadAddress;
744 ULONG_PTR BadAddress;
745 NTSTATUS Status = STATUS_SUCCESS;
746 PAGED_CODE();
747
748 //
749 // Calculate the maximum amount of data to move
750 //
751 TotalSize = MI_MAPPED_COPY_PAGES * PAGE_SIZE;
752 if (BufferSize <= TotalSize) TotalSize = BufferSize;
753 CurrentSize = TotalSize;
754 RemainingSize = BufferSize;
755
756 //
757 // Loop as long as there is still data
758 //
759 while (RemainingSize > 0)
760 {
761 //
762 // Check if this transfer will finish everything off
763 //
764 if (RemainingSize < CurrentSize) CurrentSize = RemainingSize;
765
766 //
767 // Attach to the source address space
768 //
769 KeStackAttachProcess(&SourceProcess->Pcb, &ApcState);
770
771 //
772 // Reset state for this pass
773 //
774 MdlAddress = NULL;
775 PagesLocked = FALSE;
776 FailedInMoving = FALSE;
777 ASSERT(FailedInProbe == FALSE);
778
779 //
780 // Protect user-mode copy
781 //
782 _SEH2_TRY
783 {
784 //
785 // If this is our first time, probe the buffer
786 //
787 if ((CurrentAddress == SourceAddress) && (PreviousMode != KernelMode))
788 {
789 //
790 // Catch a failure here
791 //
792 FailedInProbe = TRUE;
793
794 //
795 // Do the probe
796 //
797 ProbeForRead(SourceAddress, BufferSize, sizeof(CHAR));
798
799 //
800 // Passed
801 //
802 FailedInProbe = FALSE;
803 }
804
805 //
806 // Initialize and probe and lock the MDL
807 //
808 MmInitializeMdl(Mdl, CurrentAddress, CurrentSize);
809 MmProbeAndLockPages(Mdl, PreviousMode, IoReadAccess);
810 PagesLocked = TRUE;
811
812 //
813 // Now map the pages
814 //
815 MdlAddress = MmMapLockedPagesSpecifyCache(Mdl,
816 KernelMode,
817 MmCached,
818 NULL,
819 FALSE,
820 HighPagePriority);
821 if (!MdlAddress)
822 {
823 //
824 // Use our SEH handler to pick this up
825 //
826 FailedInMapping = TRUE;
827 ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES);
828 }
829
830 //
831 // Now let go of the source and grab to the target process
832 //
833 KeUnstackDetachProcess(&ApcState);
834 KeStackAttachProcess(&TargetProcess->Pcb, &ApcState);
835
836 //
837 // Check if this is our first time through
838 //
839 if ((CurrentAddress == SourceAddress) && (PreviousMode != KernelMode))
840 {
841 //
842 // Catch a failure here
843 //
844 FailedInProbe = TRUE;
845
846 //
847 // Do the probe
848 //
849 ProbeForWrite(TargetAddress, BufferSize, sizeof(CHAR));
850
851 //
852 // Passed
853 //
854 FailedInProbe = FALSE;
855 }
856
857 //
858 // Now do the actual move
859 //
860 FailedInMoving = TRUE;
861 RtlCopyMemory(CurrentTargetAddress, MdlAddress, CurrentSize);
862 }
863 _SEH2_EXCEPT(MiGetExceptionInfo(_SEH2_GetExceptionInformation(),
864 &HaveBadAddress,
865 &BadAddress))
866 {
867 //
868 // Detach from whoever we may be attached to
869 //
870 KeUnstackDetachProcess(&ApcState);
871
872 //
873 // Check if we had mapped the pages
874 //
875 if (MdlAddress) MmUnmapLockedPages(MdlAddress, Mdl);
876
877 //
878 // Check if we had locked the pages
879 //
880 if (PagesLocked) MmUnlockPages(Mdl);
881
882 //
883 // Check if we hit working set quota
884 //
885 if (_SEH2_GetExceptionCode() == STATUS_WORKING_SET_QUOTA)
886 {
887 //
888 // Return the error
889 //
890 return STATUS_WORKING_SET_QUOTA;
891 }
892
893 //
894 // Check if we failed during the probe or mapping
895 //
896 if ((FailedInProbe) || (FailedInMapping))
897 {
898 //
899 // Exit
900 //
901 Status = _SEH2_GetExceptionCode();
902 _SEH2_YIELD(return Status);
903 }
904
905 //
906 // Otherwise, we failed probably during the move
907 //
908 *ReturnSize = BufferSize - RemainingSize;
909 if (FailedInMoving)
910 {
911 //
912 // Check if we know exactly where we stopped copying
913 //
914 if (HaveBadAddress)
915 {
916 //
917 // Return the exact number of bytes copied
918 //
919 *ReturnSize = BadAddress - (ULONG_PTR)SourceAddress;
920 }
921 }
922
923 //
924 // Return partial copy
925 //
926 Status = STATUS_PARTIAL_COPY;
927 }
928 _SEH2_END;
929
930 //
931 // Check for SEH status
932 //
933 if (Status != STATUS_SUCCESS) return Status;
934
935 //
936 // Detach from target
937 //
938 KeUnstackDetachProcess(&ApcState);
939
940 //
941 // Unmap and unlock
942 //
943 MmUnmapLockedPages(MdlAddress, Mdl);
944 MmUnlockPages(Mdl);
945
946 //
947 // Update location and size
948 //
949 RemainingSize -= CurrentSize;
950 CurrentAddress = (PVOID)((ULONG_PTR)CurrentAddress + CurrentSize);
951 CurrentTargetAddress = (PVOID)((ULONG_PTR)CurrentTargetAddress + CurrentSize);
952 }
953
954 //
955 // All bytes read
956 //
957 *ReturnSize = BufferSize;
958 return STATUS_SUCCESS;
959 }
960
961 NTSTATUS
962 NTAPI
963 MiDoPoolCopy(IN PEPROCESS SourceProcess,
964 IN PVOID SourceAddress,
965 IN PEPROCESS TargetProcess,
966 OUT PVOID TargetAddress,
967 IN SIZE_T BufferSize,
968 IN KPROCESSOR_MODE PreviousMode,
969 OUT PSIZE_T ReturnSize)
970 {
971 UCHAR StackBuffer[MI_POOL_COPY_BYTES];
972 SIZE_T TotalSize, CurrentSize, RemainingSize;
973 volatile BOOLEAN FailedInProbe = FALSE, FailedInMoving, HavePoolAddress = FALSE;
974 PVOID CurrentAddress = SourceAddress, CurrentTargetAddress = TargetAddress;
975 PVOID PoolAddress;
976 KAPC_STATE ApcState;
977 BOOLEAN HaveBadAddress;
978 ULONG_PTR BadAddress;
979 NTSTATUS Status = STATUS_SUCCESS;
980 PAGED_CODE();
981
982 //
983 // Calculate the maximum amount of data to move
984 //
985 TotalSize = MI_MAX_TRANSFER_SIZE;
986 if (BufferSize <= MI_MAX_TRANSFER_SIZE) TotalSize = BufferSize;
987 CurrentSize = TotalSize;
988 RemainingSize = BufferSize;
989
990 //
991 // Check if we can use the stack
992 //
993 if (BufferSize <= MI_POOL_COPY_BYTES)
994 {
995 //
996 // Use it
997 //
998 PoolAddress = (PVOID)StackBuffer;
999 }
1000 else
1001 {
1002 //
1003 // Allocate pool
1004 //
1005 PoolAddress = ExAllocatePoolWithTag(NonPagedPool, TotalSize, 'VmRw');
1006 if (!PoolAddress) ASSERT(FALSE);
1007 HavePoolAddress = TRUE;
1008 }
1009
1010 //
1011 // Loop as long as there is still data
1012 //
1013 while (RemainingSize > 0)
1014 {
1015 //
1016 // Check if this transfer will finish everything off
1017 //
1018 if (RemainingSize < CurrentSize) CurrentSize = RemainingSize;
1019
1020 //
1021 // Attach to the source address space
1022 //
1023 KeStackAttachProcess(&SourceProcess->Pcb, &ApcState);
1024
1025 //
1026 // Reset state for this pass
1027 //
1028 FailedInMoving = FALSE;
1029 ASSERT(FailedInProbe == FALSE);
1030
1031 //
1032 // Protect user-mode copy
1033 //
1034 _SEH2_TRY
1035 {
1036 //
1037 // If this is our first time, probe the buffer
1038 //
1039 if ((CurrentAddress == SourceAddress) && (PreviousMode != KernelMode))
1040 {
1041 //
1042 // Catch a failure here
1043 //
1044 FailedInProbe = TRUE;
1045
1046 //
1047 // Do the probe
1048 //
1049 ProbeForRead(SourceAddress, BufferSize, sizeof(CHAR));
1050
1051 //
1052 // Passed
1053 //
1054 FailedInProbe = FALSE;
1055 }
1056
1057 //
1058 // Do the copy
1059 //
1060 RtlCopyMemory(PoolAddress, CurrentAddress, CurrentSize);
1061
1062 //
1063 // Now let go of the source and grab to the target process
1064 //
1065 KeUnstackDetachProcess(&ApcState);
1066 KeStackAttachProcess(&TargetProcess->Pcb, &ApcState);
1067
1068 //
1069 // Check if this is our first time through
1070 //
1071 if ((CurrentAddress == SourceAddress) && (PreviousMode != KernelMode))
1072 {
1073 //
1074 // Catch a failure here
1075 //
1076 FailedInProbe = TRUE;
1077
1078 //
1079 // Do the probe
1080 //
1081 ProbeForWrite(TargetAddress, BufferSize, sizeof(CHAR));
1082
1083 //
1084 // Passed
1085 //
1086 FailedInProbe = FALSE;
1087 }
1088
1089 //
1090 // Now do the actual move
1091 //
1092 FailedInMoving = TRUE;
1093 RtlCopyMemory(CurrentTargetAddress, PoolAddress, CurrentSize);
1094 }
1095 _SEH2_EXCEPT(MiGetExceptionInfo(_SEH2_GetExceptionInformation(),
1096 &HaveBadAddress,
1097 &BadAddress))
1098 {
1099 //
1100 // Detach from whoever we may be attached to
1101 //
1102 KeUnstackDetachProcess(&ApcState);
1103
1104 //
1105 // Check if we had allocated pool
1106 //
1107 if (HavePoolAddress) ExFreePool(PoolAddress);
1108
1109 //
1110 // Check if we failed during the probe
1111 //
1112 if (FailedInProbe)
1113 {
1114 //
1115 // Exit
1116 //
1117 Status = _SEH2_GetExceptionCode();
1118 _SEH2_YIELD(return Status);
1119 }
1120
1121 //
1122 // Otherwise, we failed, probably during the move
1123 //
1124 *ReturnSize = BufferSize - RemainingSize;
1125 if (FailedInMoving)
1126 {
1127 //
1128 // Check if we know exactly where we stopped copying
1129 //
1130 if (HaveBadAddress)
1131 {
1132 //
1133 // Return the exact number of bytes copied
1134 //
1135 *ReturnSize = BadAddress - (ULONG_PTR)SourceAddress;
1136 }
1137 }
1138
1139 //
1140 // Return partial copy
1141 //
1142 Status = STATUS_PARTIAL_COPY;
1143 }
1144 _SEH2_END;
1145
1146 //
1147 // Check for SEH status
1148 //
1149 if (Status != STATUS_SUCCESS) return Status;
1150
1151 //
1152 // Detach from target
1153 //
1154 KeUnstackDetachProcess(&ApcState);
1155
1156 //
1157 // Update location and size
1158 //
1159 RemainingSize -= CurrentSize;
1160 CurrentAddress = (PVOID)((ULONG_PTR)CurrentAddress + CurrentSize);
1161 CurrentTargetAddress = (PVOID)((ULONG_PTR)CurrentTargetAddress +
1162 CurrentSize);
1163 }
1164
1165 //
1166 // Check if we had allocated pool
1167 //
1168 if (HavePoolAddress) ExFreePool(PoolAddress);
1169
1170 //
1171 // All bytes read
1172 //
1173 *ReturnSize = BufferSize;
1174 return STATUS_SUCCESS;
1175 }
1176
1177 NTSTATUS
1178 NTAPI
1179 MmCopyVirtualMemory(IN PEPROCESS SourceProcess,
1180 IN PVOID SourceAddress,
1181 IN PEPROCESS TargetProcess,
1182 OUT PVOID TargetAddress,
1183 IN SIZE_T BufferSize,
1184 IN KPROCESSOR_MODE PreviousMode,
1185 OUT PSIZE_T ReturnSize)
1186 {
1187 NTSTATUS Status;
1188 PEPROCESS Process = SourceProcess;
1189
1190 //
1191 // Don't accept zero-sized buffers
1192 //
1193 if (!BufferSize) return STATUS_SUCCESS;
1194
1195 //
1196 // If we are copying from ourselves, lock the target instead
1197 //
1198 if (SourceProcess == PsGetCurrentProcess()) Process = TargetProcess;
1199
1200 //
1201 // Acquire rundown protection
1202 //
1203 if (!ExAcquireRundownProtection(&Process->RundownProtect))
1204 {
1205 //
1206 // Fail
1207 //
1208 return STATUS_PROCESS_IS_TERMINATING;
1209 }
1210
1211 //
1212 // See if we should use the pool copy
1213 //
1214 if (BufferSize > MI_POOL_COPY_BYTES)
1215 {
1216 //
1217 // Use MDL-copy
1218 //
1219 Status = MiDoMappedCopy(SourceProcess,
1220 SourceAddress,
1221 TargetProcess,
1222 TargetAddress,
1223 BufferSize,
1224 PreviousMode,
1225 ReturnSize);
1226 }
1227 else
1228 {
1229 //
1230 // Do pool copy
1231 //
1232 Status = MiDoPoolCopy(SourceProcess,
1233 SourceAddress,
1234 TargetProcess,
1235 TargetAddress,
1236 BufferSize,
1237 PreviousMode,
1238 ReturnSize);
1239 }
1240
1241 //
1242 // Release the lock
1243 //
1244 ExReleaseRundownProtection(&Process->RundownProtect);
1245 return Status;
1246 }
1247
1248 NTSTATUS
1249 NTAPI
1250 MmFlushVirtualMemory(IN PEPROCESS Process,
1251 IN OUT PVOID *BaseAddress,
1252 IN OUT PSIZE_T RegionSize,
1253 OUT PIO_STATUS_BLOCK IoStatusBlock)
1254 {
1255 PAGED_CODE();
1256 UNIMPLEMENTED;
1257
1258 //
1259 // Fake success
1260 //
1261 return STATUS_SUCCESS;
1262 }
1263
1264 ULONG
1265 NTAPI
1266 MiGetPageProtection(IN PMMPTE PointerPte)
1267 {
1268 MMPTE TempPte;
1269 PMMPFN Pfn;
1270 PAGED_CODE();
1271
1272 /* Copy this PTE's contents */
1273 TempPte = *PointerPte;
1274
1275 /* Assure it's not totally zero */
1276 ASSERT(TempPte.u.Long);
1277
1278 /* Check for a special prototype format */
1279 if (TempPte.u.Soft.Valid == 0 &&
1280 TempPte.u.Soft.Prototype == 1)
1281 {
1282 /* Unsupported now */
1283 UNIMPLEMENTED;
1284 ASSERT(FALSE);
1285 }
1286
1287 /* In the easy case of transition or demand zero PTE just return its protection */
1288 if (!TempPte.u.Hard.Valid) return MmProtectToValue[TempPte.u.Soft.Protection];
1289
1290 /* If we get here, the PTE is valid, so look up the page in PFN database */
1291 Pfn = MiGetPfnEntry(TempPte.u.Hard.PageFrameNumber);
1292 if (!Pfn->u3.e1.PrototypePte)
1293 {
1294 /* Return protection of the original pte */
1295 ASSERT(Pfn->u4.AweAllocation == 0);
1296 return MmProtectToValue[Pfn->OriginalPte.u.Soft.Protection];
1297 }
1298
1299 /* This is software PTE */
1300 DPRINT1("Prototype PTE: %lx %p\n", TempPte.u.Hard.PageFrameNumber, Pfn);
1301 DPRINT1("VA: %p\n", MiPteToAddress(&TempPte));
1302 DPRINT1("Mask: %lx\n", TempPte.u.Soft.Protection);
1303 DPRINT1("Mask2: %lx\n", Pfn->OriginalPte.u.Soft.Protection);
1304 return MmProtectToValue[TempPte.u.Soft.Protection];
1305 }
1306
1307 ULONG
1308 NTAPI
1309 MiQueryAddressState(IN PVOID Va,
1310 IN PMMVAD Vad,
1311 IN PEPROCESS TargetProcess,
1312 OUT PULONG ReturnedProtect,
1313 OUT PVOID *NextVa)
1314 {
1315
1316 PMMPTE PointerPte, ProtoPte;
1317 PMMPDE PointerPde;
1318 MMPTE TempPte, TempProtoPte;
1319 BOOLEAN DemandZeroPte = TRUE, ValidPte = FALSE;
1320 ULONG State = MEM_RESERVE, Protect = 0;
1321 ASSERT((Vad->StartingVpn <= ((ULONG_PTR)Va >> PAGE_SHIFT)) &&
1322 (Vad->EndingVpn >= ((ULONG_PTR)Va >> PAGE_SHIFT)));
1323
1324 /* Only normal VADs supported */
1325 ASSERT(Vad->u.VadFlags.VadType == VadNone);
1326
1327 /* Get the PDE and PTE for the address */
1328 PointerPde = MiAddressToPde(Va);
1329 PointerPte = MiAddressToPte(Va);
1330
1331 /* Return the next range */
1332 *NextVa = (PVOID)((ULONG_PTR)Va + PAGE_SIZE);
1333
1334 /* Is the PDE demand-zero? */
1335 if (PointerPde->u.Long != 0)
1336 {
1337 /* It is not. Is it valid? */
1338 if (PointerPde->u.Hard.Valid == 0)
1339 {
1340 /* Is isn't, fault it in */
1341 PointerPte = MiPteToAddress(PointerPde);
1342 MiMakeSystemAddressValid(PointerPte, TargetProcess);
1343 ValidPte = TRUE;
1344 }
1345 }
1346 else
1347 {
1348 /* It is, skip it and move to the next PDE */
1349 *NextVa = MiPdeToAddress(PointerPde + 1);
1350 }
1351
1352 /* Is it safe to try reading the PTE? */
1353 if (ValidPte)
1354 {
1355 /* FIXME: watch out for large pages */
1356 ASSERT(PointerPde->u.Hard.LargePage == FALSE);
1357
1358 /* Capture the PTE */
1359 TempPte = *PointerPte;
1360 if (TempPte.u.Long != 0)
1361 {
1362 /* The PTE is valid, so it's not zeroed out */
1363 DemandZeroPte = FALSE;
1364
1365 /* Is it a decommited, invalid, or faulted PTE? */
1366 if ((TempPte.u.Soft.Protection == MM_DECOMMIT) &&
1367 (TempPte.u.Hard.Valid == 0) &&
1368 ((TempPte.u.Soft.Prototype == 0) ||
1369 (TempPte.u.Soft.PageFileHigh == MI_PTE_LOOKUP_NEEDED)))
1370 {
1371 /* Otherwise our defaults should hold */
1372 ASSERT(Protect == 0);
1373 ASSERT(State == MEM_RESERVE);
1374 }
1375 else
1376 {
1377 /* This means it's committed */
1378 State = MEM_COMMIT;
1379
1380 /* We don't support these */
1381 ASSERT(Vad->u.VadFlags.VadType != VadDevicePhysicalMemory);
1382 ASSERT(Vad->u.VadFlags.VadType != VadRotatePhysical);
1383 ASSERT(Vad->u.VadFlags.VadType != VadAwe);
1384
1385 /* Get protection state of this page */
1386 Protect = MiGetPageProtection(PointerPte);
1387
1388 /* Check if this is an image-backed VAD */
1389 if ((TempPte.u.Soft.Valid == 0) &&
1390 (TempPte.u.Soft.Prototype == 1) &&
1391 (Vad->u.VadFlags.PrivateMemory == 0) &&
1392 (Vad->ControlArea))
1393 {
1394 DPRINT1("Not supported\n");
1395 ASSERT(FALSE);
1396 }
1397 }
1398 }
1399 }
1400
1401 /* Check if this was a demand-zero PTE, since we need to find the state */
1402 if (DemandZeroPte)
1403 {
1404 /* Not yet handled */
1405 ASSERT(Vad->u.VadFlags.VadType != VadDevicePhysicalMemory);
1406 ASSERT(Vad->u.VadFlags.VadType != VadAwe);
1407
1408 /* Check if this is private commited memory, or an section-backed VAD */
1409 if ((Vad->u.VadFlags.PrivateMemory == 0) && (Vad->ControlArea))
1410 {
1411 /* Tell caller about the next range */
1412 *NextVa = (PVOID)((ULONG_PTR)Va + PAGE_SIZE);
1413
1414 /* Get the prototype PTE for this VAD */
1415 ProtoPte = MI_GET_PROTOTYPE_PTE_FOR_VPN(Vad,
1416 (ULONG_PTR)Va >> PAGE_SHIFT);
1417 if (ProtoPte)
1418 {
1419 /* We should unlock the working set, but it's not being held! */
1420
1421 /* Is the prototype PTE actually valid (committed)? */
1422 TempProtoPte = *ProtoPte;
1423 if (TempProtoPte.u.Long)
1424 {
1425 /* Unless this is a memory-mapped file, handle it like private VAD */
1426 State = MEM_COMMIT;
1427 ASSERT(Vad->u.VadFlags.VadType != VadImageMap);
1428 Protect = MmProtectToValue[Vad->u.VadFlags.Protection];
1429 }
1430
1431 /* We should re-lock the working set */
1432 }
1433 }
1434 else if (Vad->u.VadFlags.MemCommit)
1435 {
1436 /* This is committed memory */
1437 State = MEM_COMMIT;
1438
1439 /* Convert the protection */
1440 Protect = MmProtectToValue[Vad->u.VadFlags.Protection];
1441 }
1442 }
1443
1444 /* Return the protection code */
1445 *ReturnedProtect = Protect;
1446 return State;
1447 }
1448
1449 NTSTATUS
1450 NTAPI
1451 MiQueryMemoryBasicInformation(IN HANDLE ProcessHandle,
1452 IN PVOID BaseAddress,
1453 OUT PVOID MemoryInformation,
1454 IN SIZE_T MemoryInformationLength,
1455 OUT PSIZE_T ReturnLength)
1456 {
1457 PEPROCESS TargetProcess;
1458 NTSTATUS Status = STATUS_SUCCESS;
1459 PMMVAD Vad = NULL;
1460 PVOID Address, NextAddress;
1461 BOOLEAN Found = FALSE;
1462 ULONG NewProtect, NewState;
1463 ULONG_PTR BaseVpn;
1464 MEMORY_BASIC_INFORMATION MemoryInfo;
1465 KAPC_STATE ApcState;
1466 KPROCESSOR_MODE PreviousMode = ExGetPreviousMode();
1467 PMEMORY_AREA MemoryArea;
1468 SIZE_T ResultLength;
1469
1470 /* Check for illegal addresses in user-space, or the shared memory area */
1471 if ((BaseAddress > MM_HIGHEST_VAD_ADDRESS) ||
1472 (PAGE_ALIGN(BaseAddress) == (PVOID)MM_SHARED_USER_DATA_VA))
1473 {
1474 Address = PAGE_ALIGN(BaseAddress);
1475
1476 /* Make up an info structure describing this range */
1477 MemoryInfo.BaseAddress = Address;
1478 MemoryInfo.AllocationProtect = PAGE_READONLY;
1479 MemoryInfo.Type = MEM_PRIVATE;
1480
1481 /* Special case for shared data */
1482 if (Address == (PVOID)MM_SHARED_USER_DATA_VA)
1483 {
1484 MemoryInfo.AllocationBase = (PVOID)MM_SHARED_USER_DATA_VA;
1485 MemoryInfo.State = MEM_COMMIT;
1486 MemoryInfo.Protect = PAGE_READONLY;
1487 MemoryInfo.RegionSize = PAGE_SIZE;
1488 }
1489 else
1490 {
1491 MemoryInfo.AllocationBase = (PCHAR)MM_HIGHEST_VAD_ADDRESS + 1;
1492 MemoryInfo.State = MEM_RESERVE;
1493 MemoryInfo.Protect = PAGE_NOACCESS;
1494 MemoryInfo.RegionSize = (ULONG_PTR)MM_HIGHEST_USER_ADDRESS + 1 - (ULONG_PTR)Address;
1495 }
1496
1497 /* Return the data, NtQueryInformation already probed it*/
1498 if (PreviousMode != KernelMode)
1499 {
1500 _SEH2_TRY
1501 {
1502 *(PMEMORY_BASIC_INFORMATION)MemoryInformation = MemoryInfo;
1503 if (ReturnLength) *ReturnLength = sizeof(MEMORY_BASIC_INFORMATION);
1504 }
1505 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
1506 {
1507 Status = _SEH2_GetExceptionCode();
1508 }
1509 _SEH2_END;
1510 }
1511 else
1512 {
1513 *(PMEMORY_BASIC_INFORMATION)MemoryInformation = MemoryInfo;
1514 if (ReturnLength) *ReturnLength = sizeof(MEMORY_BASIC_INFORMATION);
1515 }
1516
1517 return Status;
1518 }
1519
1520 /* Check if this is for a local or remote process */
1521 if (ProcessHandle == NtCurrentProcess())
1522 {
1523 TargetProcess = PsGetCurrentProcess();
1524 }
1525 else
1526 {
1527 /* Reference the target process */
1528 Status = ObReferenceObjectByHandle(ProcessHandle,
1529 PROCESS_QUERY_INFORMATION,
1530 PsProcessType,
1531 ExGetPreviousMode(),
1532 (PVOID*)&TargetProcess,
1533 NULL);
1534 if (!NT_SUCCESS(Status)) return Status;
1535
1536 /* Attach to it now */
1537 KeStackAttachProcess(&TargetProcess->Pcb, &ApcState);
1538 }
1539
1540 /* Loop the VADs */
1541 ASSERT(TargetProcess->VadRoot.NumberGenericTableElements);
1542 if (TargetProcess->VadRoot.NumberGenericTableElements)
1543 {
1544 /* Scan on the right */
1545 Vad = (PMMVAD)TargetProcess->VadRoot.BalancedRoot.RightChild;
1546 BaseVpn = (ULONG_PTR)BaseAddress >> PAGE_SHIFT;
1547 while (Vad)
1548 {
1549 /* Check if this VAD covers the allocation range */
1550 if ((BaseVpn >= Vad->StartingVpn) &&
1551 (BaseVpn <= Vad->EndingVpn))
1552 {
1553 /* We're done */
1554 Found = TRUE;
1555 break;
1556 }
1557
1558 /* Check if this VAD is too high */
1559 if (BaseVpn < Vad->StartingVpn)
1560 {
1561 /* Stop if there is no left child */
1562 if (!Vad->LeftChild) break;
1563
1564 /* Search on the left next */
1565 Vad = Vad->LeftChild;
1566 }
1567 else
1568 {
1569 /* Then this VAD is too low, keep searching on the right */
1570 ASSERT(BaseVpn > Vad->EndingVpn);
1571
1572 /* Stop if there is no right child */
1573 if (!Vad->RightChild) break;
1574
1575 /* Search on the right next */
1576 Vad = Vad->RightChild;
1577 }
1578 }
1579 }
1580
1581 /* Was a VAD found? */
1582 if (!Found)
1583 {
1584 Address = PAGE_ALIGN(BaseAddress);
1585
1586 /* Calculate region size */
1587 if (Vad)
1588 {
1589 if (Vad->StartingVpn >= BaseVpn)
1590 {
1591 /* Region size is the free space till the start of that VAD */
1592 MemoryInfo.RegionSize = (ULONG_PTR)(Vad->StartingVpn << PAGE_SHIFT) - (ULONG_PTR)Address;
1593 }
1594 else
1595 {
1596 /* Get the next VAD */
1597 Vad = (PMMVAD)MiGetNextNode((PMMADDRESS_NODE)Vad);
1598 if (Vad)
1599 {
1600 /* Region size is the free space till the start of that VAD */
1601 MemoryInfo.RegionSize = (ULONG_PTR)(Vad->StartingVpn << PAGE_SHIFT) - (ULONG_PTR)Address;
1602 }
1603 else
1604 {
1605 /* Maximum possible region size with that base address */
1606 MemoryInfo.RegionSize = (PCHAR)MM_HIGHEST_VAD_ADDRESS + 1 - (PCHAR)Address;
1607 }
1608 }
1609 }
1610 else
1611 {
1612 /* Maximum possible region size with that base address */
1613 MemoryInfo.RegionSize = (PCHAR)MM_HIGHEST_VAD_ADDRESS + 1 - (PCHAR)Address;
1614 }
1615
1616 /* Check if we were attached */
1617 if (ProcessHandle != NtCurrentProcess())
1618 {
1619 /* Detach and derefernece the process */
1620 KeUnstackDetachProcess(&ApcState);
1621 ObDereferenceObject(TargetProcess);
1622 }
1623
1624 /* Build the rest of the initial information block */
1625 MemoryInfo.BaseAddress = Address;
1626 MemoryInfo.AllocationBase = NULL;
1627 MemoryInfo.AllocationProtect = 0;
1628 MemoryInfo.State = MEM_FREE;
1629 MemoryInfo.Protect = PAGE_NOACCESS;
1630 MemoryInfo.Type = 0;
1631
1632 /* Return the data, NtQueryInformation already probed it*/
1633 if (PreviousMode != KernelMode)
1634 {
1635 _SEH2_TRY
1636 {
1637 *(PMEMORY_BASIC_INFORMATION)MemoryInformation = MemoryInfo;
1638 if (ReturnLength) *ReturnLength = sizeof(MEMORY_BASIC_INFORMATION);
1639 }
1640 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
1641 {
1642 Status = _SEH2_GetExceptionCode();
1643 }
1644 _SEH2_END;
1645 }
1646 else
1647 {
1648 *(PMEMORY_BASIC_INFORMATION)MemoryInformation = MemoryInfo;
1649 if (ReturnLength) *ReturnLength = sizeof(MEMORY_BASIC_INFORMATION);
1650 }
1651
1652 return Status;
1653 }
1654
1655 /* Set the correct memory type based on what kind of VAD this is */
1656 if ((Vad->u.VadFlags.PrivateMemory) ||
1657 (Vad->u.VadFlags.VadType == VadRotatePhysical))
1658 {
1659 MemoryInfo.Type = MEM_PRIVATE;
1660 }
1661 else if (Vad->u.VadFlags.VadType == VadImageMap)
1662 {
1663 MemoryInfo.Type = MEM_IMAGE;
1664 }
1665 else
1666 {
1667 MemoryInfo.Type = MEM_MAPPED;
1668 }
1669
1670 /* Lock the address space of the process */
1671 MmLockAddressSpace(&TargetProcess->Vm);
1672
1673 /* Find the memory area the specified address belongs to */
1674 MemoryArea = MmLocateMemoryAreaByAddress(&TargetProcess->Vm, BaseAddress);
1675 ASSERT(MemoryArea != NULL);
1676
1677 /* Determine information dependent on the memory area type */
1678 if (MemoryArea->Type == MEMORY_AREA_SECTION_VIEW)
1679 {
1680 Status = MmQuerySectionView(MemoryArea, BaseAddress, &MemoryInfo, &ResultLength);
1681 ASSERT(NT_SUCCESS(Status));
1682 }
1683 else
1684 {
1685 /* Build the initial information block */
1686 Address = PAGE_ALIGN(BaseAddress);
1687 MemoryInfo.BaseAddress = Address;
1688 MemoryInfo.AllocationBase = (PVOID)(Vad->StartingVpn << PAGE_SHIFT);
1689 MemoryInfo.AllocationProtect = MmProtectToValue[Vad->u.VadFlags.Protection];
1690 MemoryInfo.Type = MEM_PRIVATE;
1691
1692 /* Find the largest chunk of memory which has the same state and protection mask */
1693 MemoryInfo.State = MiQueryAddressState(Address,
1694 Vad,
1695 TargetProcess,
1696 &MemoryInfo.Protect,
1697 &NextAddress);
1698 Address = NextAddress;
1699 while (((ULONG_PTR)Address >> PAGE_SHIFT) <= Vad->EndingVpn)
1700 {
1701 /* Keep going unless the state or protection mask changed */
1702 NewState = MiQueryAddressState(Address, Vad, TargetProcess, &NewProtect, &NextAddress);
1703 if ((NewState != MemoryInfo.State) || (NewProtect != MemoryInfo.Protect)) break;
1704 Address = NextAddress;
1705 }
1706
1707 /* Now that we know the last VA address, calculate the region size */
1708 MemoryInfo.RegionSize = ((ULONG_PTR)Address - (ULONG_PTR)MemoryInfo.BaseAddress);
1709 }
1710
1711 /* Unlock the address space of the process */
1712 MmUnlockAddressSpace(&TargetProcess->Vm);
1713
1714 /* Check if we were attached */
1715 if (ProcessHandle != NtCurrentProcess())
1716 {
1717 /* Detach and derefernece the process */
1718 KeUnstackDetachProcess(&ApcState);
1719 ObDereferenceObject(TargetProcess);
1720 }
1721
1722 /* Return the data, NtQueryInformation already probed it*/
1723 if (PreviousMode != KernelMode)
1724 {
1725 _SEH2_TRY
1726 {
1727 *(PMEMORY_BASIC_INFORMATION)MemoryInformation = MemoryInfo;
1728 if (ReturnLength) *ReturnLength = sizeof(MEMORY_BASIC_INFORMATION);
1729 }
1730 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
1731 {
1732 Status = _SEH2_GetExceptionCode();
1733 }
1734 _SEH2_END;
1735 }
1736 else
1737 {
1738 *(PMEMORY_BASIC_INFORMATION)MemoryInformation = MemoryInfo;
1739 if (ReturnLength) *ReturnLength = sizeof(MEMORY_BASIC_INFORMATION);
1740 }
1741
1742 /* All went well */
1743 DPRINT("Base: %p AllocBase: %p AllocProtect: %lx Protect: %lx "
1744 "State: %lx Type: %lx Size: %lx\n",
1745 MemoryInfo.BaseAddress, MemoryInfo.AllocationBase,
1746 MemoryInfo.AllocationProtect, MemoryInfo.Protect,
1747 MemoryInfo.State, MemoryInfo.Type, MemoryInfo.RegionSize);
1748
1749 return Status;
1750 }
1751
1752 NTSTATUS
1753 NTAPI
1754 MiProtectVirtualMemory(IN PEPROCESS Process,
1755 IN OUT PVOID *BaseAddress,
1756 IN OUT PSIZE_T NumberOfBytesToProtect,
1757 IN ULONG NewAccessProtection,
1758 OUT PULONG OldAccessProtection OPTIONAL)
1759 {
1760 PMEMORY_AREA MemoryArea;
1761 PMMVAD Vad;
1762 PMMSUPPORT AddressSpace;
1763 ULONG_PTR StartingAddress, EndingAddress;
1764 PMMPTE PointerPde, PointerPte, LastPte;
1765 MMPTE PteContents;
1766 PUSHORT UsedPageTableEntries;
1767 PMMPFN Pfn1;
1768 ULONG ProtectionMask;
1769 NTSTATUS Status = STATUS_SUCCESS;
1770
1771 /* Check for ROS specific memory area */
1772 MemoryArea = MmLocateMemoryAreaByAddress(&Process->Vm, *BaseAddress);
1773 if ((MemoryArea) && (MemoryArea->Type == MEMORY_AREA_SECTION_VIEW))
1774 {
1775 return MiRosProtectVirtualMemory(Process,
1776 BaseAddress,
1777 NumberOfBytesToProtect,
1778 NewAccessProtection,
1779 OldAccessProtection);
1780 }
1781
1782 /* Calcualte base address for the VAD */
1783 StartingAddress = (ULONG_PTR)PAGE_ALIGN((*BaseAddress));
1784 EndingAddress = (((ULONG_PTR)*BaseAddress + *NumberOfBytesToProtect - 1) | (PAGE_SIZE - 1));
1785
1786 /* Calculate the protection mask and make sure it's valid */
1787 ProtectionMask = MiMakeProtectionMask(NewAccessProtection);
1788 if (ProtectionMask == MM_INVALID_PROTECTION)
1789 {
1790 DPRINT1("Invalid protection mask\n");
1791 return STATUS_INVALID_PAGE_PROTECTION;
1792 }
1793
1794 /* Lock the address space and make sure the process isn't already dead */
1795 AddressSpace = MmGetCurrentAddressSpace();
1796 MmLockAddressSpace(AddressSpace);
1797 if (Process->VmDeleted)
1798 {
1799 DPRINT1("Process is dying\n");
1800 Status = STATUS_PROCESS_IS_TERMINATING;
1801 goto FailPath;
1802 }
1803
1804 /* Get the VAD for this address range, and make sure it exists */
1805 Vad = (PMMVAD)MiCheckForConflictingNode(StartingAddress >> PAGE_SHIFT,
1806 EndingAddress >> PAGE_SHIFT,
1807 &Process->VadRoot);
1808 if (!Vad)
1809 {
1810 DPRINT("Could not find a VAD for this allocation\n");
1811 Status = STATUS_CONFLICTING_ADDRESSES;
1812 goto FailPath;
1813 }
1814
1815 /* Make sure the address is within this VAD's boundaries */
1816 if ((((ULONG_PTR)StartingAddress >> PAGE_SHIFT) < Vad->StartingVpn) ||
1817 (((ULONG_PTR)EndingAddress >> PAGE_SHIFT) > Vad->EndingVpn))
1818 {
1819 Status = STATUS_CONFLICTING_ADDRESSES;
1820 goto FailPath;
1821 }
1822
1823 /* These kinds of VADs are not supported atm */
1824 if ((Vad->u.VadFlags.VadType == VadAwe) ||
1825 (Vad->u.VadFlags.VadType == VadDevicePhysicalMemory) ||
1826 (Vad->u.VadFlags.VadType == VadLargePages))
1827 {
1828 DPRINT1("Illegal VAD for attempting to set protection\n");
1829 Status = STATUS_CONFLICTING_ADDRESSES;
1830 goto FailPath;
1831 }
1832
1833 /* Check for a VAD whose protection can't be changed */
1834 if (Vad->u.VadFlags.NoChange == 1)
1835 {
1836 DPRINT1("Trying to change protection of a NoChange VAD\n");
1837 Status = STATUS_INVALID_PAGE_PROTECTION;
1838 goto FailPath;
1839 }
1840
1841 if (Vad->u.VadFlags.PrivateMemory == 0)
1842 {
1843 /* This is a section, handled by the ROS specific code above */
1844 UNIMPLEMENTED;
1845 }
1846 else
1847 {
1848 /* Private memory, check protection flags */
1849 if ((NewAccessProtection & PAGE_WRITECOPY) ||
1850 (NewAccessProtection & PAGE_EXECUTE_WRITECOPY))
1851 {
1852 Status = STATUS_INVALID_PARAMETER_4;
1853 goto FailPath;
1854 }
1855
1856 //MiLockProcessWorkingSet(Thread, Process);
1857
1858 /* TODO: Check if all pages in this range are committed */
1859
1860 /* Compute starting and ending PTE and PDE addresses */
1861 PointerPde = MiAddressToPde(StartingAddress);
1862 PointerPte = MiAddressToPte(StartingAddress);
1863 LastPte = MiAddressToPte(EndingAddress);
1864
1865 /* Make this PDE valid */
1866 MiMakePdeExistAndMakeValid(PointerPde, Process, MM_NOIRQL);
1867
1868 /* Save protection of the first page */
1869 if (PointerPte->u.Long != 0)
1870 {
1871 /* Capture the page protection and make the PDE valid */
1872 *OldAccessProtection = MiGetPageProtection(PointerPte);
1873 MiMakePdeExistAndMakeValid(PointerPde, Process, MM_NOIRQL);
1874 }
1875 else
1876 {
1877 /* Grab the old protection from the VAD itself */
1878 *OldAccessProtection = MmProtectToValue[Vad->u.VadFlags.Protection];
1879 }
1880
1881 /* Loop all the PTEs now */
1882 while (PointerPte <= LastPte)
1883 {
1884 /* Check if we've crossed a PDE boundary and make the new PDE valid too */
1885 if ((((ULONG_PTR)PointerPte) & (SYSTEM_PD_SIZE - 1)) == 0)
1886 {
1887 PointerPde = MiAddressToPte(PointerPte);
1888 MiMakePdeExistAndMakeValid(PointerPde, Process, MM_NOIRQL);
1889 }
1890
1891 /* Capture the PTE and see what we're dealing with */
1892 PteContents = *PointerPte;
1893 if (PteContents.u.Long == 0)
1894 {
1895 /* This used to be a zero PTE and it no longer is, so we must add a
1896 reference to the pagetable. */
1897 UsedPageTableEntries = &MmWorkingSetList->UsedPageTableEntries[MiGetPdeOffset(MiPteToAddress(PointerPte))];
1898 (*UsedPageTableEntries)++;
1899 ASSERT((*UsedPageTableEntries) <= PTE_COUNT);
1900 }
1901 else if (PteContents.u.Hard.Valid == 1)
1902 {
1903 /* Get the PFN entry */
1904 Pfn1 = MiGetPfnEntry(PFN_FROM_PTE(&PteContents));
1905
1906 /* We don't support this yet */
1907 ASSERT(Pfn1->u3.e1.PrototypePte == 0);
1908
1909 /* Check if the page should not be accessible at all */
1910 if ((NewAccessProtection & PAGE_NOACCESS) ||
1911 (NewAccessProtection & PAGE_GUARD))
1912 {
1913 /* TODO */
1914 UNIMPLEMENTED;
1915 }
1916
1917 /* Write the protection mask and write it with a TLB flush */
1918 Pfn1->OriginalPte.u.Soft.Protection = ProtectionMask;
1919 MiFlushTbAndCapture(Vad,
1920 PointerPte,
1921 ProtectionMask,
1922 Pfn1,
1923 TRUE);
1924 }
1925 else
1926 {
1927 /* We don't support these cases yet */
1928 ASSERT(PteContents.u.Soft.Prototype == 0);
1929 ASSERT(PteContents.u.Soft.Transition == 0);
1930
1931 /* The PTE is already demand-zero, just update the protection mask */
1932 PointerPte->u.Soft.Protection = ProtectionMask;
1933 }
1934
1935 PointerPte++;
1936 }
1937
1938 /* Unlock the working set and update quota charges if needed, then return */
1939 //MiUnlockProcessWorkingSet(Thread, Process);
1940 }
1941
1942 FailPath:
1943 /* Unlock the address space */
1944 MmUnlockAddressSpace(AddressSpace);
1945
1946 /* Return parameters */
1947 *NumberOfBytesToProtect = (SIZE_T)((PUCHAR)EndingAddress - (PUCHAR)StartingAddress + 1);
1948 *BaseAddress = (PVOID)StartingAddress;
1949
1950 return Status;
1951 }
1952
1953 VOID
1954 NTAPI
1955 MiMakePdeExistAndMakeValid(IN PMMPTE PointerPde,
1956 IN PEPROCESS TargetProcess,
1957 IN KIRQL OldIrql)
1958 {
1959 PMMPTE PointerPte, PointerPpe, PointerPxe;
1960
1961 //
1962 // Sanity checks. The latter is because we only use this function with the
1963 // PFN lock not held, so it may go away in the future.
1964 //
1965 ASSERT(KeAreAllApcsDisabled() == TRUE);
1966 ASSERT(OldIrql == MM_NOIRQL);
1967
1968 //
1969 // Also get the PPE and PXE. This is okay not to #ifdef because they will
1970 // return the same address as the PDE on 2-level page table systems.
1971 //
1972 // If everything is already valid, there is nothing to do.
1973 //
1974 PointerPpe = MiAddressToPte(PointerPde);
1975 PointerPxe = MiAddressToPde(PointerPde);
1976 if ((PointerPxe->u.Hard.Valid) &&
1977 (PointerPpe->u.Hard.Valid) &&
1978 (PointerPde->u.Hard.Valid))
1979 {
1980 return;
1981 }
1982
1983 //
1984 // At least something is invalid, so begin by getting the PTE for the PDE itself
1985 // and then lookup each additional level. We must do it in this precise order
1986 // because the pagfault.c code (as well as in Windows) depends that the next
1987 // level up (higher) must be valid when faulting a lower level
1988 //
1989 PointerPte = MiPteToAddress(PointerPde);
1990 do
1991 {
1992 //
1993 // Make sure APCs continued to be disabled
1994 //
1995 ASSERT(KeAreAllApcsDisabled() == TRUE);
1996
1997 //
1998 // First, make the PXE valid if needed
1999 //
2000 if (!PointerPxe->u.Hard.Valid)
2001 {
2002 MiMakeSystemAddressValid(PointerPpe, TargetProcess);
2003 ASSERT(PointerPxe->u.Hard.Valid == 1);
2004 }
2005
2006 //
2007 // Next, the PPE
2008 //
2009 if (!PointerPpe->u.Hard.Valid)
2010 {
2011 MiMakeSystemAddressValid(PointerPde, TargetProcess);
2012 ASSERT(PointerPpe->u.Hard.Valid == 1);
2013 }
2014
2015 //
2016 // And finally, make the PDE itself valid.
2017 //
2018 MiMakeSystemAddressValid(PointerPte, TargetProcess);
2019
2020 //
2021 // This should've worked the first time so the loop is really just for
2022 // show -- ASSERT that we're actually NOT going to be looping.
2023 //
2024 ASSERT(PointerPxe->u.Hard.Valid == 1);
2025 ASSERT(PointerPpe->u.Hard.Valid == 1);
2026 ASSERT(PointerPde->u.Hard.Valid == 1);
2027 } while (!(PointerPxe->u.Hard.Valid) ||
2028 !(PointerPpe->u.Hard.Valid) ||
2029 !(PointerPde->u.Hard.Valid));
2030 }
2031
2032 VOID
2033 NTAPI
2034 MiProcessValidPteList(IN PMMPTE *ValidPteList,
2035 IN ULONG Count)
2036 {
2037 KIRQL OldIrql;
2038 ULONG i;
2039 MMPTE TempPte;
2040 PFN_NUMBER PageFrameIndex;
2041 PMMPFN Pfn1, Pfn2;
2042
2043 //
2044 // Acquire the PFN lock and loop all the PTEs in the list
2045 //
2046 OldIrql = KeAcquireQueuedSpinLock(LockQueuePfnLock);
2047 for (i = 0; i != Count; i++)
2048 {
2049 //
2050 // The PTE must currently be valid
2051 //
2052 TempPte = *ValidPteList[i];
2053 ASSERT(TempPte.u.Hard.Valid == 1);
2054
2055 //
2056 // Get the PFN entry for the page itself, and then for its page table
2057 //
2058 PageFrameIndex = PFN_FROM_PTE(&TempPte);
2059 Pfn1 = MiGetPfnEntry(PageFrameIndex);
2060 Pfn2 = MiGetPfnEntry(Pfn1->u4.PteFrame);
2061
2062 //
2063 // Decrement the share count on the page table, and then on the page
2064 // itself
2065 //
2066 MiDecrementShareCount(Pfn2, Pfn1->u4.PteFrame);
2067 MI_SET_PFN_DELETED(Pfn1);
2068 MiDecrementShareCount(Pfn1, PageFrameIndex);
2069
2070 //
2071 // Make the page decommitted
2072 //
2073 MI_WRITE_INVALID_PTE(ValidPteList[i], MmDecommittedPte);
2074 }
2075
2076 //
2077 // All the PTEs have been dereferenced and made invalid, flush the TLB now
2078 // and then release the PFN lock
2079 //
2080 KeFlushCurrentTb();
2081 KeReleaseQueuedSpinLock(LockQueuePfnLock, OldIrql);
2082 }
2083
2084 ULONG
2085 NTAPI
2086 MiDecommitPages(IN PVOID StartingAddress,
2087 IN PMMPTE EndingPte,
2088 IN PEPROCESS Process,
2089 IN PMMVAD Vad)
2090 {
2091 PMMPTE PointerPde, PointerPte, CommitPte = NULL;
2092 ULONG CommitReduction = 0;
2093 PMMPTE ValidPteList[256];
2094 ULONG PteCount = 0;
2095 PMMPFN Pfn1;
2096 MMPTE PteContents;
2097 PUSHORT UsedPageTableEntries;
2098 PETHREAD CurrentThread = PsGetCurrentThread();
2099
2100 //
2101 // Get the PTE and PTE for the address, and lock the working set
2102 // If this was a VAD for a MEM_COMMIT allocation, also figure out where the
2103 // commited range ends so that we can do the right accounting.
2104 //
2105 PointerPde = MiAddressToPde(StartingAddress);
2106 PointerPte = MiAddressToPte(StartingAddress);
2107 if (Vad->u.VadFlags.MemCommit) CommitPte = MiAddressToPte(Vad->EndingVpn << PAGE_SHIFT);
2108 MiLockWorkingSet(CurrentThread, &Process->Vm);
2109
2110 //
2111 // Make the PDE valid, and now loop through each page's worth of data
2112 //
2113 MiMakePdeExistAndMakeValid(PointerPde, Process, MM_NOIRQL);
2114 while (PointerPte <= EndingPte)
2115 {
2116 //
2117 // Check if we've crossed a PDE boundary
2118 //
2119 if ((((ULONG_PTR)PointerPte) & (SYSTEM_PD_SIZE - 1)) == 0)
2120 {
2121 //
2122 // Get the new PDE and flush the valid PTEs we had built up until
2123 // now. This helps reduce the amount of TLB flushing we have to do.
2124 // Note that Windows does a much better job using timestamps and
2125 // such, and does not flush the entire TLB all the time, but right
2126 // now we have bigger problems to worry about than TLB flushing.
2127 //
2128 PointerPde = MiAddressToPde(StartingAddress);
2129 if (PteCount)
2130 {
2131 MiProcessValidPteList(ValidPteList, PteCount);
2132 PteCount = 0;
2133 }
2134
2135 //
2136 // Make this PDE valid
2137 //
2138 MiMakePdeExistAndMakeValid(PointerPde, Process, MM_NOIRQL);
2139 }
2140
2141 //
2142 // Read this PTE. It might be active or still demand-zero.
2143 //
2144 PteContents = *PointerPte;
2145 if (PteContents.u.Long)
2146 {
2147 //
2148 // The PTE is active. It might be valid and in a working set, or
2149 // it might be a prototype PTE or paged out or even in transition.
2150 //
2151 if (PointerPte->u.Long == MmDecommittedPte.u.Long)
2152 {
2153 //
2154 // It's already decommited, so there's nothing for us to do here
2155 //
2156 CommitReduction++;
2157 }
2158 else
2159 {
2160 //
2161 // Remove it from the counters, and check if it was valid or not
2162 //
2163 //Process->NumberOfPrivatePages--;
2164 if (PteContents.u.Hard.Valid)
2165 {
2166 //
2167 // It's valid. At this point make sure that it is not a ROS
2168 // PFN. Also, we don't support ProtoPTEs in this code path.
2169 //
2170 Pfn1 = MiGetPfnEntry(PteContents.u.Hard.PageFrameNumber);
2171 ASSERT(MI_IS_ROS_PFN(Pfn1) == FALSE);
2172 ASSERT(Pfn1->u3.e1.PrototypePte == FALSE);
2173
2174 //
2175 // Flush any pending PTEs that we had not yet flushed, if our
2176 // list has gotten too big, then add this PTE to the flush list.
2177 //
2178 if (PteCount == 256)
2179 {
2180 MiProcessValidPteList(ValidPteList, PteCount);
2181 PteCount = 0;
2182 }
2183 ValidPteList[PteCount++] = PointerPte;
2184 }
2185 else
2186 {
2187 //
2188 // We do not support any of these other scenarios at the moment
2189 //
2190 ASSERT(PteContents.u.Soft.Prototype == 0);
2191 ASSERT(PteContents.u.Soft.Transition == 0);
2192 ASSERT(PteContents.u.Soft.PageFileHigh == 0);
2193
2194 //
2195 // So the only other possibility is that it is still a demand
2196 // zero PTE, in which case we undo the accounting we did
2197 // earlier and simply make the page decommitted.
2198 //
2199 //Process->NumberOfPrivatePages++;
2200 MI_WRITE_INVALID_PTE(PointerPte, MmDecommittedPte);
2201 }
2202 }
2203 }
2204 else
2205 {
2206 //
2207 // This used to be a zero PTE and it no longer is, so we must add a
2208 // reference to the pagetable.
2209 //
2210 UsedPageTableEntries = &MmWorkingSetList->UsedPageTableEntries[MiGetPdeOffset(StartingAddress)];
2211 (*UsedPageTableEntries)++;
2212 ASSERT((*UsedPageTableEntries) <= PTE_COUNT);
2213
2214 //
2215 // Next, we account for decommitted PTEs and make the PTE as such
2216 //
2217 if (PointerPte > CommitPte) CommitReduction++;
2218 MI_WRITE_INVALID_PTE(PointerPte, MmDecommittedPte);
2219 }
2220
2221 //
2222 // Move to the next PTE and the next address
2223 //
2224 PointerPte++;
2225 StartingAddress = (PVOID)((ULONG_PTR)StartingAddress + PAGE_SIZE);
2226 }
2227
2228 //
2229 // Flush any dangling PTEs from the loop in the last page table, and then
2230 // release the working set and return the commit reduction accounting.
2231 //
2232 if (PteCount) MiProcessValidPteList(ValidPteList, PteCount);
2233 MiUnlockWorkingSet(CurrentThread, &Process->Vm);
2234 return CommitReduction;
2235 }
2236
2237 /* PUBLIC FUNCTIONS ***********************************************************/
2238
2239 /*
2240 * @unimplemented
2241 */
2242 PVOID
2243 NTAPI
2244 MmGetVirtualForPhysical(IN PHYSICAL_ADDRESS PhysicalAddress)
2245 {
2246 UNIMPLEMENTED;
2247 return 0;
2248 }
2249
2250 /*
2251 * @unimplemented
2252 */
2253 PVOID
2254 NTAPI
2255 MmSecureVirtualMemory(IN PVOID Address,
2256 IN SIZE_T Length,
2257 IN ULONG Mode)
2258 {
2259 static BOOLEAN Warn; if (!Warn++) UNIMPLEMENTED;
2260 return Address;
2261 }
2262
2263 /*
2264 * @unimplemented
2265 */
2266 VOID
2267 NTAPI
2268 MmUnsecureVirtualMemory(IN PVOID SecureMem)
2269 {
2270 static BOOLEAN Warn; if (!Warn++) UNIMPLEMENTED;
2271 }
2272
2273 /* SYSTEM CALLS ***************************************************************/
2274
2275 NTSTATUS
2276 NTAPI
2277 NtReadVirtualMemory(IN HANDLE ProcessHandle,
2278 IN PVOID BaseAddress,
2279 OUT PVOID Buffer,
2280 IN SIZE_T NumberOfBytesToRead,
2281 OUT PSIZE_T NumberOfBytesRead OPTIONAL)
2282 {
2283 KPROCESSOR_MODE PreviousMode = ExGetPreviousMode();
2284 PEPROCESS Process;
2285 NTSTATUS Status = STATUS_SUCCESS;
2286 SIZE_T BytesRead = 0;
2287 PAGED_CODE();
2288
2289 //
2290 // Check if we came from user mode
2291 //
2292 if (PreviousMode != KernelMode)
2293 {
2294 //
2295 // Validate the read addresses
2296 //
2297 if ((((ULONG_PTR)BaseAddress + NumberOfBytesToRead) < (ULONG_PTR)BaseAddress) ||
2298 (((ULONG_PTR)Buffer + NumberOfBytesToRead) < (ULONG_PTR)Buffer) ||
2299 (((ULONG_PTR)BaseAddress + NumberOfBytesToRead) > MmUserProbeAddress) ||
2300 (((ULONG_PTR)Buffer + NumberOfBytesToRead) > MmUserProbeAddress))
2301 {
2302 //
2303 // Don't allow to write into kernel space
2304 //
2305 return STATUS_ACCESS_VIOLATION;
2306 }
2307
2308 //
2309 // Enter SEH for probe
2310 //
2311 _SEH2_TRY
2312 {
2313 //
2314 // Probe the output value
2315 //
2316 if (NumberOfBytesRead) ProbeForWriteSize_t(NumberOfBytesRead);
2317 }
2318 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2319 {
2320 //
2321 // Get exception code
2322 //
2323 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2324 }
2325 _SEH2_END;
2326 }
2327
2328 //
2329 // Don't do zero-byte transfers
2330 //
2331 if (NumberOfBytesToRead)
2332 {
2333 //
2334 // Reference the process
2335 //
2336 Status = ObReferenceObjectByHandle(ProcessHandle,
2337 PROCESS_VM_READ,
2338 PsProcessType,
2339 PreviousMode,
2340 (PVOID*)(&Process),
2341 NULL);
2342 if (NT_SUCCESS(Status))
2343 {
2344 //
2345 // Do the copy
2346 //
2347 Status = MmCopyVirtualMemory(Process,
2348 BaseAddress,
2349 PsGetCurrentProcess(),
2350 Buffer,
2351 NumberOfBytesToRead,
2352 PreviousMode,
2353 &BytesRead);
2354
2355 //
2356 // Dereference the process
2357 //
2358 ObDereferenceObject(Process);
2359 }
2360 }
2361
2362 //
2363 // Check if the caller sent this parameter
2364 //
2365 if (NumberOfBytesRead)
2366 {
2367 //
2368 // Enter SEH to guard write
2369 //
2370 _SEH2_TRY
2371 {
2372 //
2373 // Return the number of bytes read
2374 //
2375 *NumberOfBytesRead = BytesRead;
2376 }
2377 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2378 {
2379 }
2380 _SEH2_END;
2381 }
2382
2383 //
2384 // Return status
2385 //
2386 return Status;
2387 }
2388
2389 NTSTATUS
2390 NTAPI
2391 NtWriteVirtualMemory(IN HANDLE ProcessHandle,
2392 IN PVOID BaseAddress,
2393 IN PVOID Buffer,
2394 IN SIZE_T NumberOfBytesToWrite,
2395 OUT PSIZE_T NumberOfBytesWritten OPTIONAL)
2396 {
2397 KPROCESSOR_MODE PreviousMode = ExGetPreviousMode();
2398 PEPROCESS Process;
2399 NTSTATUS Status = STATUS_SUCCESS;
2400 SIZE_T BytesWritten = 0;
2401 PAGED_CODE();
2402
2403 //
2404 // Check if we came from user mode
2405 //
2406 if (PreviousMode != KernelMode)
2407 {
2408 //
2409 // Validate the read addresses
2410 //
2411 if ((((ULONG_PTR)BaseAddress + NumberOfBytesToWrite) < (ULONG_PTR)BaseAddress) ||
2412 (((ULONG_PTR)Buffer + NumberOfBytesToWrite) < (ULONG_PTR)Buffer) ||
2413 (((ULONG_PTR)BaseAddress + NumberOfBytesToWrite) > MmUserProbeAddress) ||
2414 (((ULONG_PTR)Buffer + NumberOfBytesToWrite) > MmUserProbeAddress))
2415 {
2416 //
2417 // Don't allow to write into kernel space
2418 //
2419 return STATUS_ACCESS_VIOLATION;
2420 }
2421
2422 //
2423 // Enter SEH for probe
2424 //
2425 _SEH2_TRY
2426 {
2427 //
2428 // Probe the output value
2429 //
2430 if (NumberOfBytesWritten) ProbeForWriteSize_t(NumberOfBytesWritten);
2431 }
2432 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2433 {
2434 //
2435 // Get exception code
2436 //
2437 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2438 }
2439 _SEH2_END;
2440 }
2441
2442 //
2443 // Don't do zero-byte transfers
2444 //
2445 if (NumberOfBytesToWrite)
2446 {
2447 //
2448 // Reference the process
2449 //
2450 Status = ObReferenceObjectByHandle(ProcessHandle,
2451 PROCESS_VM_WRITE,
2452 PsProcessType,
2453 PreviousMode,
2454 (PVOID*)&Process,
2455 NULL);
2456 if (NT_SUCCESS(Status))
2457 {
2458 //
2459 // Do the copy
2460 //
2461 Status = MmCopyVirtualMemory(PsGetCurrentProcess(),
2462 Buffer,
2463 Process,
2464 BaseAddress,
2465 NumberOfBytesToWrite,
2466 PreviousMode,
2467 &BytesWritten);
2468
2469 //
2470 // Dereference the process
2471 //
2472 ObDereferenceObject(Process);
2473 }
2474 }
2475
2476 //
2477 // Check if the caller sent this parameter
2478 //
2479 if (NumberOfBytesWritten)
2480 {
2481 //
2482 // Enter SEH to guard write
2483 //
2484 _SEH2_TRY
2485 {
2486 //
2487 // Return the number of bytes written
2488 //
2489 *NumberOfBytesWritten = BytesWritten;
2490 }
2491 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2492 {
2493 }
2494 _SEH2_END;
2495 }
2496
2497 //
2498 // Return status
2499 //
2500 return Status;
2501 }
2502
2503 NTSTATUS
2504 NTAPI
2505 NtProtectVirtualMemory(IN HANDLE ProcessHandle,
2506 IN OUT PVOID *UnsafeBaseAddress,
2507 IN OUT SIZE_T *UnsafeNumberOfBytesToProtect,
2508 IN ULONG NewAccessProtection,
2509 OUT PULONG UnsafeOldAccessProtection)
2510 {
2511 PEPROCESS Process;
2512 ULONG OldAccessProtection;
2513 ULONG Protection;
2514 PEPROCESS CurrentProcess = PsGetCurrentProcess();
2515 PVOID BaseAddress = NULL;
2516 SIZE_T NumberOfBytesToProtect = 0;
2517 KPROCESSOR_MODE PreviousMode = ExGetPreviousMode();
2518 NTSTATUS Status;
2519 BOOLEAN Attached = FALSE;
2520 KAPC_STATE ApcState;
2521 PAGED_CODE();
2522
2523 //
2524 // Check for valid protection flags
2525 //
2526 Protection = NewAccessProtection & ~(PAGE_GUARD|PAGE_NOCACHE);
2527 if (Protection != PAGE_NOACCESS &&
2528 Protection != PAGE_READONLY &&
2529 Protection != PAGE_READWRITE &&
2530 Protection != PAGE_WRITECOPY &&
2531 Protection != PAGE_EXECUTE &&
2532 Protection != PAGE_EXECUTE_READ &&
2533 Protection != PAGE_EXECUTE_READWRITE &&
2534 Protection != PAGE_EXECUTE_WRITECOPY)
2535 {
2536 //
2537 // Fail
2538 //
2539 return STATUS_INVALID_PAGE_PROTECTION;
2540 }
2541
2542 //
2543 // Check if we came from user mode
2544 //
2545 if (PreviousMode != KernelMode)
2546 {
2547 //
2548 // Enter SEH for probing
2549 //
2550 _SEH2_TRY
2551 {
2552 //
2553 // Validate all outputs
2554 //
2555 ProbeForWritePointer(UnsafeBaseAddress);
2556 ProbeForWriteSize_t(UnsafeNumberOfBytesToProtect);
2557 ProbeForWriteUlong(UnsafeOldAccessProtection);
2558
2559 //
2560 // Capture them
2561 //
2562 BaseAddress = *UnsafeBaseAddress;
2563 NumberOfBytesToProtect = *UnsafeNumberOfBytesToProtect;
2564 }
2565 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2566 {
2567 //
2568 // Get exception code
2569 //
2570 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2571 }
2572 _SEH2_END;
2573 }
2574 else
2575 {
2576 //
2577 // Capture directly
2578 //
2579 BaseAddress = *UnsafeBaseAddress;
2580 NumberOfBytesToProtect = *UnsafeNumberOfBytesToProtect;
2581 }
2582
2583 //
2584 // Catch illegal base address
2585 //
2586 if (BaseAddress > MM_HIGHEST_USER_ADDRESS) return STATUS_INVALID_PARAMETER_2;
2587
2588 //
2589 // Catch illegal region size
2590 //
2591 if ((MmUserProbeAddress - (ULONG_PTR)BaseAddress) < NumberOfBytesToProtect)
2592 {
2593 //
2594 // Fail
2595 //
2596 return STATUS_INVALID_PARAMETER_3;
2597 }
2598
2599 //
2600 // 0 is also illegal
2601 //
2602 if (!NumberOfBytesToProtect) return STATUS_INVALID_PARAMETER_3;
2603
2604 //
2605 // Get a reference to the process
2606 //
2607 Status = ObReferenceObjectByHandle(ProcessHandle,
2608 PROCESS_VM_OPERATION,
2609 PsProcessType,
2610 PreviousMode,
2611 (PVOID*)(&Process),
2612 NULL);
2613 if (!NT_SUCCESS(Status)) return Status;
2614
2615 //
2616 // Check if we should attach
2617 //
2618 if (CurrentProcess != Process)
2619 {
2620 //
2621 // Do it
2622 //
2623 KeStackAttachProcess(&Process->Pcb, &ApcState);
2624 Attached = TRUE;
2625 }
2626
2627 //
2628 // Do the actual work
2629 //
2630 Status = MiProtectVirtualMemory(Process,
2631 &BaseAddress,
2632 &NumberOfBytesToProtect,
2633 NewAccessProtection,
2634 &OldAccessProtection);
2635
2636 //
2637 // Detach if needed
2638 //
2639 if (Attached) KeUnstackDetachProcess(&ApcState);
2640
2641 //
2642 // Release reference
2643 //
2644 ObDereferenceObject(Process);
2645
2646 //
2647 // Enter SEH to return data
2648 //
2649 _SEH2_TRY
2650 {
2651 //
2652 // Return data to user
2653 //
2654 *UnsafeOldAccessProtection = OldAccessProtection;
2655 *UnsafeBaseAddress = BaseAddress;
2656 *UnsafeNumberOfBytesToProtect = NumberOfBytesToProtect;
2657 }
2658 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2659 {
2660 }
2661 _SEH2_END;
2662
2663 //
2664 // Return status
2665 //
2666 return Status;
2667 }
2668
2669 NTSTATUS
2670 NTAPI
2671 NtLockVirtualMemory(IN HANDLE ProcessHandle,
2672 IN OUT PVOID *BaseAddress,
2673 IN OUT PSIZE_T NumberOfBytesToLock,
2674 IN ULONG MapType)
2675 {
2676 PEPROCESS Process;
2677 PEPROCESS CurrentProcess = PsGetCurrentProcess();
2678 NTSTATUS Status;
2679 BOOLEAN Attached = FALSE;
2680 KAPC_STATE ApcState;
2681 KPROCESSOR_MODE PreviousMode = ExGetPreviousMode();
2682 PVOID CapturedBaseAddress;
2683 SIZE_T CapturedBytesToLock;
2684 PAGED_CODE();
2685
2686 //
2687 // Validate flags
2688 //
2689 if ((MapType & ~(MAP_PROCESS | MAP_SYSTEM)))
2690 {
2691 //
2692 // Invalid set of flags
2693 //
2694 return STATUS_INVALID_PARAMETER;
2695 }
2696
2697 //
2698 // At least one flag must be specified
2699 //
2700 if (!(MapType & (MAP_PROCESS | MAP_SYSTEM)))
2701 {
2702 //
2703 // No flag given
2704 //
2705 return STATUS_INVALID_PARAMETER;
2706 }
2707
2708 //
2709 // Enter SEH for probing
2710 //
2711 _SEH2_TRY
2712 {
2713 //
2714 // Validate output data
2715 //
2716 ProbeForWritePointer(BaseAddress);
2717 ProbeForWriteSize_t(NumberOfBytesToLock);
2718
2719 //
2720 // Capture it
2721 //
2722 CapturedBaseAddress = *BaseAddress;
2723 CapturedBytesToLock = *NumberOfBytesToLock;
2724 }
2725 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2726 {
2727 //
2728 // Get exception code
2729 //
2730 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2731 }
2732 _SEH2_END;
2733
2734 //
2735 // Catch illegal base address
2736 //
2737 if (CapturedBaseAddress > MM_HIGHEST_USER_ADDRESS) return STATUS_INVALID_PARAMETER;
2738
2739 //
2740 // Catch illegal region size
2741 //
2742 if ((MmUserProbeAddress - (ULONG_PTR)CapturedBaseAddress) < CapturedBytesToLock)
2743 {
2744 //
2745 // Fail
2746 //
2747 return STATUS_INVALID_PARAMETER;
2748 }
2749
2750 //
2751 // 0 is also illegal
2752 //
2753 if (!CapturedBytesToLock) return STATUS_INVALID_PARAMETER;
2754
2755 //
2756 // Get a reference to the process
2757 //
2758 Status = ObReferenceObjectByHandle(ProcessHandle,
2759 PROCESS_VM_OPERATION,
2760 PsProcessType,
2761 PreviousMode,
2762 (PVOID*)(&Process),
2763 NULL);
2764 if (!NT_SUCCESS(Status)) return Status;
2765
2766 //
2767 // Check if this is is system-mapped
2768 //
2769 if (MapType & MAP_SYSTEM)
2770 {
2771 //
2772 // Check for required privilege
2773 //
2774 if (!SeSinglePrivilegeCheck(SeLockMemoryPrivilege, PreviousMode))
2775 {
2776 //
2777 // Fail: Don't have it
2778 //
2779 ObDereferenceObject(Process);
2780 return STATUS_PRIVILEGE_NOT_HELD;
2781 }
2782 }
2783
2784 //
2785 // Check if we should attach
2786 //
2787 if (CurrentProcess != Process)
2788 {
2789 //
2790 // Do it
2791 //
2792 KeStackAttachProcess(&Process->Pcb, &ApcState);
2793 Attached = TRUE;
2794 }
2795
2796 //
2797 // Oops :(
2798 //
2799 UNIMPLEMENTED;
2800
2801 //
2802 // Detach if needed
2803 //
2804 if (Attached) KeUnstackDetachProcess(&ApcState);
2805
2806 //
2807 // Release reference
2808 //
2809 ObDereferenceObject(Process);
2810
2811 //
2812 // Enter SEH to return data
2813 //
2814 _SEH2_TRY
2815 {
2816 //
2817 // Return data to user
2818 //
2819 *BaseAddress = CapturedBaseAddress;
2820 *NumberOfBytesToLock = 0;
2821 }
2822 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2823 {
2824 //
2825 // Get exception code
2826 //
2827 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2828 }
2829 _SEH2_END;
2830
2831 //
2832 // Return status
2833 //
2834 return STATUS_SUCCESS;
2835 }
2836
2837 NTSTATUS
2838 NTAPI
2839 NtUnlockVirtualMemory(IN HANDLE ProcessHandle,
2840 IN OUT PVOID *BaseAddress,
2841 IN OUT PSIZE_T NumberOfBytesToUnlock,
2842 IN ULONG MapType)
2843 {
2844 PEPROCESS Process;
2845 PEPROCESS CurrentProcess = PsGetCurrentProcess();
2846 NTSTATUS Status;
2847 BOOLEAN Attached = FALSE;
2848 KAPC_STATE ApcState;
2849 KPROCESSOR_MODE PreviousMode = ExGetPreviousMode();
2850 PVOID CapturedBaseAddress;
2851 SIZE_T CapturedBytesToUnlock;
2852 PAGED_CODE();
2853
2854 //
2855 // Validate flags
2856 //
2857 if ((MapType & ~(MAP_PROCESS | MAP_SYSTEM)))
2858 {
2859 //
2860 // Invalid set of flags
2861 //
2862 return STATUS_INVALID_PARAMETER;
2863 }
2864
2865 //
2866 // At least one flag must be specified
2867 //
2868 if (!(MapType & (MAP_PROCESS | MAP_SYSTEM)))
2869 {
2870 //
2871 // No flag given
2872 //
2873 return STATUS_INVALID_PARAMETER;
2874 }
2875
2876 //
2877 // Enter SEH for probing
2878 //
2879 _SEH2_TRY
2880 {
2881 //
2882 // Validate output data
2883 //
2884 ProbeForWritePointer(BaseAddress);
2885 ProbeForWriteSize_t(NumberOfBytesToUnlock);
2886
2887 //
2888 // Capture it
2889 //
2890 CapturedBaseAddress = *BaseAddress;
2891 CapturedBytesToUnlock = *NumberOfBytesToUnlock;
2892 }
2893 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2894 {
2895 //
2896 // Get exception code
2897 //
2898 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2899 }
2900 _SEH2_END;
2901
2902 //
2903 // Catch illegal base address
2904 //
2905 if (CapturedBaseAddress > MM_HIGHEST_USER_ADDRESS) return STATUS_INVALID_PARAMETER;
2906
2907 //
2908 // Catch illegal region size
2909 //
2910 if ((MmUserProbeAddress - (ULONG_PTR)CapturedBaseAddress) < CapturedBytesToUnlock)
2911 {
2912 //
2913 // Fail
2914 //
2915 return STATUS_INVALID_PARAMETER;
2916 }
2917
2918 //
2919 // 0 is also illegal
2920 //
2921 if (!CapturedBytesToUnlock) return STATUS_INVALID_PARAMETER;
2922
2923 //
2924 // Get a reference to the process
2925 //
2926 Status = ObReferenceObjectByHandle(ProcessHandle,
2927 PROCESS_VM_OPERATION,
2928 PsProcessType,
2929 PreviousMode,
2930 (PVOID*)(&Process),
2931 NULL);
2932 if (!NT_SUCCESS(Status)) return Status;
2933
2934 //
2935 // Check if this is is system-mapped
2936 //
2937 if (MapType & MAP_SYSTEM)
2938 {
2939 //
2940 // Check for required privilege
2941 //
2942 if (!SeSinglePrivilegeCheck(SeLockMemoryPrivilege, PreviousMode))
2943 {
2944 //
2945 // Fail: Don't have it
2946 //
2947 ObDereferenceObject(Process);
2948 return STATUS_PRIVILEGE_NOT_HELD;
2949 }
2950 }
2951
2952 //
2953 // Check if we should attach
2954 //
2955 if (CurrentProcess != Process)
2956 {
2957 //
2958 // Do it
2959 //
2960 KeStackAttachProcess(&Process->Pcb, &ApcState);
2961 Attached = TRUE;
2962 }
2963
2964 //
2965 // Oops :(
2966 //
2967 UNIMPLEMENTED;
2968
2969 //
2970 // Detach if needed
2971 //
2972 if (Attached) KeUnstackDetachProcess(&ApcState);
2973
2974 //
2975 // Release reference
2976 //
2977 ObDereferenceObject(Process);
2978
2979 //
2980 // Enter SEH to return data
2981 //
2982 _SEH2_TRY
2983 {
2984 //
2985 // Return data to user
2986 //
2987 *BaseAddress = PAGE_ALIGN(CapturedBaseAddress);
2988 *NumberOfBytesToUnlock = 0;
2989 }
2990 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
2991 {
2992 //
2993 // Get exception code
2994 //
2995 _SEH2_YIELD(return _SEH2_GetExceptionCode());
2996 }
2997 _SEH2_END;
2998
2999 //
3000 // Return status
3001 //
3002 return STATUS_SUCCESS;
3003 }
3004
3005 NTSTATUS
3006 NTAPI
3007 NtFlushVirtualMemory(IN HANDLE ProcessHandle,
3008 IN OUT PVOID *BaseAddress,
3009 IN OUT PSIZE_T NumberOfBytesToFlush,
3010 OUT PIO_STATUS_BLOCK IoStatusBlock)
3011 {
3012 PEPROCESS Process;
3013 NTSTATUS Status;
3014 KPROCESSOR_MODE PreviousMode = ExGetPreviousMode();
3015 PVOID CapturedBaseAddress;
3016 SIZE_T CapturedBytesToFlush;
3017 IO_STATUS_BLOCK LocalStatusBlock;
3018 PAGED_CODE();
3019
3020 //
3021 // Check if we came from user mode
3022 //
3023 if (PreviousMode != KernelMode)
3024 {
3025 //
3026 // Enter SEH for probing
3027 //
3028 _SEH2_TRY
3029 {
3030 //
3031 // Validate all outputs
3032 //
3033 ProbeForWritePointer(BaseAddress);
3034 ProbeForWriteSize_t(NumberOfBytesToFlush);
3035 ProbeForWriteIoStatusBlock(IoStatusBlock);
3036
3037 //
3038 // Capture them
3039 //
3040 CapturedBaseAddress = *BaseAddress;
3041 CapturedBytesToFlush = *NumberOfBytesToFlush;
3042 }
3043 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
3044 {
3045 //
3046 // Get exception code
3047 //
3048 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3049 }
3050 _SEH2_END;
3051 }
3052 else
3053 {
3054 //
3055 // Capture directly
3056 //
3057 CapturedBaseAddress = *BaseAddress;
3058 CapturedBytesToFlush = *NumberOfBytesToFlush;
3059 }
3060
3061 //
3062 // Catch illegal base address
3063 //
3064 if (CapturedBaseAddress > MM_HIGHEST_USER_ADDRESS) return STATUS_INVALID_PARAMETER;
3065
3066 //
3067 // Catch illegal region size
3068 //
3069 if ((MmUserProbeAddress - (ULONG_PTR)CapturedBaseAddress) < CapturedBytesToFlush)
3070 {
3071 //
3072 // Fail
3073 //
3074 return STATUS_INVALID_PARAMETER;
3075 }
3076
3077 //
3078 // Get a reference to the process
3079 //
3080 Status = ObReferenceObjectByHandle(ProcessHandle,
3081 PROCESS_VM_OPERATION,
3082 PsProcessType,
3083 PreviousMode,
3084 (PVOID*)(&Process),
3085 NULL);
3086 if (!NT_SUCCESS(Status)) return Status;
3087
3088 //
3089 // Do it
3090 //
3091 Status = MmFlushVirtualMemory(Process,
3092 &CapturedBaseAddress,
3093 &CapturedBytesToFlush,
3094 &LocalStatusBlock);
3095
3096 //
3097 // Release reference
3098 //
3099 ObDereferenceObject(Process);
3100
3101 //
3102 // Enter SEH to return data
3103 //
3104 _SEH2_TRY
3105 {
3106 //
3107 // Return data to user
3108 //
3109 *BaseAddress = PAGE_ALIGN(CapturedBaseAddress);
3110 *NumberOfBytesToFlush = 0;
3111 *IoStatusBlock = LocalStatusBlock;
3112 }
3113 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
3114 {
3115 }
3116 _SEH2_END;
3117
3118 //
3119 // Return status
3120 //
3121 return Status;
3122 }
3123
3124 /*
3125 * @unimplemented
3126 */
3127 NTSTATUS
3128 NTAPI
3129 NtGetWriteWatch(IN HANDLE ProcessHandle,
3130 IN ULONG Flags,
3131 IN PVOID BaseAddress,
3132 IN SIZE_T RegionSize,
3133 IN PVOID *UserAddressArray,
3134 OUT PULONG_PTR EntriesInUserAddressArray,
3135 OUT PULONG Granularity)
3136 {
3137 PEPROCESS Process;
3138 NTSTATUS Status;
3139 PVOID EndAddress;
3140 KPROCESSOR_MODE PreviousMode = ExGetPreviousMode();
3141 ULONG_PTR CapturedEntryCount;
3142 PAGED_CODE();
3143
3144 //
3145 // Check if we came from user mode
3146 //
3147 if (PreviousMode != KernelMode)
3148 {
3149 //
3150 // Enter SEH for probing
3151 //
3152 _SEH2_TRY
3153 {
3154 //
3155 // Catch illegal base address
3156 //
3157 if (BaseAddress > MM_HIGHEST_USER_ADDRESS) return STATUS_INVALID_PARAMETER_2;
3158
3159 //
3160 // Catch illegal region size
3161 //
3162 if ((MmUserProbeAddress - (ULONG_PTR)BaseAddress) < RegionSize)
3163 {
3164 //
3165 // Fail
3166 //
3167 return STATUS_INVALID_PARAMETER_3;
3168 }
3169
3170 //
3171 // Validate all data
3172 //
3173 ProbeForWriteSize_t(EntriesInUserAddressArray);
3174 ProbeForWriteUlong(Granularity);
3175
3176 //
3177 // Capture them
3178 //
3179 CapturedEntryCount = *EntriesInUserAddressArray;
3180
3181 //
3182 // Must have a count
3183 //
3184 if (CapturedEntryCount == 0) return STATUS_INVALID_PARAMETER_5;
3185
3186 //
3187 // Can't be larger than the maximum
3188 //
3189 if (CapturedEntryCount > (MAXULONG_PTR / sizeof(ULONG_PTR)))
3190 {
3191 //
3192 // Fail
3193 //
3194 return STATUS_INVALID_PARAMETER_5;
3195 }
3196
3197 //
3198 // Probe the actual array
3199 //
3200 ProbeForWrite(UserAddressArray,
3201 CapturedEntryCount * sizeof(PVOID),
3202 sizeof(PVOID));
3203 }
3204 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
3205 {
3206 //
3207 // Get exception code
3208 //
3209 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3210 }
3211 _SEH2_END;
3212 }
3213 else
3214 {
3215 //
3216 // Capture directly
3217 //
3218 CapturedEntryCount = *EntriesInUserAddressArray;
3219 ASSERT(CapturedEntryCount != 0);
3220 }
3221
3222 //
3223 // Check if this is a local request
3224 //
3225 if (ProcessHandle == NtCurrentProcess())
3226 {
3227 //
3228 // No need to reference the process
3229 //
3230 Process = PsGetCurrentProcess();
3231 }
3232 else
3233 {
3234 //
3235 // Reference the target
3236 //
3237 Status = ObReferenceObjectByHandle(ProcessHandle,
3238 PROCESS_VM_OPERATION,
3239 PsProcessType,
3240 PreviousMode,
3241 (PVOID *)&Process,
3242 NULL);
3243 if (!NT_SUCCESS(Status)) return Status;
3244 }
3245
3246 //
3247 // Compute the last address and validate it
3248 //
3249 EndAddress = (PVOID)((ULONG_PTR)BaseAddress + RegionSize - 1);
3250 if (BaseAddress > EndAddress)
3251 {
3252 //
3253 // Fail
3254 //
3255 if (ProcessHandle != NtCurrentProcess()) ObDereferenceObject(Process);
3256 return STATUS_INVALID_PARAMETER_4;
3257 }
3258
3259 //
3260 // Oops :(
3261 //
3262 UNIMPLEMENTED;
3263
3264 //
3265 // Dereference if needed
3266 //
3267 if (ProcessHandle != NtCurrentProcess()) ObDereferenceObject(Process);
3268
3269 //
3270 // Enter SEH to return data
3271 //
3272 _SEH2_TRY
3273 {
3274 //
3275 // Return data to user
3276 //
3277 *EntriesInUserAddressArray = 0;
3278 *Granularity = PAGE_SIZE;
3279 }
3280 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
3281 {
3282 //
3283 // Get exception code
3284 //
3285 Status = _SEH2_GetExceptionCode();
3286 }
3287 _SEH2_END;
3288
3289 //
3290 // Return success
3291 //
3292 return STATUS_SUCCESS;
3293 }
3294
3295 /*
3296 * @unimplemented
3297 */
3298 NTSTATUS
3299 NTAPI
3300 NtResetWriteWatch(IN HANDLE ProcessHandle,
3301 IN PVOID BaseAddress,
3302 IN SIZE_T RegionSize)
3303 {
3304 PVOID EndAddress;
3305 PEPROCESS Process;
3306 NTSTATUS Status;
3307 KPROCESSOR_MODE PreviousMode = ExGetPreviousMode();
3308 ASSERT (KeGetCurrentIrql() == PASSIVE_LEVEL);
3309
3310 //
3311 // Catch illegal base address
3312 //
3313 if (BaseAddress > MM_HIGHEST_USER_ADDRESS) return STATUS_INVALID_PARAMETER_2;
3314
3315 //
3316 // Catch illegal region size
3317 //
3318 if ((MmUserProbeAddress - (ULONG_PTR)BaseAddress) < RegionSize)
3319 {
3320 //
3321 // Fail
3322 //
3323 return STATUS_INVALID_PARAMETER_3;
3324 }
3325
3326 //
3327 // Check if this is a local request
3328 //
3329 if (ProcessHandle == NtCurrentProcess())
3330 {
3331 //
3332 // No need to reference the process
3333 //
3334 Process = PsGetCurrentProcess();
3335 }
3336 else
3337 {
3338 //
3339 // Reference the target
3340 //
3341 Status = ObReferenceObjectByHandle(ProcessHandle,
3342 PROCESS_VM_OPERATION,
3343 PsProcessType,
3344 PreviousMode,
3345 (PVOID *)&Process,
3346 NULL);
3347 if (!NT_SUCCESS(Status)) return Status;
3348 }
3349
3350 //
3351 // Compute the last address and validate it
3352 //
3353 EndAddress = (PVOID)((ULONG_PTR)BaseAddress + RegionSize - 1);
3354 if (BaseAddress > EndAddress)
3355 {
3356 //
3357 // Fail
3358 //
3359 if (ProcessHandle != NtCurrentProcess()) ObDereferenceObject(Process);
3360 return STATUS_INVALID_PARAMETER_3;
3361 }
3362
3363 //
3364 // Oops :(
3365 //
3366 UNIMPLEMENTED;
3367
3368 //
3369 // Dereference if needed
3370 //
3371 if (ProcessHandle != NtCurrentProcess()) ObDereferenceObject(Process);
3372
3373 //
3374 // Return success
3375 //
3376 return STATUS_SUCCESS;
3377 }
3378
3379 NTSTATUS
3380 NTAPI
3381 NtQueryVirtualMemory(IN HANDLE ProcessHandle,
3382 IN PVOID BaseAddress,
3383 IN MEMORY_INFORMATION_CLASS MemoryInformationClass,
3384 OUT PVOID MemoryInformation,
3385 IN SIZE_T MemoryInformationLength,
3386 OUT PSIZE_T ReturnLength)
3387 {
3388 NTSTATUS Status = STATUS_SUCCESS;
3389 KPROCESSOR_MODE PreviousMode;
3390
3391 DPRINT("Querying class %d about address: %p\n", MemoryInformationClass, BaseAddress);
3392
3393 /* Bail out if the address is invalid */
3394 if (BaseAddress > MM_HIGHEST_USER_ADDRESS) return STATUS_INVALID_PARAMETER;
3395
3396 /* Probe return buffer */
3397 PreviousMode = ExGetPreviousMode();
3398 if (PreviousMode != KernelMode)
3399 {
3400 _SEH2_TRY
3401 {
3402 ProbeForWrite(MemoryInformation,
3403 MemoryInformationLength,
3404 sizeof(ULONG_PTR));
3405
3406 if (ReturnLength) ProbeForWriteSize_t(ReturnLength);
3407 }
3408 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
3409 {
3410 Status = _SEH2_GetExceptionCode();
3411 }
3412 _SEH2_END;
3413
3414 if (!NT_SUCCESS(Status))
3415 {
3416 return Status;
3417 }
3418 }
3419
3420 switch(MemoryInformationClass)
3421 {
3422 case MemoryBasicInformation:
3423 /* Validate the size information of the class */
3424 if (MemoryInformationLength < sizeof(MEMORY_BASIC_INFORMATION))
3425 {
3426 /* The size is invalid */
3427 return STATUS_INFO_LENGTH_MISMATCH;
3428 }
3429 Status = MiQueryMemoryBasicInformation(ProcessHandle,
3430 BaseAddress,
3431 MemoryInformation,
3432 MemoryInformationLength,
3433 ReturnLength);
3434 break;
3435
3436 case MemorySectionName:
3437 /* Validate the size information of the class */
3438 if (MemoryInformationLength < sizeof(MEMORY_SECTION_NAME))
3439 {
3440 /* The size is invalid */
3441 return STATUS_INFO_LENGTH_MISMATCH;
3442 }
3443 Status = MiQueryMemorySectionName(ProcessHandle,
3444 BaseAddress,
3445 MemoryInformation,
3446 MemoryInformationLength,
3447 ReturnLength);
3448 break;
3449 case MemoryWorkingSetList:
3450 case MemoryBasicVlmInformation:
3451 default:
3452 DPRINT1("Unhandled memory information class %d\n", MemoryInformationClass);
3453 break;
3454 }
3455
3456 return Status;
3457 }
3458
3459 /*
3460 * @implemented
3461 */
3462 NTSTATUS
3463 NTAPI
3464 NtAllocateVirtualMemory(IN HANDLE ProcessHandle,
3465 IN OUT PVOID* UBaseAddress,
3466 IN ULONG_PTR ZeroBits,
3467 IN OUT PSIZE_T URegionSize,
3468 IN ULONG AllocationType,
3469 IN ULONG Protect)
3470 {
3471 PEPROCESS Process;
3472 PMEMORY_AREA MemoryArea;
3473 PFN_NUMBER PageCount;
3474 PMMVAD Vad, FoundVad;
3475 PUSHORT UsedPageTableEntries;
3476 NTSTATUS Status;
3477 PMMSUPPORT AddressSpace;
3478 PVOID PBaseAddress;
3479 ULONG_PTR PRegionSize, StartingAddress, EndingAddress;
3480 PEPROCESS CurrentProcess = PsGetCurrentProcess();
3481 KPROCESSOR_MODE PreviousMode = KeGetPreviousMode();
3482 PETHREAD CurrentThread = PsGetCurrentThread();
3483 KAPC_STATE ApcState;
3484 ULONG ProtectionMask, QuotaCharge = 0, QuotaFree = 0;
3485 BOOLEAN Attached = FALSE, ChangeProtection = FALSE;
3486 MMPTE TempPte;
3487 PMMPTE PointerPte, PointerPde, LastPte;
3488 PAGED_CODE();
3489
3490 /* Check for valid Zero bits */
3491 if (ZeroBits > 21)
3492 {
3493 DPRINT1("Too many zero bits\n");
3494 return STATUS_INVALID_PARAMETER_3;
3495 }
3496
3497 /* Check for valid Allocation Types */
3498 if ((AllocationType & ~(MEM_COMMIT | MEM_RESERVE | MEM_RESET | MEM_PHYSICAL |
3499 MEM_TOP_DOWN | MEM_WRITE_WATCH)))
3500 {
3501 DPRINT1("Invalid Allocation Type\n");
3502 return STATUS_INVALID_PARAMETER_5;
3503 }
3504
3505 /* Check for at least one of these Allocation Types to be set */
3506 if (!(AllocationType & (MEM_COMMIT | MEM_RESERVE | MEM_RESET)))
3507 {
3508 DPRINT1("No memory allocation base type\n");
3509 return STATUS_INVALID_PARAMETER_5;
3510 }
3511
3512 /* MEM_RESET is an exclusive flag, make sure that is valid too */
3513 if ((AllocationType & MEM_RESET) && (AllocationType != MEM_RESET))
3514 {
3515 DPRINT1("Invalid use of MEM_RESET\n");
3516 return STATUS_INVALID_PARAMETER_5;
3517 }
3518
3519 /* Check if large pages are being used */
3520 if (AllocationType & MEM_LARGE_PAGES)
3521 {
3522 /* Large page allocations MUST be committed */
3523 if (!(AllocationType & MEM_COMMIT))
3524 {
3525 DPRINT1("Must supply MEM_COMMIT with MEM_LARGE_PAGES\n");
3526 return STATUS_INVALID_PARAMETER_5;
3527 }
3528
3529 /* These flags are not allowed with large page allocations */
3530 if (AllocationType & (MEM_PHYSICAL | MEM_RESET | MEM_WRITE_WATCH))
3531 {
3532 DPRINT1("Using illegal flags with MEM_LARGE_PAGES\n");
3533 return STATUS_INVALID_PARAMETER_5;
3534 }
3535 }
3536
3537 /* MEM_WRITE_WATCH can only be used if MEM_RESERVE is also used */
3538 if ((AllocationType & MEM_WRITE_WATCH) && !(AllocationType & MEM_RESERVE))
3539 {
3540 DPRINT1("MEM_WRITE_WATCH used without MEM_RESERVE\n");
3541 return STATUS_INVALID_PARAMETER_5;
3542 }
3543
3544 /* MEM_PHYSICAL can only be used if MEM_RESERVE is also used */
3545 if ((AllocationType & MEM_PHYSICAL) && !(AllocationType & MEM_RESERVE))
3546 {
3547 DPRINT1("MEM_WRITE_WATCH used without MEM_RESERVE\n");
3548 return STATUS_INVALID_PARAMETER_5;
3549 }
3550
3551 /* Check for valid MEM_PHYSICAL usage */
3552 if (AllocationType & MEM_PHYSICAL)
3553 {
3554 /* Only these flags are allowed with MEM_PHYSIAL */
3555 if (AllocationType & ~(MEM_RESERVE | MEM_TOP_DOWN | MEM_PHYSICAL))
3556 {
3557 DPRINT1("Using illegal flags with MEM_PHYSICAL\n");
3558 return STATUS_INVALID_PARAMETER_5;
3559 }
3560
3561 /* Then make sure PAGE_READWRITE is used */
3562 if (Protect != PAGE_READWRITE)
3563 {
3564 DPRINT1("MEM_PHYSICAL used without PAGE_READWRITE\n");
3565 return STATUS_INVALID_PARAMETER_6;
3566 }
3567 }
3568
3569 //
3570 // Force PAGE_READWRITE for everything, for now
3571 //
3572 Protect = PAGE_READWRITE;
3573
3574 /* Calculate the protection mask and make sure it's valid */
3575 ProtectionMask = MiMakeProtectionMask(Protect);
3576 if (ProtectionMask == MM_INVALID_PROTECTION)
3577 {
3578 DPRINT1("Invalid protection mask\n");
3579 return STATUS_INVALID_PAGE_PROTECTION;
3580 }
3581
3582 /* Enter SEH */
3583 _SEH2_TRY
3584 {
3585 /* Check for user-mode parameters */
3586 if (PreviousMode != KernelMode)
3587 {
3588 /* Make sure they are writable */
3589 ProbeForWritePointer(UBaseAddress);
3590 ProbeForWriteUlong(URegionSize);
3591 }
3592
3593 /* Capture their values */
3594 PBaseAddress = *UBaseAddress;
3595 PRegionSize = *URegionSize;
3596 }
3597 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
3598 {
3599 /* Return the exception code */
3600 _SEH2_YIELD(return _SEH2_GetExceptionCode());
3601 }
3602 _SEH2_END;
3603
3604 /* Make sure the allocation isn't past the VAD area */
3605 if (PBaseAddress >= MM_HIGHEST_VAD_ADDRESS)
3606 {
3607 DPRINT1("Virtual allocation base above User Space\n");
3608 return STATUS_INVALID_PARAMETER_2;
3609 }
3610
3611 /* Make sure the allocation wouldn't overflow past the VAD area */
3612 if ((((ULONG_PTR)MM_HIGHEST_VAD_ADDRESS + 1) - (ULONG_PTR)PBaseAddress) < PRegionSize)
3613 {
3614 DPRINT1("Region size would overflow into kernel-memory\n");
3615 return STATUS_INVALID_PARAMETER_4;
3616 }
3617
3618 /* Make sure there's a size specified */
3619 if (!PRegionSize)
3620 {
3621 DPRINT1("Region size is invalid (zero)\n");
3622 return STATUS_INVALID_PARAMETER_4;
3623 }
3624
3625 //
3626 // If this is for the current process, just use PsGetCurrentProcess
3627 //
3628 if (ProcessHandle == NtCurrentProcess())
3629 {
3630 Process = CurrentProcess;
3631 }
3632 else
3633 {
3634 //
3635 // Otherwise, reference the process with VM rights and attach to it if
3636 // this isn't the current process. We must attach because we'll be touching
3637 // PTEs and PDEs that belong to user-mode memory, and also touching the
3638 // Working Set which is stored in Hyperspace.
3639 //
3640 Status = ObReferenceObjectByHandle(ProcessHandle,
3641 PROCESS_VM_OPERATION,
3642 PsProcessType,
3643 PreviousMode,
3644 (PVOID*)&Process,
3645 NULL);
3646 if (!NT_SUCCESS(Status)) return Status;
3647 if (CurrentProcess != Process)
3648 {
3649 KeStackAttachProcess(&Process->Pcb, &ApcState);
3650 Attached = TRUE;
3651 }
3652 }
3653
3654 //
3655 // Check for large page allocations and make sure that the required privilege
3656 // is being held, before attempting to handle them.
3657 //
3658 if ((AllocationType & MEM_LARGE_PAGES) &&
3659 !(SeSinglePrivilegeCheck(SeLockMemoryPrivilege, PreviousMode)))
3660 {
3661 /* Fail without it */
3662 DPRINT1("Privilege not held for MEM_LARGE_PAGES\n");
3663 Status = STATUS_PRIVILEGE_NOT_HELD;
3664 goto FailPathNoLock;
3665 }
3666
3667 //
3668 // Assert on the things we don't yet support
3669 //
3670 ASSERT(ZeroBits == 0);
3671 ASSERT((AllocationType & MEM_LARGE_PAGES) == 0);
3672 ASSERT((AllocationType & MEM_PHYSICAL) == 0);
3673 ASSERT((AllocationType & MEM_WRITE_WATCH) == 0);
3674 ASSERT((AllocationType & MEM_TOP_DOWN) == 0);
3675 ASSERT((AllocationType & MEM_RESET) == 0);
3676 ASSERT(Process->VmTopDown == 0);
3677
3678 //
3679 // Check if the caller is reserving memory, or committing memory and letting
3680 // us pick the base address
3681 //
3682 if (!(PBaseAddress) || (AllocationType & MEM_RESERVE))
3683 {
3684 //
3685 // Do not allow COPY_ON_WRITE through this API
3686 //
3687 if ((Protect & PAGE_WRITECOPY) || (Protect & PAGE_EXECUTE_WRITECOPY))
3688 {
3689 DPRINT1("Copy on write not allowed through this path\n");
3690 Status = STATUS_INVALID_PAGE_PROTECTION;
3691 goto FailPathNoLock;
3692 }
3693
3694 //
3695 // Does the caller have an address in mind, or is this a blind commit?
3696 //
3697 if (!PBaseAddress)
3698 {
3699 //
3700 // This is a blind commit, all we need is the region size
3701 //
3702 PRegionSize = ROUND_TO_PAGES(PRegionSize);
3703 PageCount = BYTES_TO_PAGES(PRegionSize);
3704 EndingAddress = 0;
3705 StartingAddress = 0;
3706 }
3707 else
3708 {
3709 //
3710 // This is a reservation, so compute the starting address on the
3711 // expected 64KB granularity, and see where the ending address will
3712 // fall based on the aligned address and the passed in region size
3713 //
3714 StartingAddress = ROUND_DOWN((ULONG_PTR)PBaseAddress, _64K);
3715 EndingAddress = ((ULONG_PTR)PBaseAddress + PRegionSize - 1) | (PAGE_SIZE - 1);
3716 PageCount = BYTES_TO_PAGES(EndingAddress - StartingAddress);
3717 }
3718
3719 //
3720 // Allocate and initialize the VAD
3721 //
3722 Vad = ExAllocatePoolWithTag(NonPagedPool, sizeof(MMVAD_LONG), 'SdaV');
3723 ASSERT(Vad != NULL);
3724 Vad->u.LongFlags = 0;
3725 if (AllocationType & MEM_COMMIT) Vad->u.VadFlags.MemCommit = 1;
3726 Vad->u.VadFlags.Protection = ProtectionMask;
3727 Vad->u.VadFlags.PrivateMemory = 1;
3728 Vad->u.VadFlags.CommitCharge = AllocationType & MEM_COMMIT ? PageCount : 0;
3729
3730 //
3731 // Lock the address space and make sure the process isn't already dead
3732 //
3733 AddressSpace = MmGetCurrentAddressSpace();
3734 MmLockAddressSpace(AddressSpace);
3735 if (Process->VmDeleted)
3736 {
3737 Status = STATUS_PROCESS_IS_TERMINATING;
3738 goto FailPath;
3739 }
3740
3741 //
3742 // Did we have a base address? If no, find a valid address that is 64KB
3743 // aligned in the VAD tree. Otherwise, make sure that the address range
3744 // which was passed in isn't already conflicting with an existing address
3745 // range.
3746 //
3747 if (!PBaseAddress)
3748 {
3749 Status = MiFindEmptyAddressRangeInTree(PRegionSize,
3750 _64K,
3751 &Process->VadRoot,
3752 (PMMADDRESS_NODE*)&Process->VadFreeHint,
3753 &StartingAddress);
3754 if (!NT_SUCCESS(Status)) goto FailPath;
3755
3756 //
3757 // Now we know where the allocation ends. Make sure it doesn't end up
3758 // somewhere in kernel mode.
3759 //
3760 EndingAddress = ((ULONG_PTR)StartingAddress + PRegionSize - 1) | (PAGE_SIZE - 1);
3761 if ((PVOID)EndingAddress > MM_HIGHEST_VAD_ADDRESS)
3762 {
3763 Status = STATUS_NO_MEMORY;
3764 goto FailPath;
3765 }
3766 }
3767 else if (MiCheckForConflictingNode(StartingAddress >> PAGE_SHIFT,
3768 EndingAddress >> PAGE_SHIFT,
3769 &Process->VadRoot))
3770 {
3771 //
3772 // The address specified is in conflict!
3773 //
3774 Status = STATUS_CONFLICTING_ADDRESSES;
3775 goto FailPath;
3776 }
3777
3778 //
3779 // Write out the VAD fields for this allocation
3780 //
3781 Vad->StartingVpn = (ULONG_PTR)StartingAddress >> PAGE_SHIFT;
3782 Vad->EndingVpn = (ULONG_PTR)EndingAddress >> PAGE_SHIFT;
3783
3784 //
3785 // FIXME: Should setup VAD bitmap
3786 //
3787 Status = STATUS_SUCCESS;
3788
3789 //
3790 // Lock the working set and insert the VAD into the process VAD tree
3791 //
3792 MiLockProcessWorkingSet(Process, CurrentThread);
3793 Vad->ControlArea = NULL; // For Memory-Area hack
3794 MiInsertVad(Vad, Process);
3795 MiUnlockProcessWorkingSet(Process, CurrentThread);
3796
3797 //
3798 // Update the virtual size of the process, and if this is now the highest
3799 // virtual size we have ever seen, update the peak virtual size to reflect
3800 // this.
3801 //
3802 Process->VirtualSize += PRegionSize;
3803 if (Process->VirtualSize > Process->PeakVirtualSize)
3804 {
3805 Process->PeakVirtualSize = Process->VirtualSize;
3806 }
3807
3808 //
3809 // Release address space and detach and dereference the target process if
3810 // it was different from the current process
3811 //
3812 MmUnlockAddressSpace(AddressSpace);
3813 if (Attached) KeUnstackDetachProcess(&ApcState);
3814 if (ProcessHandle != NtCurrentProcess()) ObDereferenceObject(Process);
3815
3816 //
3817 // Use SEH to write back the base address and the region size. In the case
3818 // of an exception, we do not return back the exception code, as the memory
3819 // *has* been allocated. The caller would now have to call VirtualQuery
3820 // or do some other similar trick to actually find out where its memory
3821 // allocation ended up
3822 //
3823 _SEH2_TRY
3824 {
3825 *URegionSize = PRegionSize;
3826 *UBaseAddress = (PVOID)StartingAddress;
3827 }
3828 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
3829 {
3830 }
3831 _SEH2_END;
3832 return STATUS_SUCCESS;
3833 }
3834
3835 //
3836 // This is a MEM_COMMIT on top of an existing address which must have been
3837 // MEM_RESERVED already. Compute the start and ending base addresses based
3838 // on the user input, and then compute the actual region size once all the
3839 // alignments have been done.
3840 //
3841 StartingAddress = (ULONG_PTR)PAGE_ALIGN(PBaseAddress);
3842 EndingAddress = (((ULONG_PTR)PBaseAddress + PRegionSize - 1) | (PAGE_SIZE - 1));
3843 PRegionSize = EndingAddress - StartingAddress + 1;
3844
3845 //
3846 // Lock the address space and make sure the process isn't already dead
3847 //
3848 AddressSpace = MmGetCurrentAddressSpace();
3849 MmLockAddressSpace(AddressSpace);
3850 if (Process->VmDeleted)
3851 {
3852 DPRINT1("Process is dying\n");
3853 Status = STATUS_PROCESS_IS_TERMINATING;
3854 goto FailPath;
3855 }
3856
3857 //
3858 // Get the VAD for this address range, and make sure it exists
3859 //
3860 FoundVad = (PMMVAD)MiCheckForConflictingNode(StartingAddress >> PAGE_SHIFT,
3861 EndingAddress >> PAGE_SHIFT,
3862 &Process->VadRoot);
3863 if (!FoundVad)
3864 {
3865 DPRINT1("Could not find a VAD for this allocation\n");
3866 Status = STATUS_CONFLICTING_ADDRESSES;
3867 goto FailPath;
3868 }
3869
3870 //
3871 // These kinds of VADs are illegal for this Windows function when trying to
3872 // commit an existing range
3873 //
3874 if ((FoundVad->u.VadFlags.VadType == VadAwe) ||
3875 (FoundVad->u.VadFlags.VadType == VadDevicePhysicalMemory) ||
3876 (FoundVad->u.VadFlags.VadType == VadLargePages))
3877 {
3878 DPRINT1("Illegal VAD for attempting a MEM_COMMIT\n");
3879 Status = STATUS_CONFLICTING_ADDRESSES;
3880 goto FailPath;
3881 }
3882
3883 //
3884 // Make sure that this address range actually fits within the VAD for it
3885 //
3886 if (((StartingAddress >> PAGE_SHIFT) < FoundVad->StartingVpn) &&
3887 ((EndingAddress >> PAGE_SHIFT) > FoundVad->EndingVpn))
3888 {
3889 DPRINT1("Address range does not fit into the VAD\n");
3890 Status = STATUS_CONFLICTING_ADDRESSES;
3891 goto FailPath;
3892 }
3893
3894 //
3895 // If this is an existing section view, we call the old RosMm routine which
3896 // has the relevant code required to handle the section scenario. In the future
3897 // we will limit this even more so that there's almost nothing that the code
3898 // needs to do, and it will become part of section.c in RosMm
3899 //
3900 MemoryArea = MmLocateMemoryAreaByAddress(AddressSpace, (PVOID)PAGE_ROUND_DOWN(PBaseAddress));
3901 if (MemoryArea->Type != MEMORY_AREA_OWNED_BY_ARM3)
3902 {
3903 return MiRosAllocateVirtualMemory(ProcessHandle,
3904 Process,
3905 MemoryArea,
3906 AddressSpace,
3907 UBaseAddress,
3908 Attached,
3909 URegionSize,
3910 AllocationType,
3911 Protect);
3912 }
3913
3914 // Is this a previously reserved section being committed? If so, enter the
3915 // special section path
3916 //
3917 if (FoundVad->u.VadFlags.PrivateMemory == FALSE)
3918 {
3919 //
3920 // You cannot commit large page sections through this API
3921 //
3922 if (FoundVad->u.VadFlags.VadType == VadLargePageSection)
3923 {
3924 DPRINT1("Large page sections cannot be VirtualAlloc'd\n");
3925 Status = STATUS_INVALID_PAGE_PROTECTION;
3926 goto FailPath;
3927 }
3928
3929 //
3930 // You can only use caching flags on a rotate VAD
3931 //
3932 if ((Protect & (PAGE_NOCACHE | PAGE_WRITECOMBINE)) &&
3933 (FoundVad->u.VadFlags.VadType != VadRotatePhysical))
3934 {
3935 DPRINT1("Cannot use caching flags with anything but rotate VADs\n");
3936 Status = STATUS_INVALID_PAGE_PROTECTION;
3937 goto FailPath;
3938 }
3939
3940 //
3941 // We should make sure that the section's permissions aren't being messed with
3942 //
3943 if (FoundVad->u.VadFlags.NoChange)
3944 {
3945 DPRINT1("SEC_NO_CHANGE section being touched. Assuming this is ok\n");
3946 }
3947
3948 //
3949 // ARM3 does not support file-backed sections, only shared memory
3950 //
3951 ASSERT(FoundVad->ControlArea->FilePointer == NULL);
3952
3953 //
3954 // Rotate VADs cannot be guard pages or inaccessible, nor copy on write
3955 //
3956 if ((FoundVad->u.VadFlags.VadType == VadRotatePhysical) &&
3957 (Protect & (PAGE_WRITECOPY | PAGE_EXECUTE_WRITECOPY | PAGE_NOACCESS | PAGE_GUARD)))
3958 {
3959 DPRINT1("Invalid page protection for rotate VAD\n");
3960 Status = STATUS_INVALID_PAGE_PROTECTION;
3961 goto FailPath;
3962 }
3963
3964 //
3965 // Compute PTE addresses and the quota charge, then grab the commit lock
3966 //
3967 PointerPte = MI_GET_PROTOTYPE_PTE_FOR_VPN(FoundVad, StartingAddress >> PAGE_SHIFT);
3968 LastPte = MI_GET_PROTOTYPE_PTE_FOR_VPN(FoundVad, EndingAddress >> PAGE_SHIFT);
3969 QuotaCharge = (ULONG)(LastPte - PointerPte + 1);
3970 KeAcquireGuardedMutexUnsafe(&MmSectionCommitMutex);
3971
3972 //
3973 // Get the segment template PTE and start looping each page
3974 //
3975 TempPte = FoundVad->ControlArea->Segment->SegmentPteTemplate;
3976 ASSERT(TempPte.u.Long != 0);
3977 while (PointerPte <= LastPte)
3978 {
3979 //
3980 // For each non-already-committed page, write the invalid template PTE
3981 //
3982 if (PointerPte->u.Long == 0)
3983 {
3984 MI_WRITE_INVALID_PTE(PointerPte, TempPte);
3985 }
3986 else
3987 {
3988 QuotaFree++;
3989 }
3990 PointerPte++;
3991 }
3992
3993 //
3994 // Now do the commit accounting and release the lock
3995 //
3996 ASSERT(QuotaCharge >= QuotaFree);
3997 QuotaCharge -= QuotaFree;
3998 FoundVad->ControlArea->Segment->NumberOfCommittedPages += QuotaCharge;
3999 KeReleaseGuardedMutexUnsafe(&MmSectionCommitMutex);
4000
4001 //
4002 // We are done with committing the section pages
4003 //
4004 Status = STATUS_SUCCESS;
4005 goto FailPath;
4006 }
4007
4008 //
4009 // This is a specific ReactOS check because we only use normal VADs
4010 //
4011 ASSERT(FoundVad->u.VadFlags.VadType == VadNone);
4012
4013 //
4014 // While this is an actual Windows check
4015 //
4016 ASSERT(FoundVad->u.VadFlags.VadType != VadRotatePhysical);
4017
4018 //
4019 // Throw out attempts to use copy-on-write through this API path
4020 //
4021 if ((Protect & PAGE_WRITECOPY) || (Protect & PAGE_EXECUTE_WRITECOPY))
4022 {
4023 DPRINT1("Write copy attempted when not allowed\n");
4024 Status = STATUS_INVALID_PAGE_PROTECTION;
4025 goto FailPath;
4026 }
4027
4028 //
4029 // Initialize a demand-zero PTE
4030 //
4031 TempPte.u.Long = 0;
4032 TempPte.u.Soft.Protection = ProtectionMask;
4033
4034 //
4035 // Get the PTE, PDE and the last PTE for this address range
4036 //
4037 PointerPde = MiAddressToPde(StartingAddress);
4038 PointerPte = MiAddressToPte(StartingAddress);
4039 LastPte = MiAddressToPte(EndingAddress);
4040
4041 //
4042 // Update the commit charge in the VAD as well as in the process, and check
4043 // if this commit charge was now higher than the last recorded peak, in which
4044 // case we also update the peak
4045 //
4046 FoundVad->u.VadFlags.CommitCharge += (1 + LastPte - PointerPte);
4047 Process->CommitCharge += (1 + LastPte - PointerPte);
4048 if (Process->CommitCharge > Process->CommitChargePeak)
4049 {
4050 Process->CommitChargePeak = Process->CommitCharge;
4051 }
4052
4053 //
4054 // Lock the working set while we play with user pages and page tables
4055 //
4056 //MiLockWorkingSet(CurrentThread, AddressSpace);
4057
4058 //
4059 // Make the current page table valid, and then loop each page within it
4060 //
4061 MiMakePdeExistAndMakeValid(PointerPde, Process, MM_NOIRQL);
4062 while (PointerPte <= LastPte)
4063 {
4064 //
4065 // Have we crossed into a new page table?
4066 //
4067 if (!(((ULONG_PTR)PointerPte) & (SYSTEM_PD_SIZE - 1)))
4068 {
4069 //
4070 // Get the PDE and now make it valid too
4071 //
4072 PointerPde = MiAddressToPte(PointerPte);
4073 MiMakePdeExistAndMakeValid(PointerPde, Process, MM_NOIRQL);
4074 }
4075
4076 //
4077 // Is this a zero PTE as expected?
4078 //
4079 if (PointerPte->u.Long == 0)
4080 {
4081 //
4082 // First increment the count of pages in the page table for this
4083 // process
4084 //
4085 UsedPageTableEntries = &MmWorkingSetList->UsedPageTableEntries[MiGetPdeOffset(MiPteToAddress(PointerPte))];
4086 (*UsedPageTableEntries)++;
4087 ASSERT((*UsedPageTableEntries) <= PTE_COUNT);
4088
4089 //
4090 // And now write the invalid demand-zero PTE as requested
4091 //
4092 MI_WRITE_INVALID_PTE(PointerPte, TempPte);
4093 }
4094 else if (PointerPte->u.Long == MmDecommittedPte.u.Long)
4095 {
4096 //
4097 // If the PTE was already decommitted, there is nothing else to do
4098 // but to write the new demand-zero PTE
4099 //
4100 MI_WRITE_INVALID_PTE(PointerPte, TempPte);
4101 }
4102 else if (!(ChangeProtection) && (Protect != MiGetPageProtection(PointerPte)))
4103 {
4104 //
4105 // We don't handle these scenarios yet
4106 //
4107 if (PointerPte->u.Soft.Valid == 0)
4108 {
4109 ASSERT(PointerPte->u.Soft.Prototype == 0);
4110 ASSERT(PointerPte->u.Soft.PageFileHigh == 0);
4111 }
4112
4113 //
4114 // There's a change in protection, remember this for later, but do
4115 // not yet handle it.
4116 //
4117 DPRINT1("Protection change to: 0x%lx not implemented\n", Protect);
4118 ChangeProtection = TRUE;
4119 }
4120
4121 //
4122 // Move to the next PTE
4123 //
4124 PointerPte++;
4125 }
4126
4127 //
4128 // This path is not yet handled
4129 //
4130 ASSERT(ChangeProtection == FALSE);
4131
4132 //
4133 // Release the working set lock, unlock the address space, and detach from
4134 // the target process if it was not the current process. Also dereference the
4135 // target process if this wasn't the case.
4136 //
4137 //MiUnlockProcessWorkingSet(Process, CurrentThread);
4138 Status = STATUS_SUCCESS;
4139 FailPath:
4140 MmUnlockAddressSpace(AddressSpace);
4141 FailPathNoLock:
4142 if (Attached) KeUnstackDetachProcess(&ApcState);
4143 if (ProcessHandle != NtCurrentProcess()) ObDereferenceObject(Process);
4144
4145 //
4146 // Use SEH to write back the base address and the region size. In the case
4147 // of an exception, we strangely do return back the exception code, even
4148 // though the memory *has* been allocated. This mimics Windows behavior and
4149 // there is not much we can do about it.
4150 //
4151 _SEH2_TRY
4152 {
4153 *URegionSize = PRegionSize;
4154 *UBaseAddress = (PVOID)StartingAddress;
4155 }
4156 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
4157 {
4158 Status = _SEH2_GetExceptionCode();
4159 }
4160 _SEH2_END;
4161 return Status;
4162 }
4163
4164 /*
4165 * @implemented
4166 */
4167 NTSTATUS
4168 NTAPI
4169 NtFreeVirtualMemory(IN HANDLE ProcessHandle,
4170 IN PVOID* UBaseAddress,
4171 IN PSIZE_T URegionSize,
4172 IN ULONG FreeType)
4173 {
4174 PMEMORY_AREA MemoryArea;
4175 SIZE_T PRegionSize;
4176 PVOID PBaseAddress;
4177 ULONG_PTR CommitReduction = 0;
4178 ULONG_PTR StartingAddress, EndingAddress;
4179 PMMVAD Vad;
4180 NTSTATUS Status;
4181 PEPROCESS Process;
4182 PMMSUPPORT AddressSpace;
4183 PETHREAD CurrentThread = PsGetCurrentThread();
4184 PEPROCESS CurrentProcess = PsGetCurrentProcess();
4185 KPROCESSOR_MODE PreviousMode = KeGetPreviousMode();
4186 KAPC_STATE ApcState;
4187 BOOLEAN Attached = FALSE;
4188 PAGED_CODE();
4189
4190 //
4191 // Only two flags are supported
4192 //
4193 if (!(FreeType & (MEM_RELEASE | MEM_DECOMMIT)))
4194 {
4195 DPRINT1("Invalid FreeType\n");
4196 return STATUS_INVALID_PARAMETER_4;
4197 }
4198
4199 //
4200 // Check if no flag was used, or if both flags were used
4201 //
4202 if (!((FreeType & (MEM_DECOMMIT | MEM_RELEASE))) ||
4203 ((FreeType & (MEM_DECOMMIT | MEM_RELEASE)) == (MEM_DECOMMIT | MEM_RELEASE)))
4204 {
4205 DPRINT1("Invalid FreeType combination\n");
4206 return STATUS_INVALID_PARAMETER_4;
4207 }
4208
4209 //
4210 // Enter SEH for probe and capture. On failure, return back to the caller
4211 // with an exception violation.
4212 //
4213 _SEH2_TRY
4214 {
4215 //
4216 // Check for user-mode parameters and make sure that they are writeable
4217 //
4218 if (PreviousMode != KernelMode)
4219 {
4220 ProbeForWritePointer(UBaseAddress);
4221 ProbeForWriteUlong(URegionSize);
4222 }
4223
4224 //
4225 // Capture the current values
4226 //
4227 PBaseAddress = *UBaseAddress;
4228 PRegionSize = *URegionSize;
4229 }
4230 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
4231 {
4232 _SEH2_YIELD(return _SEH2_GetExceptionCode());
4233 }
4234 _SEH2_END;
4235
4236 //
4237 // Make sure the allocation isn't past the user area
4238 //
4239 if (PBaseAddress >= MM_HIGHEST_USER_ADDRESS)
4240 {
4241 DPRINT1("Virtual free base above User Space\n");
4242 return STATUS_INVALID_PARAMETER_2;
4243 }
4244
4245 //
4246 // Make sure the allocation wouldn't overflow past the user area
4247 //
4248 if (((ULONG_PTR)MM_HIGHEST_USER_ADDRESS - (ULONG_PTR)PBaseAddress) < PRegionSize)
4249 {
4250 DPRINT1("Region size would overflow into kernel-memory\n");
4251 return STATUS_INVALID_PARAMETER_3;
4252 }
4253
4254 //
4255 // If this is for the current process, just use PsGetCurrentProcess
4256 //
4257 if (ProcessHandle == NtCurrentProcess())
4258 {
4259 Process = CurrentProcess;
4260 }
4261 else
4262 {
4263 //
4264 // Otherwise, reference the process with VM rights and attach to it if
4265 // this isn't the current process. We must attach because we'll be touching
4266 // PTEs and PDEs that belong to user-mode memory, and also touching the
4267 // Working Set which is stored in Hyperspace.
4268 //
4269 Status = ObReferenceObjectByHandle(ProcessHandle,
4270 PROCESS_VM_OPERATION,
4271 PsProcessType,
4272 PreviousMode,
4273 (PVOID*)&Process,
4274 NULL);
4275 if (!NT_SUCCESS(Status)) return Status;
4276 if (CurrentProcess != Process)
4277 {
4278 KeStackAttachProcess(&Process->Pcb, &ApcState);
4279 Attached = TRUE;
4280 }
4281 }
4282
4283 //
4284 // Lock the address space
4285 //
4286 AddressSpace = MmGetCurrentAddressSpace();
4287 MmLockAddressSpace(AddressSpace);
4288
4289 //
4290 // If the address space is being deleted, fail the de-allocation since it's
4291 // too late to do anything about it
4292 //
4293 if (Process->VmDeleted)
4294 {
4295 DPRINT1("Process is dead\n");
4296 Status = STATUS_PROCESS_IS_TERMINATING;
4297 goto FailPath;
4298 }
4299
4300 //
4301 // Compute start and end addresses, and locate the VAD
4302 //
4303 StartingAddress = (ULONG_PTR)PAGE_ALIGN(PBaseAddress);
4304 EndingAddress = ((ULONG_PTR)PBaseAddress + PRegionSize - 1) | (PAGE_SIZE - 1);
4305 Vad = MiLocateAddress((PVOID)StartingAddress);
4306 if (!Vad)
4307 {
4308 DPRINT1("Unable to find VAD for address 0x%p\n", StartingAddress);
4309 Status = STATUS_MEMORY_NOT_ALLOCATED;
4310 goto FailPath;
4311 }
4312
4313 //
4314 // If the range exceeds the VAD's ending VPN, fail this request
4315 //
4316 if (Vad->EndingVpn < (EndingAddress >> PAGE_SHIFT))
4317 {
4318 DPRINT1("Address 0x%p is beyond the VAD\n", EndingAddress);
4319 Status = STATUS_UNABLE_TO_FREE_VM;
4320 goto FailPath;
4321 }
4322
4323 //
4324 // These ASSERTs are here because ReactOS ARM3 does not currently implement
4325 // any other kinds of VADs.
4326 //
4327 ASSERT(Vad->u.VadFlags.PrivateMemory == 1);
4328 ASSERT(Vad->u.VadFlags.NoChange == 0);
4329 ASSERT(Vad->u.VadFlags.VadType == VadNone);
4330
4331 //
4332 // Finally, make sure there is a ReactOS Mm MEMORY_AREA for this allocation
4333 // and that is is an ARM3 memory area, and not a section view, as we currently
4334 // don't support freeing those though this interface.
4335 //
4336 MemoryArea = MmLocateMemoryAreaByAddress(AddressSpace, (PVOID)StartingAddress);
4337 ASSERT(MemoryArea);
4338 ASSERT(MemoryArea->Type == MEMORY_AREA_OWNED_BY_ARM3);
4339
4340 //
4341 // Now we can try the operation. First check if this is a RELEASE or a DECOMMIT
4342 //
4343 if (FreeType & MEM_RELEASE)
4344 {
4345 //
4346 // Is the caller trying to remove the whole VAD, or remove only a portion
4347 // of it? If no region size is specified, then the assumption is that the
4348 // whole VAD is to be destroyed
4349 //
4350 if (!PRegionSize)
4351 {
4352 //
4353 // The caller must specify the base address identically to the range
4354 // that is stored in the VAD.
4355 //
4356 if (((ULONG_PTR)PBaseAddress >> PAGE_SHIFT) != Vad->StartingVpn)
4357 {
4358 DPRINT1("Address 0x%p does not match the VAD\n", PBaseAddress);
4359 Status = STATUS_FREE_VM_NOT_AT_BASE;
4360 goto FailPath;
4361 }
4362
4363 //
4364 // Now compute the actual start/end addresses based on the VAD
4365 //
4366 StartingAddress = Vad->StartingVpn << PAGE_SHIFT;
4367 EndingAddress = (Vad->EndingVpn << PAGE_SHIFT) | (PAGE_SIZE - 1);
4368
4369 //
4370 // Finally lock the working set and remove the VAD from the VAD tree
4371 //
4372 MiLockWorkingSet(CurrentThread, AddressSpace);
4373 ASSERT(Process->VadRoot.NumberGenericTableElements >= 1);
4374 MiRemoveNode((PMMADDRESS_NODE)Vad, &Process->VadRoot);
4375 }
4376 else
4377 {
4378 //
4379 // This means the caller wants to release a specific region within
4380 // the range. We have to find out which range this is -- the following
4381 // possibilities exist plus their union (CASE D):
4382 //
4383 // STARTING ADDRESS ENDING ADDRESS
4384 // [<========][========================================][=========>]
4385 // CASE A CASE B CASE C
4386 //
4387 //
4388 // First, check for case A or D
4389 //
4390 if ((StartingAddress >> PAGE_SHIFT) == Vad->StartingVpn)
4391 {
4392 //
4393 // Check for case D
4394 //
4395 if ((EndingAddress >> PAGE_SHIFT) == Vad->EndingVpn)
4396 {
4397 //
4398 // This is the easiest one to handle -- it is identical to
4399 // the code path above when the caller sets a zero region size
4400 // and the whole VAD is destroyed
4401 //
4402 MiLockWorkingSet(CurrentThread, AddressSpace);
4403 ASSERT(Process->VadRoot.NumberGenericTableElements >= 1);
4404 MiRemoveNode((PMMADDRESS_NODE)Vad, &Process->VadRoot);
4405 }
4406 else
4407 {
4408 //
4409 // This case is pretty easy too -- we compute a bunch of
4410 // pages to decommit, and then push the VAD's starting address
4411 // a bit further down, then decrement the commit charge
4412 //
4413 // NOT YET IMPLEMENTED IN ARM3.
4414 //
4415 DPRINT1("Case A not handled\n");
4416 Status = STATUS_FREE_VM_NOT_AT_BASE;
4417 goto FailPath;
4418
4419 //
4420 // After analyzing the VAD, set it to NULL so that we don't
4421 // free it in the exit path
4422 //
4423 Vad = NULL;
4424 }
4425 }
4426 else
4427 {
4428 //
4429 // This is case B or case C. First check for case C
4430 //
4431 if ((EndingAddress >> PAGE_SHIFT) == Vad->EndingVpn)
4432 {
4433 PMEMORY_AREA MemoryArea;
4434
4435 //
4436 // This is pretty easy and similar to case A. We compute the
4437 // amount of pages to decommit, update the VAD's commit charge
4438 // and then change the ending address of the VAD to be a bit
4439 // smaller.
4440 //
4441 MiLockWorkingSet(CurrentThread, AddressSpace);
4442 CommitReduction = MiCalculatePageCommitment(StartingAddress,
4443 EndingAddress,
4444 Vad,
4445 Process);
4446 Vad->u.VadFlags.CommitCharge -= CommitReduction;
4447 // For ReactOS: shrink the corresponding memory area
4448 MemoryArea = MmLocateMemoryAreaByAddress(AddressSpace, (PVOID)StartingAddress);
4449 ASSERT(Vad->StartingVpn << PAGE_SHIFT == (ULONG_PTR)MemoryArea->StartingAddress);
4450 ASSERT((Vad->EndingVpn + 1) << PAGE_SHIFT == (ULONG_PTR)MemoryArea->EndingAddress);
4451 Vad->EndingVpn = ((ULONG_PTR)StartingAddress - 1) >> PAGE_SHIFT;
4452 MemoryArea->EndingAddress = (PVOID)(((Vad->EndingVpn + 1) << PAGE_SHIFT) - 1);
4453 }
4454 else
4455 {
4456 //
4457 // This is case B and the hardest one. Because we are removing
4458 // a chunk of memory from the very middle of the VAD, we must
4459 // actually split the VAD into two new VADs and compute the
4460 // commit charges for each of them, and reinsert new charges.
4461 //
4462 // NOT YET IMPLEMENTED IN ARM3.
4463 //
4464 DPRINT1("Case B not handled\n");
4465 Status = STATUS_FREE_VM_NOT_AT_BASE;
4466 goto FailPath;
4467 }
4468
4469 //
4470 // After analyzing the VAD, set it to NULL so that we don't
4471 // free it in the exit path
4472 //
4473 Vad = NULL;
4474 }
4475 }
4476
4477 //
4478 // Now we have a range of pages to dereference, so call the right API
4479 // to do that and then release the working set, since we're done messing
4480 // around with process pages.
4481 //
4482 MiDeleteVirtualAddresses(StartingAddress, EndingAddress, NULL);
4483 MiUnlockWorkingSet(CurrentThread, AddressSpace);
4484 Status = STATUS_SUCCESS;
4485
4486 FinalPath:
4487 //
4488 // Update the process counters
4489 //
4490 PRegionSize = EndingAddress - StartingAddress + 1;
4491 Process->CommitCharge -= CommitReduction;
4492 if (FreeType & MEM_RELEASE) Process->VirtualSize -= PRegionSize;
4493
4494 //
4495 // Unlock the address space and free the VAD in failure cases. Next,
4496 // detach from the target process so we can write the region size and the
4497 // base address to the correct source process, and dereference the target
4498 // process.
4499 //
4500 MmUnlockAddressSpace(AddressSpace);
4501 if (Vad) ExFreePool(Vad);
4502 if (Attached) KeUnstackDetachProcess(&ApcState);
4503 if (ProcessHandle != NtCurrentProcess()) ObDereferenceObject(Process);
4504
4505 //
4506 // Use SEH to safely return the region size and the base address of the
4507 // deallocation. If we get an access violation, don't return a failure code
4508 // as the deallocation *has* happened. The caller will just have to figure
4509 // out another way to find out where it is (such as VirtualQuery).
4510 //
4511 _SEH2_TRY
4512 {
4513 *URegionSize = PRegionSize;
4514 *UBaseAddress = (PVOID)StartingAddress;
4515 }
4516 _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER)
4517 {
4518 }
4519 _SEH2_END;
4520 return Status;
4521 }
4522
4523 //
4524 // This is the decommit path. You cannot decommit from the following VADs in
4525 // Windows, so fail the vall
4526 //
4527 if ((Vad->u.VadFlags.VadType == VadAwe) ||
4528 (Vad->u.VadFlags.VadType == VadLargePages) ||
4529 (Vad->u.VadFlags.VadType == VadRotatePhysical))
4530 {
4531 DPRINT1("Trying to decommit from invalid VAD\n");
4532 Status = STATUS_MEMORY_NOT_ALLOCATED;
4533 goto FailPath;
4534 }
4535
4536 //
4537 // If the caller did not specify a region size, first make sure that this
4538 // region is actually committed. If it is, then compute the ending address
4539 // based on the VAD.
4540 //
4541 if (!PRegionSize)
4542 {
4543 if (((ULONG_PTR)PBaseAddress >> PAGE_SHIFT) != Vad->StartingVpn)
4544 {
4545 DPRINT1("Decomitting non-committed memory\n");
4546 Status = STATUS_FREE_VM_NOT_AT_BASE;
4547 goto FailPath;
4548 }
4549 EndingAddress = (Vad->EndingVpn << PAGE_SHIFT) | (PAGE_SIZE - 1);
4550 }
4551
4552 //
4553 // Decommit the PTEs for the range plus the actual backing pages for the
4554 // range, then reduce that amount from the commit charge in the VAD
4555 //
4556 CommitReduction = MiAddressToPte(EndingAddress) -
4557 MiAddressToPte(StartingAddress) +
4558 1 -
4559 MiDecommitPages((PVOID)StartingAddress,
4560 MiAddressToPte(EndingAddress),
4561 Process,
4562 Vad);
4563 ASSERT(CommitReduction >= 0);
4564 Vad->u.VadFlags.CommitCharge -= CommitReduction;
4565 ASSERT(Vad->u.VadFlags.CommitCharge >= 0);
4566
4567 //
4568 // We are done, go to the exit path without freeing the VAD as it remains
4569 // valid since we have not released the allocation.
4570 //
4571 Vad = NULL;
4572 Status = STATUS_SUCCESS;
4573 goto FinalPath;
4574
4575 //
4576 // In the failure path, we detach and derefernece the target process, and
4577 // return whatever failure code was sent.
4578 //
4579 FailPath:
4580 MmUnlockAddressSpace(AddressSpace);
4581 if (Attached) KeUnstackDetachProcess(&ApcState);
4582 if (ProcessHandle != NtCurrentProcess()) ObDereferenceObject(Process);
4583 return Status;
4584 }
4585
4586 /* EOF */