- Set the correct type and state in MiQueryVirtualMemory.
[reactos.git] / reactos / ntoskrnl / mm / virtual.c
index 45df45d..b2d9f85 100644 (file)
-/* $Id: virtual.c,v 1.32 2000/07/07 10:30:56 dwelch Exp $
+/* $Id$
  *
- * COPYRIGHT:   See COPYING in the top directory
- * PROJECT:     ReactOS kernel
- * FILE:        ntoskrnl/mm/virtual.c
- * PURPOSE:     implementing the Virtualxxx section of the win32 api
- * PROGRAMMER:  David Welch
- * UPDATE HISTORY:
- *              09/4/98: Created
- *              10/6/98: Corrections from Fatahi (i_fatahi@hotmail.com)
- *              30/9/98: Implemented ZwxxxVirtualMemory functions
+ * COPYRIGHT:       See COPYING in the top level directory
+ * PROJECT:         ReactOS kernel
+ * FILE:            ntoskrnl/mm/virtual.c
+ * PURPOSE:         Implementing operations on virtual memory.
+ *
+ * PROGRAMMERS:     David Welch
  */
+
 /* INCLUDE *****************************************************************/
 
-#include <ddk/ntddk.h>
-#include <internal/mm.h>
-#include <internal/mmhal.h>
-#include <internal/ob.h>
-#include <internal/io.h>
-#include <internal/ps.h>
-#include <string.h>
-#include <internal/string.h>
+#include <ntoskrnl.h>
 
 #define NDEBUG
 #include <internal/debug.h>
 
-/* FUNCTIONS ****************************************************************/
+/* FUNCTIONS *****************************************************************/
 
-NTSTATUS MmWritePageVirtualMemory(PMADDRESS_SPACE AddressSpace,
-                                 PMEMORY_AREA MArea,
-                                 PVOID Address)
+NTSTATUS STDCALL
+NtFlushVirtualMemory(IN HANDLE ProcessHandle,
+                     IN PVOID BaseAddress,
+                     IN ULONG NumberOfBytesToFlush,
+                     OUT PULONG NumberOfBytesFlushed OPTIONAL)
+/*
+ * FUNCTION: Flushes virtual memory to file
+ * ARGUMENTS:
+ *        ProcessHandle = Points to the process that allocated the virtual
+ *                        memory
+ *        BaseAddress = Points to the memory address
+ *        NumberOfBytesToFlush = Limits the range to flush,
+ *        NumberOfBytesFlushed = Actual number of bytes flushed
+ * RETURNS: Status
+ */
 {
-   SWAPENTRY se;
-   ULONG Flags;
-   PHYSICAL_ADDRESS PhysicalAddress;
-   PMDL Mdl;
-   NTSTATUS Status;
-   
-   /*
-    * FIXME: What should we do if an i/o operation is pending on
-    * this page
-    */
-   
-   /*
-    * If the memory area is readonly then there is nothing to do
-    */
-   if (MArea->Attributes & PAGE_READONLY ||
-       MArea->Attributes & PAGE_EXECUTE_READ)
-     {
-       return(STATUS_SUCCESS);
-     }
-   /*
-    * Set the page to readonly. This ensures the current contents aren't
-    * modified while we are writing it to swap.
-    */
-   MmSetPageProtect(AddressSpace->Process,
-                   Address,
-                   PAGE_READONLY);
-   /*
-    * If the page isn't dirty then there is nothing to do.
-    */
-   if (!MmIsPageDirty(AddressSpace->Process, Address))
-     {
-       MmSetPageProtect(AddressSpace->Process,
-                        Address,
-                        MArea->Attributes);
-       return(STATUS_SUCCESS); 
-     }
-   PhysicalAddress = MmGetPhysicalAddress(Address);
-   /*
-    * If we haven't already allocated a swap entry for this page
-    * then allocate one
-    */
-   if ((se = MmGetSavedSwapEntryPage((PVOID)PhysicalAddress.u.LowPart)) != 0)
-     {
-       se = MmAllocSwapPage();
-       if (se == 0)
-         {
-            MmSetPageProtect(AddressSpace->Process,
-                             Address,
-                             MArea->Attributes);
-            return(STATUS_UNSUCCESSFUL);
-         }
-       MmSetSavedSwapEntryPage((PVOID)PhysicalAddress.u.LowPart, se);
-     }
-   /*
-    * Set the flags so other threads will know what we are doing
-    */
-   Flags = MmGetFlagsPage((PVOID)PhysicalAddress.u.LowPart);
-   Flags = Flags | MM_PHYSICAL_PAGE_MPW_PENDING;
-   MmSetFlagsPage((PVOID)PhysicalAddress.u.LowPart, Flags);
-   /*
-    * Build an mdl to hold the page for writeout
-    */
-   Mdl = MmCreateMdl(NULL, NULL, PAGESIZE);
-   MmBuildMdlFromPages(Mdl, (PULONG)&PhysicalAddress.u.LowPart);
-   /*
-    * Unlock the address space and write out the page to swap.
-    */
-   MmUnlockAddressSpace(AddressSpace);
-   Status = MmWriteToSwapPage(se, Mdl);
-   /*
-    * Cleanup 
-    */
-   MmLockAddressSpace(AddressSpace);
-   Flags = MmGetFlagsPage((PVOID)PhysicalAddress.u.LowPart);
-   Flags = Flags & (~MM_PHYSICAL_PAGE_MPW_PENDING);
-   MmSetFlagsPage((PVOID)PhysicalAddress.u.LowPart,Flags);
-   /*
-    * If we successfully wrote the page then reset the dirty bit
-    */
-   if (NT_SUCCESS(Status))
-     {
-       MmSetCleanPage(AddressSpace->Process, Address);
-     }
-   return(Status);
+  /* This should be implemented once we support network filesystems */
+  DPRINT("NtFlushVirtualMemory is UNIMPLEMENTED\n");
+  return(STATUS_SUCCESS);
 }
 
 
-ULONG MmPageOutVirtualMemory(PMADDRESS_SPACE AddressSpace,
-                            PMEMORY_AREA MemoryArea,
-                            PVOID Address,
-                            PBOOLEAN Ul)
+NTSTATUS STDCALL
+MiLockVirtualMemory(HANDLE ProcessHandle,
+  PVOID BaseAddress,
+  ULONG NumberOfBytesToLock,
+  PULONG NumberOfBytesLocked,
+  PObReferenceObjectByHandle pObReferenceObjectByHandle,
+  PMmCreateMdl pMmCreateMdl,
+  PObDereferenceObject pObDereferenceObject,
+  PMmProbeAndLockPages pMmProbeAndLockPages,
+  PExFreePool pExFreePool)
 {
-   PHYSICAL_ADDRESS PhysicalAddress;
-   
-   if ((MemoryArea->Attributes & PAGE_READONLY) ||
-       (MemoryArea->Attributes & PAGE_EXECUTE_READ) ||
-       !MmIsPageDirty(PsGetCurrentProcess(), Address))
-     {
-       PhysicalAddress = MmGetPhysicalAddress(Address);
-       
-       MmRemovePageFromWorkingSet(AddressSpace->Process,
-                                  Address);
-       MmSetPage(PsGetCurrentProcess(),
-                 Address,
-                 0,
-                 0);
-       MmDereferencePage((PVOID)PhysicalAddress.u.LowPart);
-       *Ul = TRUE;
-       return(1);
-     }
-   *Ul = FALSE;
-   return(0);     
+  PEPROCESS Process;
+  NTSTATUS Status;
+  PMDL Mdl;
+
+  Status = pObReferenceObjectByHandle(ProcessHandle,
+    PROCESS_VM_WRITE,
+    NULL,
+    UserMode,
+    (PVOID*)(&Process),
+    NULL);
+  if (!NT_SUCCESS(Status))
+    return(Status);
+
+  Mdl = pMmCreateMdl(NULL,
+    BaseAddress,
+    NumberOfBytesToLock);
+  if (Mdl == NULL)
+    {
+      pObDereferenceObject(Process);
+      return(STATUS_NO_MEMORY);
+    }
+
+  pMmProbeAndLockPages(Mdl,
+    UserMode,
+    IoWriteAccess);
+
+  pExFreePool(Mdl);
+
+  pObDereferenceObject(Process);
+
+  *NumberOfBytesLocked = NumberOfBytesToLock;
+  return(STATUS_SUCCESS);
 }
 
-NTSTATUS MmNotPresentFaultVirtualMemory(PMADDRESS_SPACE AddressSpace,
-                                       MEMORY_AREA* MemoryArea, 
-                                       PVOID Address)
-/*
- * FUNCTION: Move data into memory to satisfy a page not present fault
- * ARGUMENTS:
- *      AddressSpace = Address space within which the fault occurred
- *      MemoryArea = The memory area within which the fault occurred
- *      Address = The absolute address of fault
- * RETURNS: Status
- * NOTES: This function is called with the address space lock held.
- */
+
+NTSTATUS STDCALL
+NtLockVirtualMemory(HANDLE ProcessHandle,
+  PVOID BaseAddress,
+  ULONG NumberOfBytesToLock,
+  PULONG NumberOfBytesLocked)
 {
-   PVOID Page;
-   NTSTATUS Status;
-   
-   if (MmIsPagePresent(NULL, Address))
-     { 
-       return(STATUS_SUCCESS);
-     }
-   
-   Page = MmAllocPage(0);
-   while (Page == NULL)
-     {
-       MmUnlockAddressSpace(AddressSpace);
-       MmWaitForFreePages();
-       MmLockAddressSpace(AddressSpace);
-       if (MmIsPagePresent(NULL, Address))
-         {
-            return(STATUS_SUCCESS);
-         }
-       Page = MmAllocPage(0);
-     }
-   Status = MmCreatePageTable(Address);
-   while (!NT_SUCCESS(Status))
-     {
-       MmUnlockAddressSpace(AddressSpace);
-       MmWaitForFreePages();
-       MmLockAddressSpace(AddressSpace);
-       if (MmIsPagePresent(NULL, Address))
-         {
-            MmDereferencePage(Page);
-            return(STATUS_SUCCESS);
-         }
-       Status = MmCreatePageTable(Address);     
-     }
-   MmAddPageToWorkingSet(PsGetCurrentProcess(), Address);
-   MmSetPage(PsGetCurrentProcess(),
-            Address,
-            MemoryArea->Attributes,
-            (ULONG)Page);
-   
-   return(STATUS_SUCCESS);
+  DPRINT("NtLockVirtualMemory(ProcessHandle %x, BaseAddress %x, "
+    "NumberOfBytesToLock %d, NumberOfBytesLocked %x)\n",
+    ProcessHandle,
+    BaseAddress,
+    NumberOfBytesToLock,
+    NumberOfBytesLocked);
+
+  return MiLockVirtualMemory(ProcessHandle,
+    BaseAddress,
+    NumberOfBytesToLock,
+    NumberOfBytesLocked,
+    ObReferenceObjectByHandle,
+    MmCreateMdl,
+    ObfDereferenceObject,
+    MmProbeAndLockPages,
+    ExFreePool);
 }
 
-NTSTATUS STDCALL NtAllocateVirtualMemory(IN    HANDLE  ProcessHandle,
-                                        IN OUT PVOID   * BaseAddress,
-                                        IN     ULONG   ZeroBits,
-                                        IN OUT PULONG  RegionSize,
-                                        IN     ULONG   AllocationType, 
-                                        IN     ULONG   Protect)
-/*
- * FUNCTION: Allocates a block of virtual memory in the process address space
- * ARGUMENTS:
- *      ProcessHandle = The handle of the process which owns the virtual memory
- *      BaseAddress   = A pointer to the virtual memory allocated. If you 
- *                      supply a non zero value the system will try to 
- *                      allocate the memory at the address supplied. It round 
- *                      it down to a multiple  of the page size.
- *      ZeroBits  = (OPTIONAL) You can specify the number of high order bits 
- *                      that must be zero, ensuring that the memory will be 
- *                      allocated at a address below a certain value.
- *      RegionSize = The number of bytes to allocate
- *      AllocationType = Indicates the type of virtual memory you like to 
- *                       allocated, can be one of the values : MEM_COMMIT, 
- *                       MEM_RESERVE, MEM_RESET, MEM_TOP_DOWN
- *      Protect = Indicates the protection type of the pages allocated, can be
- *                a combination of PAGE_READONLY, PAGE_READWRITE, 
- *                PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_GUARD, 
- *                PAGE_NOACCESS
- * REMARKS:
- *       This function maps to the win32 VirtualAllocEx. Virtual memory is 
- *       process based so the  protocol starts with a ProcessHandle. I 
- *       splitted the functionality of obtaining the actual address and 
- *       specifying the start address in two parameters ( BaseAddress and 
- *       StartAddress ) The NumberOfBytesAllocated specify the range and the 
- *       AllocationType and ProctectionType map to the other two parameters.
- * RETURNS: Status
- */
+
+NTSTATUS FASTCALL
+MiQueryVirtualMemory (IN HANDLE ProcessHandle,
+                      IN PVOID Address,
+                      IN CINT VirtualMemoryInformationClass,
+                      OUT PVOID VirtualMemoryInformation,
+                      IN ULONG Length,
+                      OUT PULONG ResultLength)
 {
+   NTSTATUS Status;
    PEPROCESS Process;
    MEMORY_AREA* MemoryArea;
-   ULONG Type;
-   NTSTATUS Status;
    PMADDRESS_SPACE AddressSpace;
-   
-   DPRINT("NtAllocateVirtualMemory(ProcessHandle %x, *BaseAddress %x, "
-         "ZeroBits %d, *RegionSize %x, AllocationType %x, Protect %x)\n",
-         ProcessHandle,*BaseAddress,ZeroBits,*RegionSize,AllocationType,
-         Protect);
-   
-   Status = ObReferenceObjectByHandle(ProcessHandle,
-                                     PROCESS_VM_OPERATION,
-                                     NULL,
-                                     UserMode,
-                                     (PVOID*)(&Process),
-                                     NULL);
-   if (Status != STATUS_SUCCESS)
-     {
-       DPRINT("NtAllocateVirtualMemory() = %x\n",Status);
-       return(Status);
-     }
-   
-   if (AllocationType & MEM_RESERVE)
-     {
-       Type = MEMORY_AREA_RESERVE;
-     }
+
+   if (Address < MmSystemRangeStart)
+   {
+      Status = ObReferenceObjectByHandle(ProcessHandle,
+                                         PROCESS_QUERY_INFORMATION,
+                                         NULL,
+                                         UserMode,
+                                         (PVOID*)(&Process),
+                                         NULL);
+
+      if (!NT_SUCCESS(Status))
+      {
+         DPRINT("NtQueryVirtualMemory() = %x\n",Status);
+         return(Status);
+      }
+      AddressSpace = &Process->AddressSpace;
+   }
    else
-     {
-       Type = MEMORY_AREA_COMMIT;
-     }
-   
-   AddressSpace = &Process->AddressSpace;
+   {
+      AddressSpace = MmGetKernelAddressSpace();
+   }
    MmLockAddressSpace(AddressSpace);
-   
-   if ((*BaseAddress) != 0)
-     {
-       MemoryArea = MmOpenMemoryAreaByAddress(&Process->AddressSpace,
-                                              *BaseAddress);
-       
-       if (MemoryArea != NULL)
-         {
-            if (MemoryArea->BaseAddress == (*BaseAddress) &&
-                MemoryArea->Length == *RegionSize)
+   MemoryArea = MmLocateMemoryAreaByAddress(AddressSpace, Address);
+   switch(VirtualMemoryInformationClass)
+   {
+      case MemoryBasicInformation:
+         {
+           PMEMORY_BASIC_INFORMATION Info =
+               (PMEMORY_BASIC_INFORMATION)VirtualMemoryInformation;
+            if (Length != sizeof(MEMORY_BASIC_INFORMATION))
+            {
+               MmUnlockAddressSpace(AddressSpace);
+               ObDereferenceObject(Process);
+               return(STATUS_INFO_LENGTH_MISMATCH);
+            }
+
+            if (MemoryArea == NULL)
+            {
+              Info->Type = 0;
+               Info->State = MEM_FREE;
+              Info->Protect = PAGE_NOACCESS;
+              Info->AllocationProtect = 0;
+               Info->BaseAddress = (PVOID)PAGE_ROUND_DOWN(Address);
+              Info->AllocationBase = NULL;
+              Info->RegionSize = MmFindGapAtAddress(AddressSpace, Info->BaseAddress);
+               Status = STATUS_SUCCESS;
+               *ResultLength = sizeof(MEMORY_BASIC_INFORMATION);
+           }
+            else
+           {
+              switch(MemoryArea->Type)
               {
-                 MemoryArea->Type = Type;
-                 MemoryArea->Attributes = Protect;
-                 DPRINT("*BaseAddress %x\n",*BaseAddress);
-                 MmUnlockAddressSpace(AddressSpace);
-                 ObDereferenceObject(Process);
-                 return(STATUS_SUCCESS);
+                 case MEMORY_AREA_VIRTUAL_MEMORY:
+                  case MEMORY_AREA_PEB_OR_TEB:
+                     Status = MmQueryAnonMem(MemoryArea, Address, Info,
+                                             ResultLength);
+                    break;
+                 case MEMORY_AREA_SECTION_VIEW:
+                     Status = MmQuerySectionView(MemoryArea, Address, Info,
+                                                 ResultLength);
+                     break;
+                 case MEMORY_AREA_NO_ACCESS:
+                    Info->Type = MEM_PRIVATE;
+                     Info->State = MEM_RESERVE;
+                    Info->Protect = MemoryArea->Attributes;
+                    Info->AllocationProtect = MemoryArea->Attributes;
+                    Info->BaseAddress = MemoryArea->StartingAddress;
+                    Info->AllocationBase = MemoryArea->StartingAddress;
+                    Info->RegionSize = (ULONG_PTR)MemoryArea->EndingAddress -
+                                       (ULONG_PTR)MemoryArea->StartingAddress;
+                     Status = STATUS_SUCCESS;
+                     *ResultLength = sizeof(MEMORY_BASIC_INFORMATION);
+                    break;
+                 case MEMORY_AREA_SHARED_DATA:
+                    Info->Type = MEM_PRIVATE;
+                     Info->State = MEM_COMMIT;
+                    Info->Protect = MemoryArea->Attributes;
+                    Info->AllocationProtect = MemoryArea->Attributes;
+                    Info->BaseAddress = MemoryArea->StartingAddress;
+                    Info->AllocationBase = MemoryArea->StartingAddress;
+                    Info->RegionSize = (ULONG_PTR)MemoryArea->EndingAddress -
+                                       (ULONG_PTR)MemoryArea->StartingAddress;
+                     Status = STATUS_SUCCESS;
+                     *ResultLength = sizeof(MEMORY_BASIC_INFORMATION);
+                    break;
+                 case MEMORY_AREA_SYSTEM:
+                    Info->Type = 0;
+                     Info->State = MEM_COMMIT;
+                    Info->Protect = MemoryArea->Attributes;
+                    Info->AllocationProtect = MemoryArea->Attributes;
+                    Info->BaseAddress = MemoryArea->StartingAddress;
+                    Info->AllocationBase = MemoryArea->StartingAddress;
+                    Info->RegionSize = (ULONG_PTR)MemoryArea->EndingAddress -
+                                       (ULONG_PTR)MemoryArea->StartingAddress;
+                     Status = STATUS_SUCCESS;
+                     *ResultLength = sizeof(MEMORY_BASIC_INFORMATION);
+                    break;
+                 case MEMORY_AREA_KERNEL_STACK:
+                    Info->Type = 0;
+                     Info->State = MEM_COMMIT;
+                    Info->Protect = MemoryArea->Attributes;
+                    Info->AllocationProtect = MemoryArea->Attributes;
+                    Info->BaseAddress = MemoryArea->StartingAddress;
+                    Info->AllocationBase = MemoryArea->StartingAddress;
+                    Info->RegionSize = (ULONG_PTR)MemoryArea->EndingAddress -
+                                       (ULONG_PTR)MemoryArea->StartingAddress;
+                     Status = STATUS_SUCCESS;
+                     *ResultLength = sizeof(MEMORY_BASIC_INFORMATION);
+                    break;
+                  case MEMORY_AREA_PAGED_POOL:
+                    Info->Type = 0;
+                     Info->State = MEM_COMMIT;
+                    Info->Protect = MemoryArea->Attributes;
+                    Info->AllocationProtect = MemoryArea->Attributes;
+                    Info->BaseAddress = MemoryArea->StartingAddress;
+                    Info->AllocationBase = MemoryArea->StartingAddress;
+                    Info->RegionSize = (ULONG_PTR)MemoryArea->EndingAddress -
+                                       (ULONG_PTR)MemoryArea->StartingAddress;
+                     Status = STATUS_SUCCESS;
+                     *ResultLength = sizeof(MEMORY_BASIC_INFORMATION);
+                    break;
+                 default:
+                    DPRINT1("unhandled memory area type: 0x%x\n", MemoryArea->Type);
+                    Status = STATUS_UNSUCCESSFUL;
+                     *ResultLength = 0;
               }
-            
-            MemoryArea = MmSplitMemoryArea(Process,
-                                           &Process->AddressSpace,
-                                           MemoryArea,
-                                           *BaseAddress,
-                                           *RegionSize,
-                                           Type,
-                                           Protect);
-            DPRINT("*BaseAddress %x\n",*BaseAddress);
-            /* FIXME: Reserve/dereserve swap pages */
-            MmUnlockAddressSpace(AddressSpace);
-            ObDereferenceObject(Process);
-            return(STATUS_SUCCESS);
-         }
-     }
-   
-   Status = MmCreateMemoryArea(Process,
-                              &Process->AddressSpace,
-                              Type,
-                              BaseAddress,
-                              *RegionSize,
-                              Protect,
-                              &MemoryArea);
-   
-   if (Status != STATUS_SUCCESS)
-     {
-       DPRINT("NtAllocateVirtualMemory() = %x\n",Status);
-       MmUnlockAddressSpace(AddressSpace);     
-       ObDereferenceObject(Process);
-       return(Status);
-     }
+           }
+            break;
+         }
+
+      default:
+         {
+            Status = STATUS_INVALID_INFO_CLASS;
+            *ResultLength = 0;
+            break;
+         }
+   }
+
+   MmUnlockAddressSpace(AddressSpace);
+   if (Address < MmSystemRangeStart)
+   {
+      ObDereferenceObject(Process);
+   }
+
+   return Status;
+}
+
+/* (tMk 2004.II.4)
+ * FUNCTION:
+ * Called from VirtualQueryEx (lib\kernel32\mem\virtual.c)
+ *
+ */
+NTSTATUS STDCALL
+NtQueryVirtualMemory (IN HANDLE ProcessHandle,
+                      IN PVOID Address,
+                      IN MEMORY_INFORMATION_CLASS VirtualMemoryInformationClass,
+                      OUT PVOID VirtualMemoryInformation,
+                      IN ULONG Length,
+                      OUT PULONG UnsafeResultLength)
+{
+   NTSTATUS Status = STATUS_SUCCESS;
+   ULONG ResultLength = 0;
+   KPROCESSOR_MODE PreviousMode;
+   union
+   {
+      MEMORY_BASIC_INFORMATION BasicInfo;
+   }
+   VirtualMemoryInfo;
+
+   DPRINT("NtQueryVirtualMemory(ProcessHandle %x, Address %x, "
+          "VirtualMemoryInformationClass %d, VirtualMemoryInformation %x, "
+          "Length %lu ResultLength %x)\n",ProcessHandle,Address,
+          VirtualMemoryInformationClass,VirtualMemoryInformation,
+          Length,ResultLength);
+
+   PreviousMode =  ExGetPreviousMode();
    
-   DPRINT("*BaseAddress %x\n",*BaseAddress);
-   if ((AllocationType & MEM_COMMIT) &&
-       ((Protect & PAGE_READWRITE) ||
-       (Protect & PAGE_EXECUTE_READWRITE)))
+   if (PreviousMode != KernelMode && UnsafeResultLength != NULL)
      {
-       MmReserveSwapPages(PAGE_ROUND_UP((*RegionSize)));
+       _SEH_TRY
+         {
+           ProbeForWriteUlong(UnsafeResultLength);
+         }
+       _SEH_HANDLE
+         {
+           Status = _SEH_GetExceptionCode();
+         }
+       _SEH_END;
+       
+       if (!NT_SUCCESS(Status))
+         {
+           return Status;
+         }
      }
-   MmUnlockAddressSpace(AddressSpace);
-   ObDereferenceObject(Process);
-   return(STATUS_SUCCESS);
+
+   if (Address >= MmSystemRangeStart)
+   {
+      DPRINT1("Invalid parameter\n");
+      return STATUS_INVALID_PARAMETER;
+   }
+
+   Status = MiQueryVirtualMemory ( ProcessHandle,
+       Address,
+       VirtualMemoryInformationClass,
+       &VirtualMemoryInfo,
+       Length,
+       &ResultLength );
+
+   if (NT_SUCCESS(Status))
+   {
+      if (PreviousMode != KernelMode)
+        {
+          _SEH_TRY
+            {
+              if (ResultLength > 0)
+                {
+                  ProbeForWrite(VirtualMemoryInformation,
+                                ResultLength,
+                                1);
+                  RtlCopyMemory(VirtualMemoryInformation,
+                                &VirtualMemoryInfo,
+                                ResultLength);
+                }
+              if (UnsafeResultLength != NULL)
+                {
+                  *UnsafeResultLength = ResultLength;
+                }
+            }
+          _SEH_HANDLE
+            {
+              Status = _SEH_GetExceptionCode();
+            }
+          _SEH_END;
+        }
+      else
+        {
+          if (ResultLength > 0)
+            {
+              RtlCopyMemory(VirtualMemoryInformation,
+                            &VirtualMemoryInfo,
+                            ResultLength);
+            }
+
+          if (UnsafeResultLength != NULL)
+            {
+              *UnsafeResultLength = ResultLength;
+            }
+        }
+   }
+
+   return(Status);
 }
 
 
-NTSTATUS STDCALL NtFlushVirtualMemory(IN       HANDLE  ProcessHandle,
-                                     IN        PVOID   BaseAddress,
-                                     IN        ULONG   NumberOfBytesToFlush,
-                                     OUT PULONG NumberOfBytesFlushed OPTIONAL)
-/*
- * FUNCTION: Flushes virtual memory to file
- * ARGUMENTS:
- *        ProcessHandle = Points to the process that allocated the virtual 
- *                        memory
- *        BaseAddress = Points to the memory address
- *        NumberOfBytesToFlush = Limits the range to flush,
- *        NumberOfBytesFlushed = Actual number of bytes flushed
- * RETURNS: Status 
- */
+NTSTATUS STDCALL
+MiProtectVirtualMemory(IN PEPROCESS Process,
+                       IN OUT PVOID *BaseAddress,
+                       IN OUT PULONG NumberOfBytesToProtect,
+                       IN ULONG NewAccessProtection,
+                       OUT PULONG OldAccessProtection  OPTIONAL)
 {
-       UNIMPLEMENTED;
+   PMEMORY_AREA MemoryArea;
+   PMADDRESS_SPACE AddressSpace;
+   ULONG OldAccessProtection_;
+   NTSTATUS Status;
+
+   *NumberOfBytesToProtect =
+      PAGE_ROUND_UP((*BaseAddress) + (*NumberOfBytesToProtect)) -
+      PAGE_ROUND_DOWN(*BaseAddress);
+   *BaseAddress = (PVOID)PAGE_ROUND_DOWN(*BaseAddress);
+
+   AddressSpace = &Process->AddressSpace;
+
+   MmLockAddressSpace(AddressSpace);
+   MemoryArea = MmLocateMemoryAreaByAddress(AddressSpace, *BaseAddress);
+   if (MemoryArea == NULL)
+   {
+      MmUnlockAddressSpace(AddressSpace);
+      return STATUS_UNSUCCESSFUL;
+   }
+
+   if (OldAccessProtection == NULL)
+      OldAccessProtection = &OldAccessProtection_;
+
+   if (MemoryArea->Type == MEMORY_AREA_VIRTUAL_MEMORY)
+   {
+      Status = MmProtectAnonMem(AddressSpace, MemoryArea, *BaseAddress,
+                                *NumberOfBytesToProtect, NewAccessProtection,
+                                OldAccessProtection);
+   }
+   else if (MemoryArea->Type == MEMORY_AREA_SECTION_VIEW)
+   {
+      Status = MmProtectSectionView(AddressSpace, MemoryArea, *BaseAddress,
+                                    *NumberOfBytesToProtect,
+                                    NewAccessProtection,
+                                    OldAccessProtection);
+   }
+   else
+   {
+      /* FIXME: Should we return failure or success in this case? */
+      Status = STATUS_CONFLICTING_ADDRESSES;
+   }
+
+   MmUnlockAddressSpace(AddressSpace);
+
+   return Status;
 }
 
 
-NTSTATUS STDCALL NtFreeVirtualMemory(IN        HANDLE  ProcessHandle,
-                                    IN PVOID   * BaseAddress,  
-                                    IN PULONG  RegionSize,     
-                                    IN ULONG   FreeType)
-/*
- * FUNCTION: Frees a range of virtual memory
- * ARGUMENTS:
- *        ProcessHandle = Points to the process that allocated the virtual 
- *                        memory
- *        BaseAddress = Points to the memory address, rounded down to a 
- *                      multiple of the pagesize
- *        RegionSize = Limits the range to free, rounded up to a multiple of 
- *                     the paging size
- *        FreeType = Can be one of the values:  MEM_DECOMMIT, or MEM_RELEASE
- * RETURNS: Status 
+/* (tMk 2004.II.5)
+ * FUNCTION:
+ * Called from VirtualProtectEx (lib\kernel32\mem\virtual.c)
+ *
  */
+NTSTATUS STDCALL
+NtProtectVirtualMemory(IN HANDLE ProcessHandle,
+                       IN OUT PVOID *UnsafeBaseAddress,
+                       IN OUT ULONG *UnsafeNumberOfBytesToProtect,
+                       IN ULONG NewAccessProtection,
+                       OUT PULONG UnsafeOldAccessProtection)
 {
-   MEMORY_AREA* MemoryArea;
-   NTSTATUS Status;
    PEPROCESS Process;
-   PMADDRESS_SPACE AddressSpace;
-   ULONG i;
+   ULONG OldAccessProtection;
+   PVOID BaseAddress = NULL;
+   ULONG NumberOfBytesToProtect = 0;
+   KPROCESSOR_MODE PreviousMode;
+   NTSTATUS Status = STATUS_SUCCESS;
    
-   DPRINT("NtFreeVirtualMemory(ProcessHandle %x, *BaseAddress %x, "
-         "*RegionSize %x, FreeType %x)\n",ProcessHandle,*BaseAddress,
-         *RegionSize,FreeType);
-                                
+   PreviousMode = ExGetPreviousMode();
    
-   Status = ObReferenceObjectByHandle(ProcessHandle,
-                                     PROCESS_VM_OPERATION,
-                                     PsProcessType,
-                                     UserMode,
-                                     (PVOID*)(&Process),
-                                     NULL);
-   if (Status != STATUS_SUCCESS)
+   if (PreviousMode != KernelMode)
      {
-       return(Status);
+       _SEH_TRY
+         {
+           ProbeForWritePointer(UnsafeBaseAddress);
+           ProbeForWriteUlong(UnsafeNumberOfBytesToProtect);
+           ProbeForWriteUlong(UnsafeOldAccessProtection);
+
+           BaseAddress = *UnsafeBaseAddress;
+           NumberOfBytesToProtect = *UnsafeNumberOfBytesToProtect;
+         }
+       _SEH_HANDLE
+         {
+           Status = _SEH_GetExceptionCode();
+         }
+       _SEH_END;
+       
+       if (!NT_SUCCESS(Status))
+         {
+           return Status;
+         }
      }
-   
-   AddressSpace = &Process->AddressSpace;
-   
-   MmLockAddressSpace(AddressSpace);
-   MemoryArea = MmOpenMemoryAreaByAddress(AddressSpace,
-                                         *BaseAddress);
-   if (MemoryArea == NULL)
+   else
      {
-       MmUnlockAddressSpace(AddressSpace);
-       ObDereferenceObject(Process);
-       return(STATUS_UNSUCCESSFUL);
+       BaseAddress = *UnsafeBaseAddress;
+       NumberOfBytesToProtect = *UnsafeNumberOfBytesToProtect;
      }
-   
-   switch (FreeType)
+
+   if ((ULONG_PTR)BaseAddress + NumberOfBytesToProtect - 1 < (ULONG_PTR)BaseAddress ||
+       (ULONG_PTR)BaseAddress + NumberOfBytesToProtect - 1 >= MmUserProbeAddress)
      {
-      case MEM_RELEASE:
-       if (MemoryArea->BaseAddress != (*BaseAddress))
-         {
-            MmUnlockAddressSpace(AddressSpace);
-            ObDereferenceObject(Process);
-            return(STATUS_UNSUCCESSFUL);
-         }
-       if ((MemoryArea->Type == MEMORY_AREA_COMMIT) &&
-           ((MemoryArea->Attributes & PAGE_READWRITE) ||
-            (MemoryArea->Attributes & PAGE_EXECUTE_READWRITE)))
-         {
-            MmDereserveSwapPages(PAGE_ROUND_UP(MemoryArea->Length));
-         }
-       
-       for (i=0; i<=(MemoryArea->Length/PAGESIZE); i++)
-         {
-            LARGE_INTEGER PhysicalAddr;
-            
-            PhysicalAddr = MmGetPhysicalAddress(MemoryArea->BaseAddress + 
-                                                (i*PAGESIZE));
-            if (PhysicalAddr.u.LowPart != 0)
-              {
-                 MmRemovePageFromWorkingSet(AddressSpace->Process,
-                                            MemoryArea->BaseAddress +
-                                            (i*PAGESIZE));
-                 MmDereferencePage((PVOID)(ULONG)(PhysicalAddr.u.LowPart));
-              }
-         }
-       
-       MmFreeMemoryArea(&Process->AddressSpace,
-                        BaseAddress,
-                        0,
-                        FALSE);
-       MmUnlockAddressSpace(AddressSpace);
-       ObDereferenceObject(Process);
-       return(STATUS_SUCCESS);
-       
-      case MEM_DECOMMIT:       
-       if ((MemoryArea->Type == MEMORY_AREA_COMMIT) &&
-           ((MemoryArea->Attributes & PAGE_READWRITE) ||
-            (MemoryArea->Attributes & PAGE_EXECUTE_READWRITE)))
-         {
-            MmDereserveSwapPages(PAGE_ROUND_UP((*RegionSize)));
-         }
-       MmSplitMemoryArea(Process,
-                         &Process->AddressSpace,
-                         MemoryArea,
-                         *BaseAddress,
-                         *RegionSize,
-                         MEMORY_AREA_RESERVE,
-                         MemoryArea->Attributes);
-       MmUnlockAddressSpace(AddressSpace);     
-       ObDereferenceObject(Process);
-       return(STATUS_SUCCESS);
+       /* Don't allow to change the protection of a kernel mode address */
+       return STATUS_INVALID_PARAMETER_2;
      }
-   MmUnlockAddressSpace(AddressSpace);
-   ObDereferenceObject(Process);
-   return(STATUS_NOT_IMPLEMENTED);
-}
 
+   /* (tMk 2004.II.5) in Microsoft SDK I read:
+    * 'if this parameter is NULL or does not point to a valid variable, the function fails'
+    */
+   if(UnsafeOldAccessProtection == NULL)
+   {
+      return(STATUS_INVALID_PARAMETER);
+   }
 
-NTSTATUS STDCALL NtLockVirtualMemory(HANDLE    ProcessHandle,
-                                    PVOID      BaseAddress,
-                                    ULONG      NumberOfBytesToLock,
-                                    PULONG     NumberOfBytesLocked)
-{
-       UNIMPLEMENTED;
-}
+   Status = ObReferenceObjectByHandle(ProcessHandle,
+                                      PROCESS_VM_OPERATION,
+                                      PsProcessType,
+                                      UserMode,
+                                      (PVOID*)(&Process),
+                                      NULL);
+   if (!NT_SUCCESS(Status))
+   {
+      DPRINT("NtProtectVirtualMemory() = %x\n",Status);
+      return(Status);
+   }
 
+   Status = MiProtectVirtualMemory(Process,
+                                   &BaseAddress,
+                                   &NumberOfBytesToProtect,
+                                   NewAccessProtection,
+                                   &OldAccessProtection);
 
-VOID MmChangeAreaProtection(PEPROCESS Process,
-                           PVOID BaseAddress,
-                           ULONG Length,
-                           ULONG Protect)
-{
-   ULONG i;
-   
-   for (i=0; i<(Length/PAGESIZE); i++)
+   ObDereferenceObject(Process);
+
+   if (PreviousMode != KernelMode)
+     {
+       _SEH_TRY
+         {
+           *UnsafeOldAccessProtection = OldAccessProtection;
+           *UnsafeBaseAddress = BaseAddress;
+           *UnsafeNumberOfBytesToProtect = NumberOfBytesToProtect;
+         }
+       _SEH_HANDLE
+         {
+           Status = _SEH_GetExceptionCode();
+         }
+       _SEH_END;
+     }
+   else
      {
-       if (MmIsPagePresent(Process, BaseAddress + (i*PAGESIZE)))
-         {
-            MmSetPageProtect(Process,
-                             BaseAddress + (i*PAGESIZE), 
-                             Protect);
-         }
+       *UnsafeOldAccessProtection = OldAccessProtection;
+       *UnsafeBaseAddress = BaseAddress;
+       *UnsafeNumberOfBytesToProtect = NumberOfBytesToProtect;
      }
+
+   return(Status);
 }
 
 
-NTSTATUS STDCALL NtProtectVirtualMemory(IN     HANDLE  ProcessHandle,
-                                       IN      PVOID   BaseAddress,
-                                       IN      ULONG   NumberOfBytesToProtect,
-                                       IN      ULONG   NewAccessProtection,
-                                       OUT     PULONG  OldAccessProtection)
+/* (tMk 2004.II.05)
+ * FUNCTION:
+ * Called from ReadProcessMemory (lib\kernel32\mem\procmem.c) and KlInitPeb(lib\kernel32\process\create.c)
+ *
+ * NOTE: This function will be correct if MmProbeAndLockPages() would be fully IMPLEMENTED.
+ */
+NTSTATUS STDCALL
+NtReadVirtualMemory(IN HANDLE ProcessHandle,
+                    IN PVOID BaseAddress,
+                    OUT PVOID Buffer,
+                    IN ULONG NumberOfBytesToRead,
+                    OUT PULONG NumberOfBytesRead OPTIONAL)
 {
-   PMEMORY_AREA MemoryArea;
-   PEPROCESS Process;
-   NTSTATUS Status;
-   PMADDRESS_SPACE AddressSpace;
-   
-   Status = ObReferenceObjectByHandle(ProcessHandle,
-                                     PROCESS_VM_OPERATION,
-                                     PsProcessType,
-                                     UserMode,
-                                     (PVOID*)(&Process),
-                                     NULL);
-   if (Status != STATUS_SUCCESS)
+   PMDL Mdl;
+   PVOID SystemAddress;
+   KPROCESSOR_MODE PreviousMode;
+   PEPROCESS Process, CurrentProcess;
+   NTSTATUS Status = STATUS_SUCCESS;
+
+   PAGED_CODE();
+
+   DPRINT("NtReadVirtualMemory(ProcessHandle %x, BaseAddress %x, "
+          "Buffer %x, NumberOfBytesToRead %d)\n",ProcessHandle,BaseAddress,
+          Buffer,NumberOfBytesToRead);
+
+   if ((ULONG_PTR)BaseAddress + NumberOfBytesToRead - 1 < (ULONG_PTR)BaseAddress ||
+       (ULONG_PTR)BaseAddress + NumberOfBytesToRead - 1 >= MmUserProbeAddress)
      {
-       DPRINT("NtProtectVirtualMemory() = %x\n",Status);
-       return(Status);
+       /* Don't allow to read from kernel space */
+       return STATUS_ACCESS_VIOLATION;
      }
 
-   AddressSpace = &Process->AddressSpace;
-   
-   MmLockAddressSpace(AddressSpace);
-   MemoryArea = MmOpenMemoryAreaByAddress(AddressSpace,
-                                         BaseAddress);
-   if (MemoryArea == NULL)
+   PreviousMode = ExGetPreviousMode();
+
+   if (PreviousMode != KernelMode)
      {
-       DPRINT("NtProtectVirtualMemory() = %x\n",STATUS_UNSUCCESSFUL);
-       MmUnlockAddressSpace(AddressSpace);
-       ObDereferenceObject(Process);
-       return(STATUS_UNSUCCESSFUL);
+       if ((ULONG_PTR)Buffer + NumberOfBytesToRead - 1 < (ULONG_PTR)Buffer ||
+           (ULONG_PTR)Buffer + NumberOfBytesToRead - 1 >= MmUserProbeAddress)
+         {
+           /* Don't allow to write into kernel space */
+           return STATUS_ACCESS_VIOLATION;
+         }
      }
 
-   *OldAccessProtection = MemoryArea->Attributes;
+   Status = ObReferenceObjectByHandle(ProcessHandle,
+                                      PROCESS_VM_READ,
+                                      NULL,
+                                      PreviousMode,
+                                      (PVOID*)(&Process),
+                                      NULL);
+   if (!NT_SUCCESS(Status))
+   {
+      return(Status);
+   }
 
-   if (MemoryArea->BaseAddress == BaseAddress &&
-       MemoryArea->Length == NumberOfBytesToProtect)
+   CurrentProcess = PsGetCurrentProcess();
+
+   if(PreviousMode != KernelMode)
+   {
+     _SEH_TRY
      {
-       MemoryArea->Attributes = NewAccessProtection;   
+       if(NumberOfBytesRead != NULL)
+       {
+         ProbeForWriteUlong(NumberOfBytesRead);
+       }
      }
-   else
+     _SEH_HANDLE
      {
-       MemoryArea = MmSplitMemoryArea(Process,
-                                      &Process->AddressSpace,
-                                      MemoryArea,
-                                      BaseAddress,
-                                      NumberOfBytesToProtect,
-                                      MemoryArea->Type,
-                                      NewAccessProtection);
+       Status = _SEH_GetExceptionCode();
      }
-   MmChangeAreaProtection(Process,
-                         BaseAddress,
-                         NumberOfBytesToProtect,
-                         NewAccessProtection);
-   MmUnlockAddressSpace(AddressSpace);
-   ObDereferenceObject(Process);
-   return(STATUS_SUCCESS);
-}
+     _SEH_END;
 
+     if(!NT_SUCCESS(Status))
+     {
+       return Status;
+     }
+   }
 
-NTSTATUS STDCALL NtQueryVirtualMemory (IN HANDLE ProcessHandle,
-                                      IN PVOID Address,
-                                      IN CINT VirtualMemoryInformationClass,
-                                      OUT PVOID VirtualMemoryInformation,
-                                      IN ULONG Length,
-                                      OUT PULONG ResultLength)
-{
-   NTSTATUS Status;
-   PEPROCESS Process;
-   MEMORY_AREA* MemoryArea;
 
-   DPRINT("NtQueryVirtualMemory(ProcessHandle %x, Address %x, "
-          "VirtualMemoryInformationClass %d, VirtualMemoryInformation %x, "
-          "Length %lu ResultLength %x)\n",ProcessHandle,Address,
-          VirtualMemoryInformationClass,VirtualMemoryInformation,
-          Length,ResultLength);
+   if (Process == CurrentProcess)
+   {
+      _SEH_TRY
+      {
+        RtlCopyMemory(Buffer, BaseAddress, NumberOfBytesToRead);
+      }
+      _SEH_HANDLE
+      {
+        Status = _SEH_GetExceptionCode();
+      }
+      _SEH_END;
+   }
+   else
+   {
+      Mdl = MmCreateMdl(NULL,
+                        Buffer,
+                        NumberOfBytesToRead);
+      if(Mdl == NULL)
+      {
+         ObDereferenceObject(Process);
+         return(STATUS_NO_MEMORY);
+      }
+      _SEH_TRY
+      {
+        MmProbeAndLockPages(Mdl,
+                            PreviousMode,
+                            IoWriteAccess);
+      }
+      _SEH_HANDLE
+      {
+        Status = _SEH_GetExceptionCode();
+      }
+      _SEH_END;
 
-   switch(VirtualMemoryInformationClass)
+      if(NT_SUCCESS(Status))
+      {
+        KeAttachProcess(&Process->Pcb);
+
+        SystemAddress = MmGetSystemAddressForMdl(Mdl);
+
+          Status = STATUS_SUCCESS;
+          _SEH_TRY {
+              Status = STATUS_PARTIAL_COPY;
+              RtlCopyMemory(SystemAddress, BaseAddress, NumberOfBytesToRead);
+              Status = STATUS_SUCCESS;
+          } _SEH_HANDLE {
+              if(Status != STATUS_PARTIAL_COPY)
+                  Status = _SEH_GetExceptionCode();
+          } _SEH_END;
+
+        KeDetachProcess();
+
+        if (Mdl->MappedSystemVa != NULL)
+        {
+           MmUnmapLockedPages(Mdl->MappedSystemVa, Mdl);
+        }
+        MmUnlockPages(Mdl);
+      }
+      ExFreePool(Mdl);
+   }
+
+   ObDereferenceObject(Process);
+
+   if((NT_SUCCESS(Status) || Status == STATUS_PARTIAL_COPY) &&
+      NumberOfBytesRead != NULL)
+   {
+     _SEH_TRY
      {
-        case MemoryBasicInformation:
-          {
-             PMEMORY_BASIC_INFORMATION Info =
-                (PMEMORY_BASIC_INFORMATION)VirtualMemoryInformation;
-            PMADDRESS_SPACE AddressSpace;
-            
-             if (Length < sizeof(MEMORY_BASIC_INFORMATION))
-               {
-                  ObDereferenceObject(Process);
-                  return STATUS_INFO_LENGTH_MISMATCH;
-               }
-
-             if (ResultLength)
-               {
-                  *ResultLength = sizeof(MEMORY_BASIC_INFORMATION);
-               }
-
-             Status = ObReferenceObjectByHandle(ProcessHandle,
-                                                PROCESS_QUERY_INFORMATION,
-                                                NULL,
-                                                UserMode,
-                                                (PVOID*)(&Process),
-                                                NULL);
-
-             if (!NT_SUCCESS(Status))
-               {
-                  DPRINT("NtQueryVirtualMemory() = %x\n",Status);
-                  return(Status);
-               }
-
-            AddressSpace = &Process->AddressSpace;
-            MmLockAddressSpace(AddressSpace);
-             MemoryArea = MmOpenMemoryAreaByAddress(AddressSpace,
-                                                    Address);
-
-             if (MemoryArea == NULL)
-               {
-                  Info->State = MEM_FREE;
-                  DPRINT("Virtual memory at %p is free.\n", Address);
-                 MmUnlockAddressSpace(AddressSpace);
-                  ObDereferenceObject(Process);
-                  return (STATUS_SUCCESS);
-               }
-
-             if (MemoryArea->Type == MEMORY_AREA_COMMIT)
-               {
-                  Info->State = MEM_COMMIT;
-               }
-             else
-               {
-                  Info->State = MEM_RESERVE;
-               }
-
-             Info->BaseAddress = MemoryArea->BaseAddress;
-             Info->RegionSize  = MemoryArea->Length;
-
-             DPRINT("BaseAddress %p, RegionSize %x State %x\n",
-                    Info->BaseAddress, Info->RegionSize, Info->State);
-            
-            MmUnlockAddressSpace(AddressSpace);
-             ObDereferenceObject(Process);
-             return STATUS_SUCCESS;
-          }
-          break;
+       *NumberOfBytesRead = NumberOfBytesToRead;
      }
+     _SEH_HANDLE
+     {
+       Status = _SEH_GetExceptionCode();
+     }
+     _SEH_END;
+   }
 
-   return STATUS_INVALID_INFO_CLASS;
+   return(Status);
 }
 
-
-NTSTATUS STDCALL NtReadVirtualMemory(IN        HANDLE  ProcessHandle,
-                                    IN PVOID   BaseAddress,
-                                    OUT        PVOID   Buffer,
-                                    IN ULONG   NumberOfBytesToRead,
-                                    OUT        PULONG  NumberOfBytesRead)
+/* (tMk 2004.II.05)
+ * FUNCTION:  THIS function doesn't make a sense...
+ * Called from VirtualUnlock (lib\kernel32\mem\virtual.c)
+ */
+NTSTATUS STDCALL
+NtUnlockVirtualMemory(HANDLE ProcessHandle,
+                      PVOID BaseAddress,
+                      ULONG NumberOfBytesToUnlock,
+                      PULONG NumberOfBytesUnlocked OPTIONAL)
 {
+   // AG [08-20-03] : I have *no* idea if this is correct, I just used the
+   // other functions as a template and made a few intelligent guesses...
+
    NTSTATUS Status;
    PMDL Mdl;
-   PVOID SystemAddress;
    PEPROCESS Process;
-   
-   DPRINT("NtReadVirtualMemory(ProcessHandle %x, BaseAddress %x, "
-           "Buffer %x, NumberOfBytesToRead %d)\n",ProcessHandle,BaseAddress,
-           Buffer,NumberOfBytesToRead);
-   
+
+   DPRINT("NtUnlockVirtualMemory(ProcessHandle %x, BaseAddress %x, "
+          "NumberOfBytesToUnlock %d), NumberOfBytesUnlocked %x\n",ProcessHandle,BaseAddress,
+          NumberOfBytesToUnlock, NumberOfBytesUnlocked);
+
    Status = ObReferenceObjectByHandle(ProcessHandle,
-                                     PROCESS_VM_WRITE,
-                                     NULL,
-                                     UserMode,
-                                     (PVOID*)(&Process),
-                                     NULL);
-   if (Status != STATUS_SUCCESS)
-     {
-       return(Status);
-     }
-   
-   Mdl = MmCreateMdl(NULL, 
-                    Buffer,
-                    NumberOfBytesToRead);
-   MmProbeAndLockPages(Mdl,
-                      UserMode,
-                      IoWriteAccess);
-   
-   KeAttachProcess(Process);
-   
-   SystemAddress = MmGetSystemAddressForMdl(Mdl);
-   memcpy(SystemAddress, BaseAddress, NumberOfBytesToRead);
-   
-   KeDetachProcess();
-   
+                                      PROCESS_VM_WRITE,
+                                      NULL,
+                                      UserMode,
+                                      (PVOID*)(&Process),
+                                      NULL);
+   if (!NT_SUCCESS(Status))
+   {
+      return(Status);
+   }
+
+   Mdl = MmCreateMdl(NULL,
+                     BaseAddress,
+                     NumberOfBytesToUnlock);
+   if(Mdl == NULL)
+   {
+      ObDereferenceObject(Process);
+      return(STATUS_NO_MEMORY);
+   }
+
    ObDereferenceObject(Process);
-   
-   *NumberOfBytesRead = NumberOfBytesToRead;
-   return(STATUS_SUCCESS);
-}
 
+   if (Mdl->MappedSystemVa != NULL)
+   {
+      MmUnmapLockedPages(Mdl->MappedSystemVa, Mdl);
+   }
+   MmUnlockPages(Mdl);
+   ExFreePool(Mdl);
 
-NTSTATUS STDCALL NtUnlockVirtualMemory(HANDLE  ProcessHandle,
-                                      PVOID    BaseAddress,
-                                      ULONG    NumberOfBytesToUnlock,
-                                      PULONG NumberOfBytesUnlocked OPTIONAL)
-{
-       UNIMPLEMENTED;
+   *NumberOfBytesUnlocked = NumberOfBytesToUnlock;
+
+   return(STATUS_SUCCESS);
 }
 
 
-NTSTATUS STDCALL NtWriteVirtualMemory(IN       HANDLE  ProcessHandle,
-                                     IN        PVOID   BaseAddress,
-                                     IN        PVOID   Buffer,
-                                     IN        ULONG   NumberOfBytesToWrite,
-                                     OUT       PULONG  NumberOfBytesWritten)
+/* (tMk 2004.II.05)
+ * FUNCTION:
+ * Called from WriteProcessMemory (lib\kernel32\mem\procmem.c) and KlInitPeb(lib\kernel32\process\create.c)
+ *
+ * NOTE: This function will be correct if MmProbeAndLockPages() would be fully IMPLEMENTED.
+ */
+NTSTATUS STDCALL
+NtWriteVirtualMemory(IN HANDLE ProcessHandle,
+                     IN PVOID BaseAddress,
+                     IN PVOID Buffer,
+                     IN ULONG NumberOfBytesToWrite,
+                     OUT PULONG NumberOfBytesWritten  OPTIONAL)
 {
-   NTSTATUS Status;
    PMDL Mdl;
    PVOID SystemAddress;
    PEPROCESS Process;
-   
+   KPROCESSOR_MODE PreviousMode;
+   NTSTATUS CopyStatus, Status = STATUS_SUCCESS;
+
    DPRINT("NtWriteVirtualMemory(ProcessHandle %x, BaseAddress %x, "
-           "Buffer %x, NumberOfBytesToWrite %d)\n",ProcessHandle,BaseAddress,
-           Buffer,NumberOfBytesToWrite);
-   
-   Status = ObReferenceObjectByHandle(ProcessHandle,
-                                     PROCESS_VM_WRITE,
-                                     NULL,
-                                     UserMode,
-                                     (PVOID*)(&Process),
-                                     NULL);
-   if (Status != STATUS_SUCCESS)
+          "Buffer %x, NumberOfBytesToWrite %d)\n",ProcessHandle,BaseAddress,
+          Buffer,NumberOfBytesToWrite);
+
+   if ((ULONG_PTR)BaseAddress + NumberOfBytesToWrite - 1 < (ULONG_PTR)BaseAddress ||
+       (ULONG_PTR)BaseAddress + NumberOfBytesToWrite - 1 >= MmUserProbeAddress)
      {
-       return(Status);
+       /* Don't allow to write into kernel space */
+       return STATUS_ACCESS_VIOLATION;
      }
+
+   PreviousMode = ExGetPreviousMode();
    
-   Mdl = MmCreateMdl(NULL, 
-                    Buffer,
-                    NumberOfBytesToWrite);
-   MmProbeAndLockPages(Mdl,
-                      UserMode,
-                      IoReadAccess);
-   
-   KeAttachProcess(Process);
-   
-   DPRINT("Attached to process copying memory\n");
-   
-   SystemAddress = MmGetSystemAddressForMdl(Mdl);
-   memcpy(BaseAddress, SystemAddress, NumberOfBytesToWrite);
-   
-   DPRINT("Done copy\n");
-   
-   KeDetachProcess();
-   
+   if (PreviousMode != KernelMode)
+     {
+       if ((ULONG_PTR)Buffer + NumberOfBytesToWrite - 1 < (ULONG_PTR)Buffer ||
+           (ULONG_PTR)Buffer + NumberOfBytesToWrite - 1 >= MmUserProbeAddress)
+         {
+           /* Don't allow to read from kernel space */
+           return STATUS_ACCESS_VIOLATION;
+         }
+       if (NumberOfBytesWritten != NULL)
+         {
+           _SEH_TRY
+             {
+               ProbeForWriteUlong(NumberOfBytesWritten);
+             }
+           _SEH_HANDLE
+             {
+               Status = _SEH_GetExceptionCode();
+             }
+           _SEH_END;
+       
+           if (!NT_SUCCESS(Status))
+             {
+               return Status;
+             }
+          }
+     }
+
+   Status = ObReferenceObjectByHandle(ProcessHandle,
+                                      PROCESS_VM_WRITE,
+                                      NULL,
+                                      UserMode,
+                                      (PVOID*)(&Process),
+                                      NULL);
+   if (!NT_SUCCESS(Status))
+   {
+      return(Status);
+   }
+
+   CopyStatus = STATUS_SUCCESS;
+
+   /* Write memory */
+   if (Process == PsGetCurrentProcess())
+   {
+      if (PreviousMode != KernelMode)
+        {
+         _SEH_TRY
+            {
+              memcpy(BaseAddress, Buffer, NumberOfBytesToWrite);
+            }
+          _SEH_HANDLE
+            {
+              CopyStatus = _SEH_GetExceptionCode();
+            }
+          _SEH_END;
+        }
+      else
+        {
+          memcpy(BaseAddress, Buffer, NumberOfBytesToWrite);
+        }
+   }
+   else
+   {
+      /* Create MDL describing the source buffer. */
+      Mdl = MmCreateMdl(NULL,
+                        Buffer,
+                        NumberOfBytesToWrite);
+      if(Mdl == NULL)
+        {
+          ObDereferenceObject(Process);
+          return(STATUS_NO_MEMORY);
+        }
+      _SEH_TRY
+        {
+          /* Map the MDL. */
+          MmProbeAndLockPages(Mdl,
+                              UserMode,
+                              IoReadAccess);
+       }
+      _SEH_HANDLE
+        {
+         CopyStatus = _SEH_GetExceptionCode();
+        }
+      _SEH_END;
+
+      if (NT_SUCCESS(CopyStatus))
+        {
+          /* Copy memory from the mapped MDL into the target buffer. */
+          KeAttachProcess(&Process->Pcb);
+
+          SystemAddress = MmGetSystemAddressForMdl(Mdl);
+          if (PreviousMode != KernelMode)
+            {
+              _SEH_TRY
+                {
+                  memcpy(BaseAddress, SystemAddress, NumberOfBytesToWrite);
+                }
+              _SEH_HANDLE
+                {
+                  CopyStatus = _SEH_GetExceptionCode();
+                }
+              _SEH_END;
+            }
+          else
+            {
+              memcpy(BaseAddress, SystemAddress, NumberOfBytesToWrite);
+            }
+
+          KeDetachProcess();
+       }
+
+      /* Free the MDL. */
+      if (Mdl->MappedSystemVa != NULL)
+      {
+         MmUnmapLockedPages(Mdl->MappedSystemVa, Mdl);
+      }
+      MmUnlockPages(Mdl);
+      ExFreePool(Mdl);
+   }
    ObDereferenceObject(Process);
-   
-   *NumberOfBytesWritten = NumberOfBytesToWrite;
-   
-   DPRINT("Finished NtWriteVirtualMemory()\n");
-   
-   return(STATUS_SUCCESS);
+
+   if (NT_SUCCESS(CopyStatus) && NumberOfBytesWritten != NULL)
+     {
+       if (PreviousMode != KernelMode)
+         {
+           _SEH_TRY
+             {
+               *NumberOfBytesWritten = NumberOfBytesToWrite;
+             }
+           _SEH_HANDLE
+             {
+               Status = _SEH_GetExceptionCode();
+             }
+           _SEH_END;
+         }
+       else
+         {
+           *NumberOfBytesWritten = NumberOfBytesToWrite;
+         }
+     }
+
+   return(NT_SUCCESS(CopyStatus) ? Status : CopyStatus);
 }
 
+/*
+ * @unimplemented
+ */
 
-DWORD
+PVOID
 STDCALL
-MmSecureVirtualMemory (
-       DWORD   Unknown0,
-       DWORD   Unknown1,
-       DWORD   Unknown2
-       )
+MmGetVirtualForPhysical (
+    IN PHYSICAL_ADDRESS PhysicalAddress
+    )
 {
        UNIMPLEMENTED;
        return 0;
 }
 
+/* FUNCTION:
+ * Called from EngSecureMem (subsys\win32k\eng\mem.c)
+ * @unimplemented
+ */
+PVOID STDCALL
+MmSecureVirtualMemory (PVOID  Address,
+                       SIZE_T Length,
+                       ULONG  Mode)
+{
+   /* Only works for user space */
+   if (MmHighestUserAddress < Address)
+   {
+      return NULL;
+   }
 
-VOID
-STDCALL
-MmUnsecureVirtualMemory (
-       DWORD   Unknown0
-       )
+   UNIMPLEMENTED;
+
+   return 0;
+}
+
+
+/* FUNCTION:
+ * Called from EngUnsecureMem (subsys\win32k\eng\mem.c)
+ * @unimplemented
+ */
+VOID STDCALL
+MmUnsecureVirtualMemory(PVOID SecureMem)
 {
-       UNIMPLEMENTED;
+   if (NULL == SecureMem)
+   {
+      return;
+   }
+
+   UNIMPLEMENTED;
+}
+
+
+/*
+ * @implemented
+ */
+VOID STDCALL
+ProbeForRead (IN CONST VOID *Address,
+              IN ULONG Length,
+              IN ULONG Alignment)
+{
+   ASSERT(Alignment == 1 || Alignment == 2 || Alignment == 4 || Alignment == 8);
+
+   if (Length == 0)
+      return;
+
+   if (((ULONG_PTR)Address & (Alignment - 1)) != 0)
+   {
+      ExRaiseStatus (STATUS_DATATYPE_MISALIGNMENT);
+   }
+   else if ((ULONG_PTR)Address + Length - 1 < (ULONG_PTR)Address ||
+            (ULONG_PTR)Address + Length - 1 >= (ULONG_PTR)MmUserProbeAddress)
+   {
+      ExRaiseStatus (STATUS_ACCESS_VIOLATION);
+   }
+}
+
+
+/*
+ * @implemented
+ */
+VOID STDCALL
+ProbeForWrite (IN CONST VOID *Address,
+               IN ULONG Length,
+               IN ULONG Alignment)
+{
+   volatile CHAR *Current;
+   PCHAR Last;
+
+   ASSERT(Alignment == 1 || Alignment == 2 || Alignment == 4 || Alignment == 8);
+
+   if (Length == 0)
+      return;
+
+   if (((ULONG_PTR)Address & (Alignment - 1)) != 0)
+   {
+      ExRaiseStatus (STATUS_DATATYPE_MISALIGNMENT);
+   }
+
+   Last = (CHAR*)((ULONG_PTR)Address + Length - 1);
+   if ((ULONG_PTR)Last < (ULONG_PTR)Address ||
+       (ULONG_PTR)Last >= (ULONG_PTR)MmUserProbeAddress)
+   {
+      ExRaiseStatus (STATUS_ACCESS_VIOLATION);
+   }
+
+   /* Check for accessible pages */
+   Current = (CHAR*)Address;
+   *Current = *Current;
+   Current = (PCHAR)((ULONG_PTR)PAGE_ROUND_DOWN(Current) + PAGE_SIZE);
+   while (Current <= Last)
+   {
+     *Current = *Current;
+     Current = (CHAR*)((ULONG_PTR)Current + PAGE_SIZE);
+   } 
 }
 
 /* EOF */