using System; using System.Runtime.InteropServices; using Vanara.InteropServices; namespace Vanara.PInvoke { public static partial class Kernel32 { /// /// An application-defined function registered with the RegisterBadMemoryNotification function that is called when one or more bad /// memory pages are detected. /// [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void BadMemoryCallbackRoutine(); /// Flags that indicate which of the file cache limits are enabled. [PInvokeData("MemoryApi.h")] [Flags] public enum FILE_CACHE_LIMITS : uint { /// /// Enable the maximum size limit. /// The FILE_CACHE_MAX_HARD_DISABLE and FILE_CACHE_MAX_HARD_ENABLE flags are mutually exclusive. /// FILE_CACHE_MAX_HARD_ENABLE = 0x00000001, /// /// Disable the maximum size limit. /// The FILE_CACHE_MAX_HARD_DISABLE and FILE_CACHE_MAX_HARD_ENABLE flags are mutually exclusive. /// FILE_CACHE_MAX_HARD_DISABLE = 0x00000002, /// /// Enable the minimum size limit. /// The FILE_CACHE_MIN_HARD_DISABLE and FILE_CACHE_MIN_HARD_ENABLE flags are mutually exclusive. /// FILE_CACHE_MIN_HARD_ENABLE = 0x00000004, /// /// Disable the minimum size limit. /// The FILE_CACHE_MIN_HARD_DISABLE and FILE_CACHE_MIN_HARD_ENABLE flags are mutually exclusive. /// FILE_CACHE_MIN_HARD_DISABLE = 0x00000008, } /// The type of access to a file mapping object, which determines the page protection of the pages. [PInvokeData("MemoryApi.h")] [Flags] public enum FILE_MAP : uint { /// /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or /// PAGE_EXECUTE_READWRITE protection. /// When used with MapViewOfFileEx, (FILE_MAP_WRITE | FILE_MAP_READ) and FILE_MAP_ALL_ACCESS are equivalent to FILE_MAP_WRITE. /// FILE_MAP_WRITE = SECTION_MAP.SECTION_MAP_WRITE, /// /// A read-only view of the file is mapped. An attempt to write to the file view results in an access violation. /// /// The file mapping object must have been created with PAGE_READONLY, PAGE_READWRITE, PAGE_EXECUTE_READ, or /// PAGE_EXECUTE_READWRITE protection. /// /// FILE_MAP_READ = SECTION_MAP.SECTION_MAP_READ, /// /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or /// PAGE_EXECUTE_READWRITE protection. /// When used with the MapViewOfFileEx function, FILE_MAP_ALL_ACCESS is equivalent to FILE_MAP_WRITE. /// FILE_MAP_ALL_ACCESS = SECTION_MAP.SECTION_ALL_ACCESS, /// /// An executable view of the file is mapped (mapped memory can be run as code). The file mapping object must have been created /// with PAGE_EXECUTE_READ, PAGE_EXECUTE_WRITECOPY, or PAGE_EXECUTE_READWRITE protection. /// /// Windows Server 2003 and Windows XP: This value is available starting with Windows XP with SP2 and Windows Server 2003 with SP1. /// /// FILE_MAP_EXECUTE = SECTION_MAP.SECTION_MAP_EXECUTE_EXPLICIT, /// /// A copy-on-write view of the file is mapped. The file mapping object must have been created with PAGE_READONLY, /// PAGE_READ_EXECUTE, PAGE_WRITECOPY, PAGE_EXECUTE_WRITECOPY, PAGE_READWRITE, or PAGE_EXECUTE_READWRITE protection. /// /// When a process writes to a copy-on-write page, the system copies the original page to a new page that is private to the /// process.The new page is backed by the paging file.The protection of the new page changes from copy-on-write to read/write. /// /// /// When copy-on-write access is specified, the system and process commit charge taken is for the entire view because the calling /// process can potentially write to every page in the view, making all pages private. The contents of the new page are never /// written back to the original file and are lost when the view is unmapped. /// /// FILE_MAP_COPY = 0x00000001, /// FILE_MAP_RESERVE = 0x80000000, /// /// Sets all the locations in the mapped file as invalid targets for CFG. This flag is similar to PAGE_TARGETS_INVALID. It is /// used along with the execute access right FILE_MAP_EXECUTE. Any indirect call to locations in those pages will fail CFG checks /// and the process will be terminated. The default behavior for executable pages allocated is to be marked valid call targets /// for CFG. /// FILE_MAP_TARGETS_INVALID = 0x40000000, /// FILE_MAP_LARGE_PAGES = 0x20000000, } /// The type of memory allocation. [PInvokeData("WinNT.h")] [Flags] public enum MEM_ALLOCATION_TYPE : uint { /// /// Allocates memory charges (from the overall size of memory and the paging files on disk) for the specified reserved memory /// pages. The function also guarantees that when the caller later initially accesses the memory, the contents will be zero. /// Actual physical pages are not allocated unless/until the virtual addresses are actually accessed.To reserve and commit pages /// in one step, call VirtualAlloc with .Attempting to commit a specific address range by specifying MEM_COMMIT without /// MEM_RESERVE and a non-NULL lpAddress fails unless the entire range has already been reserved. The resulting error code is /// ERROR_INVALID_ADDRESS.An attempt to commit a page that is already committed does not cause the function to fail. This means /// that you can commit pages without first determining the current commitment state of each page.If lpAddress specifies an /// address within an enclave, flAllocationType must be MEM_COMMIT. /// MEM_COMMIT = 0x00001000, /// /// Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the /// paging file on disk.You can commit reserved pages in subsequent calls to the VirtualAlloc function. To reserve and commit /// pages in one step, call VirtualAlloc with MEM_COMMIT | MEM_RESERVE.Other memory allocation functions, such as malloc and /// LocalAlloc, cannot use a reserved range of memory until it is released. /// MEM_RESERVE = 0x00002000, /// /// Decommits the specified region of committed pages. After the operation, the pages are in the reserved state. The function /// does not fail if you attempt to decommit an uncommitted page. This means that you can decommit a range of pages without first /// determining the current commitment state.Do not use this value with MEM_RELEASE.The MEM_DECOMMIT value is not supported when /// the lpAddress parameter provides the base address for an enclave. /// MEM_DECOMMIT = 0x00004000, /// /// Releases the specified region of pages. After this operation, the pages are in the free state. If you specify this value, /// dwSize must be 0 (zero), and lpAddress must point to the base address returned by the VirtualAlloc function when the region /// is reserved. The function fails if either of these conditions is not met. If any pages in the region are committed currently, /// the function first decommits, and then releases them.The function does not fail if you attempt to release pages that are in /// different states, some reserved and some committed. This means that you can release a range of pages without first /// determining the current commitment state.Do not use this value with MEM_DECOMMIT. /// MEM_RELEASE = 0x00008000, /// /// Indicates free pages not accessible to the calling process and available to be allocated. For free pages, the information in /// the AllocationBase, AllocationProtect, Protect, and Type members is undefined. /// MEM_FREE = 0x00010000, /// Indicates that the memory pages within the region are private (that is, not shared by other processes). MEM_PRIVATE = 0x00020000, /// Indicates that the memory pages within the region are mapped into the view of a section. MEM_MAPPED = 0x00040000, /// /// Indicates that data in the memory range specified by lpAddress and dwSize is no longer of interest. The pages should not be /// read from or written to the paging file. However, the memory block will be used again later, so it should not be decommitted. /// This value cannot be used with any other value.Using this value does not guarantee that the range operated on with MEM_RESET /// will contain zeros. If you want the range to contain zeros, decommit the memory and then recommit it.When you specify /// MEM_RESET, the VirtualAlloc function ignores the value of flProtect. However, you must still set flProtect to a valid /// protection value, such as PAGE_NOACCESS.VirtualAlloc returns an error if you use MEM_RESET and the range of memory is mapped /// to a file. A shared view is only acceptable if it is mapped to a paging file. /// MEM_RESET = 0x00080000, /// /// Allocates memory at the highest possible address. This can be slower than regular allocations, especially when there are many allocations. /// MEM_TOP_DOWN = 0x00100000, /// /// Causes the system to track pages that are written to in the allocated region. If you specify this value, you must also /// specify MEM_RESERVE.To retrieve the addresses of the pages that have been written to since the region was allocated or the /// write-tracking state was reset, call the GetWriteWatch function. To reset the write-tracking state, call GetWriteWatch or /// ResetWriteWatch. The write-tracking feature remains enabled for the memory region until the region is freed. /// MEM_WRITE_WATCH = 0x00200000, /// /// Reserves an address range that can be used to map Address Windowing Extensions (AWE) pages.This value must be used with /// MEM_RESERVE and no other values. /// MEM_PHYSICAL = 0x00400000, /// MEM_ROTATE = 0x00800000, /// MEM_DIFFERENT_IMAGE_BASE_OK = 0x00800000, /// /// MEM_RESET_UNDO should only be called on an address range to which MEM_RESET was successfully applied earlier. It indicates /// that the data in the specified memory range specified by lpAddress and dwSize is of interest to the caller and attempts to /// reverse the effects of MEM_RESET. If the function succeeds, that means all data in the specified address range is intact. If /// the function fails, at least some of the data in the address range has been replaced with zeroes.This value cannot be used /// with any other value. If MEM_RESET_UNDO is called on an address range which was not MEM_RESET earlier, the behavior is /// undefined. When you specify MEM_RESET, the VirtualAlloc function ignores the value of flProtect. However, you must still set /// flProtect to a valid protection value, such as PAGE_NOACCESS.Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows /// Vista, Windows Server 2003 and Windows XP: The MEM_RESET_UNDO flag is not supported until Windows 8 and Windows Server 2012. /// MEM_RESET_UNDO = 0x01000000, /// /// Allocates memory using large page support.The size and alignment must be a multiple of the large-page minimum. To obtain this /// value, use the GetLargePageMinimum function.If you specify this value, you must also specify MEM_RESERVE and MEM_COMMIT. /// MEM_LARGE_PAGES = 0x20000000, /// MEM_4MB_PAGES = 0x80000000, /// MEM_64K_PAGES = MEM_LARGE_PAGES | MEM_PHYSICAL } /// Flags used by to specify the value type. [PInvokeData("winnt.h", MSDNShortId = "8D189F7E-83E7-4AF3-9E25-928C66666887")] public enum MEM_EXTENDED_PARAMETER_TYPE : ulong { /// MemExtendedParameterInvalidType, /// /// This extended parameter type is used to specify alignment and virtual address range restrictions for new memory allocations /// created by VirtualAlloc2 and MapViewOfFile3. /// MemExtendedParameterAddressRequirements, /// /// This extended parameter type is used to specify the preferred NUMA node for new memory allocations created by VirtualAlloc2 /// and MapViewOfFile3. /// MemExtendedParameterNumaNode, /// MemExtendedParameterPartitionHandle, /// MemExtendedParameterUserPhysicalHandle, /// MemExtendedParameterAttributeFlags, /// MemExtendedParameterMax } /// /// The following are the memory-protection options; you must specify one of the following values when allocating or protecting a /// page in memory. Protection attributes cannot be assigned to a portion of a page; they can only be assigned to a whole page. /// [PInvokeData("WinNT.h")] [Flags] public enum MEM_PROTECTION : uint { /// /// Disables all access to the committed region of pages. An attempt to read from, write to, or execute the committed region /// results in an access violation. /// This flag is not supported by the CreateFileMapping function. /// PAGE_NOACCESS = 0x01, /// /// Enables read-only access to the committed region of pages. An attempt to write to the committed region results in an access /// violation. If Data Execution Prevention is enabled, an attempt to execute code in the committed region results in an access violation. /// PAGE_READONLY = 0x02, /// /// Enables read-only or read/write access to the committed region of pages. If Data Execution Prevention is enabled, attempting /// to execute code in the committed region results in an access violation. /// PAGE_READWRITE = 0x04, /// /// Enables read-only or copy-on-write access to a mapped view of a file mapping object. An attempt to write to a committed /// copy-on-write page results in a private copy of the page being made for the process. The private page is marked as /// PAGE_READWRITE, and the change is written to the new page. If Data Execution Prevention is enabled, attempting to execute /// code in the committed region results in an access violation. /// This flag is not supported by the VirtualAlloc or VirtualAllocEx functions. /// PAGE_WRITECOPY = 0x08, /// /// Enables execute access to the committed region of pages. An attempt to write to the committed region results in an access violation. /// This flag is not supported by the CreateFileMapping function. /// PAGE_EXECUTE = 0x10, /// /// Enables execute or read-only access to the committed region of pages. An attempt to write to the committed region results in /// an access violation. /// /// Windows Server 2003 and Windows XP: This attribute is not supported by the CreateFileMapping function until Windows XP with /// SP2 and Windows Server 2003 with SP1. /// /// PAGE_EXECUTE_READ = 0x20, /// /// Enables execute, read-only, or read/write access to the committed region of pages. /// /// Windows Server 2003 and Windows XP: This attribute is not supported by the CreateFileMapping function until Windows XP with /// SP2 and Windows Server 2003 with SP1. /// /// PAGE_EXECUTE_READWRITE = 0x40, /// /// Enables execute, read-only, or copy-on-write access to a mapped view of a file mapping object. An attempt to write to a /// committed copy-on-write page results in a private copy of the page being made for the process. The private page is marked as /// PAGE_EXECUTE_READWRITE, and the change is written to the new page. /// This flag is not supported by the VirtualAlloc or VirtualAllocEx functions. /// /// Windows Vista, Windows Server 2003 and Windows XP: This attribute is not supported by the CreateFileMapping function until /// Windows Vista with SP1 and Windows Server 2008. /// /// PAGE_EXECUTE_WRITECOPY = 0x80, /// /// Pages in the region become guard pages. Any attempt to access a guard page causes the system to raise a /// STATUS_GUARD_PAGE_VIOLATION exception and turn off the guard page status. Guard pages thus act as a one-time access alarm. /// For more information, see Creating Guard Pages. /// When an access attempt leads the system to turn off guard page status, the underlying page protection takes over. /// If a guard page exception occurs during a system service, the service typically returns a failure status indicator. /// This value cannot be used with PAGE_NOACCESS. /// This flag is not supported by the CreateFileMapping function. /// PAGE_GUARD = 0x100, /// /// Sets all pages to be non-cachable. Applications should not use this attribute except when explicitly required for a device. /// Using the interlocked functions with memory that is mapped with SEC_NOCACHE can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception. /// The PAGE_NOCACHE flag cannot be used with the PAGE_GUARD, PAGE_NOACCESS, or PAGE_WRITECOMBINE flags. /// /// The PAGE_NOCACHE flag can be used only when allocating private memory with the VirtualAlloc, VirtualAllocEx, or /// VirtualAllocExNuma functions. To enable non-cached memory access for shared memory, specify the SEC_NOCACHE flag when calling /// the CreateFileMapping function. /// /// PAGE_NOCACHE = 0x200, /// /// Sets all pages to be write-combined. /// /// Applications should not use this attribute except when explicitly required for a device. Using the interlocked functions with /// memory that is mapped as write-combined can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception. /// /// The PAGE_WRITECOMBINE flag cannot be specified with the PAGE_NOACCESS, PAGE_GUARD, and PAGE_NOCACHE flags. /// /// The PAGE_WRITECOMBINE flag can be used only when allocating private memory with the VirtualAlloc, VirtualAllocEx, or /// VirtualAllocExNuma functions. To enable write-combined memory access for shared memory, specify the SEC_WRITECOMBINE flag /// when calling the CreateFileMapping function. /// /// Windows Server 2003 and Windows XP: This flag is not supported until Windows Server 2003 with SP1. /// PAGE_WRITECOMBINE = 0x400, /// /// The page contents that you supply are excluded from measurement with the EEXTEND instruction of the Intel SGX programming model. /// PAGE_ENCLAVE_UNVALIDATED = 0x20000000, /// /// Sets all locations in the pages as invalid targets for CFG. Used along with any execute page protection like PAGE_EXECUTE, /// PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE and PAGE_EXECUTE_WRITECOPY. Any indirect call to locations in those pages will fail /// CFG checks and the process will be terminated. The default behavior for executable pages allocated is to be marked valid call /// targets for CFG. /// This flag is not supported by the VirtualProtect or CreateFileMapping functions. /// PAGE_TARGETS_INVALID = 0x40000000, /// /// Pages in the region will not have their CFG information updated while the protection changes for VirtualProtect. For example, /// if the pages in the region was allocated using PAGE_TARGETS_INVALID, then the invalid information will be maintained while /// the page protection changes. This flag is only valid when the protection changes to an executable type like PAGE_EXECUTE, /// PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE and PAGE_EXECUTE_WRITECOPY. The default behavior for VirtualProtect protection /// change to executable is to mark all locations as valid call targets for CFG. /// /// The following are modifiers that can be used in addition to the options provided in the previous table, except as noted. /// /// PAGE_TARGETS_NO_UPDATE = 0x40000000, /// The page contains a thread control structure (TCS). PAGE_ENCLAVE_THREAD_CONTROL = 0x80000000, /// PAGE_REVERT_TO_FILE_MAP = 0x80000000, } /// The memory condition under which the object is to be signaled. [PInvokeData("MemoryApi.h")] public enum MEMORY_RESOURCE_NOTIFICATION_TYPE { /// Available physical memory is running low. LowMemoryResourceNotification, /// Available physical memory is high. HighMemoryResourceNotification, } /// /// Indicates how important the offered memory is to the application. A higher priority increases the probability that the offered /// memory can be reclaimed intact when calling ReclaimVirtualMemory. /// public enum OFFER_PRIORITY { /// The offered memory is very low priority, and should be the first discarded. VmOfferPriorityVeryLow = 1, /// The offered memory is low priority. VmOfferPriorityLow, /// The offered memory is below normal priority. VmOfferPriorityBelowNormal, /// The offered memory is of normal priority to the application, and should be the last discarded. VmOfferPriorityNormal } /// Flags that determines the allocation attributes of the section, file, page, etc. [PInvokeData("winbase.h", MSDNShortId = "d3302183-76a0-47ec-874f-1173db353dfe")] public enum SEC_ALLOC : uint { /// /// If the file mapping object is backed by the operating system paging file (the hfile parameter is INVALID_HANDLE_VALUE), /// specifies that when a view of the file is mapped into a process address space, the entire range of pages is committed rather /// than reserved. The system must have enough committable pages to hold the entire mapping. Otherwise, CreateFileMapping /// fails.This attribute has no effect for file mapping objects that are backed by executable image files or data files (the /// hfile parameter is a handle to a file).SEC_COMMIT cannot be combined with SEC_RESERVE.If no attribute is specified, /// SEC_COMMIT is assumed. /// SEC_COMMIT = 0x8000000, /// /// Specifies that the file that the hFile parameter specifies is an executable image file.The SEC_IMAGE attribute must be /// combined with a page protection value such as PAGE_READONLY. However, this page protection value has no effect on views of /// the executable image file. Page protection for views of an executable image file is determined by the executable file /// itself.No other attributes are valid with SEC_IMAGE. /// SEC_IMAGE = 0x1000000, /// /// Specifies that the file that the hFile parameter specifies is an executable image file that will not be executed and the /// loaded image file will have no forced integrity checks run. Additionally, mapping a view of a file mapping object created /// with the SEC_IMAGE_NO_EXECUTE attribute will not invoke driver callbacks registered using the PsSetLoadImageNotifyRoutine /// kernel API.The SEC_IMAGE_NO_EXECUTE attribute must be combined with the PAGE_READONLY page protection value. No other /// attributes are valid with SEC_IMAGE_NO_EXECUTE.Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows /// Server 2003 and Windows XP: This value is not supported before Windows Server 2012 and Windows 8. /// SEC_IMAGE_NO_EXECUTE = 0x11000000, /// /// Enables large pages to be used for file mapping objects that are backed by the operating system paging file (the hfile /// parameter is INVALID_HANDLE_VALUE). This attribute is not supported for file mapping objects that are backed by executable /// image files or data files (the hFile parameter is a handle to an executable image or data file).The maximum size of the file /// mapping object must be a multiple of the minimum size of a large page returned by the GetLargePageMinimum function. If it is /// not, CreateFileMapping fails. When mapping a view of a file mapping object created with SEC_LARGE_PAGES, the base address and /// view size must also be multiples of the minimum large page size.SEC_LARGE_PAGES requires the SeLockMemoryPrivilege privilege /// to be enabled in the caller's token.If SEC_LARGE_PAGES is specified, SEC_COMMIT must also be specified.Windows Server 2003: /// This value is not supported until Windows Server 2003 with SP1.Windows XP: This value is not supported. /// SEC_LARGE_PAGES = 0x80000000, /// /// Sets all pages to be non-cachable.Applications should not use this attribute except when explicitly required for a device. /// Using the interlocked functions with memory that is mapped with SEC_NOCACHE can result in an EXCEPTION_ILLEGAL_INSTRUCTION /// exception.SEC_NOCACHE requires either the SEC_RESERVE or SEC_COMMIT attribute to be set. /// SEC_NOCACHE = 0x10000000, /// /// If the file mapping object is backed by the operating system paging file (the hfile parameter is INVALID_HANDLE_VALUE), /// specifies that when a view of the file is mapped into a process address space, the entire range of pages is reserved for /// later use by the process rather than committed.Reserved pages can be committed in subsequent calls to the VirtualAlloc /// function. After the pages are committed, they cannot be freed or decommitted with the VirtualFree function.This attribute has /// no effect for file mapping objects that are backed by executable image files or data files (the hfile parameter is a handle /// to a file).SEC_RESERVE cannot be combined with SEC_COMMIT. /// SEC_RESERVE = 0x4000000, /// /// Sets all pages to be write-combined.Applications should not use this attribute except when explicitly required for a device. /// Using the interlocked functions with memory that is mapped with SEC_WRITECOMBINE can result in an /// EXCEPTION_ILLEGAL_INSTRUCTION exception.SEC_WRITECOMBINE requires either the SEC_RESERVE or SEC_COMMIT attribute to be /// set.Windows Server 2003 and Windows XP: This flag is not supported until Windows Vista. /// SEC_WRITECOMBINE = 0x40000000, } /// Used by . public enum WIN32_MEMORY_INFORMATION_CLASS { /// This parameter must point to a WIN32_MEMORY_REGION_INFORMATION structure. MemoryRegionInfo } /// Flags used in . public enum WRITE_WATCH { /// Do not reset the write-tracking state. WRITE_WATCH_UNSPECIFIED = 0, /// Reset the write-tracking state. WRITE_WATCH_FLAG_RESET = 1 } /// /// /// Allocates physical memory pages to be mapped and unmapped within any Address Windowing Extensions (AWE) region of a specified process. /// /// /// 64-bit Windows on Itanium-based systems: Due to the difference in page sizes, AllocateUserPhysicalPages is not /// supported for 32-bit applications. /// /// /// /// A handle to a process. /// /// The function allocates memory that can later be mapped within the virtual address space of this process. The handle must have the /// PROCESS_VM_OPERATION access right. For more information, see Process Security and Access Rights. /// /// /// /// The size of the physical memory to allocate, in pages. /// /// To determine the page size of the computer, use the GetSystemInfo function. On output, this parameter receives the number /// of pages that are actually allocated, which might be less than the number requested. /// /// /// /// A pointer to an array to store the page frame numbers of the allocated memory. /// /// The size of the array that is allocated should be at least the NumberOfPages times the size of the ULONG_PTR data type. /// /// /// Do not attempt to modify this buffer. It contains operating system data, and corruption could be catastrophic. The information in /// the buffer is not useful to an application. /// /// /// /// If the function succeeds, the return value is TRUE. /// /// Fewer pages than requested can be allocated. The caller must check the value of the NumberOfPages parameter on return to see how /// many pages are allocated. All allocated page frame numbers are sequentially placed in the memory pointed to by the UserPfnArray parameter. /// /// /// If the function fails, the return value is FALSE, and no frames are allocated. To get extended error information, call GetLastError. /// /// // BOOL WINAPI AllocateUserPhysicalPages( _In_ HANDLE hProcess, _Inout_ PULONG_PTR NumberOfPages, _Out_ PULONG_PTR UserPfnArray); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366528")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool AllocateUserPhysicalPages([In] HPROCESS hProcess, ref SizeT NumberOfPages, [Out] IntPtr[] UserPfnArray); /// /// Allocates physical memory pages to be mapped and unmapped within any Address Windowing Extensions (AWE) region of a specified /// process and specifies the NUMA node for the physical memory. /// /// /// A handle to a process. /// /// The function allocates memory that can later be mapped within the virtual address space of this process. The handle must have the /// PROCESS_VM_OPERATION access right. For more information, see Process Security and Access Rights. /// /// /// /// The size of the physical memory to allocate, in pages. /// /// To determine the page size of the computer, use the GetSystemInfo function. On output, this parameter receives the number /// of pages that are actually allocated, which might be less than the number requested. /// /// /// /// A pointer to an array to store the page frame numbers of the allocated memory. /// /// The size of the array that is allocated should be at least the NumberOfPages times the size of the ULONG_PTR data type. /// /// /// The NUMA node where the physical memory should reside. /// /// If the function succeeds, the return value is TRUE. /// /// Fewer pages than requested can be allocated. The caller must check the value of the NumberOfPages parameter on return to see how /// many pages are allocated. All allocated page frame numbers are sequentially placed in the memory pointed to by the PageArray parameter. /// /// /// If the function fails, the return value is FALSE and no frames are allocated. To get extended error information, call the /// GetLastError function. /// /// // BOOL WINAPI AllocateUserPhysicalPagesNuma( _In_ HANDLE hProcess, _Inout_ PULONG_PTR NumberOfPages, _Out_ PULONG_PTR PageArray, // _In_ DWORD nndPreferred); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366529")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool AllocateUserPhysicalPagesNuma([In] HPROCESS hProcess, ref SizeT NumberOfPages, [Out] IntPtr[] PageArray, uint nndPreferred); /// /// Creates or opens a named or unnamed file mapping object for a specified file. /// To specify the NUMA node for the physical memory, see CreateFileMappingNuma. /// /// /// A handle to the file from which to create a file mapping object. /// /// The file must be opened with access rights that are compatible with the protection flags that the flProtect parameter specifies. /// It is not required, but it is recommended that files you intend to map be opened for exclusive access. For more information, see /// File Security and Access Rights. /// /// /// If hFile is INVALID_HANDLE_VALUE, the calling process must also specify a size for the file mapping object in the /// dwMaximumSizeHigh and dwMaximumSizeLow parameters. In this scenario, CreateFileMapping creates a file mapping object of a /// specified size that is backed by the system paging file instead of by a file in the file system. /// /// /// /// /// A pointer to a SECURITY_ATTRIBUTES structure that determines whether a returned handle can be inherited by child /// processes. The lpSecurityDescriptor member of the SECURITY_ATTRIBUTES structure specifies a security descriptor for /// a new file mapping object. /// /// /// If lpAttributes is NULL, the handle cannot be inherited and the file mapping object gets a default security descriptor. /// The access control lists (ACL) in the default security descriptor for a file mapping object come from the primary or /// impersonation token of the creator. For more information, see File Mapping Security and Access Rights. /// /// /// /// /// Specifies the page protection of the file mapping object. All mapped views of the object must be compatible with this protection. /// /// This parameter can be one of the following values. /// /// /// /// Value /// Meaning /// /// /// PAGE_EXECUTE_READ0x20 /// /// Allows views to be mapped for read-only, copy-on-write, or execute access.The file handle specified by the hFile parameter must /// be created with the GENERIC_READ and GENERIC_EXECUTE access rights.Windows Server 2003 and Windows XP: This value is not /// available until Windows XP with SP2 and Windows Server 2003 with SP1. /// /// /// /// PAGE_EXECUTE_READWRITE0x40 /// /// Allows views to be mapped for read-only, copy-on-write, read/write, or execute access.The file handle that the hFile parameter /// specifies must be created with the GENERIC_READ, GENERIC_WRITE, and GENERIC_EXECUTE access rights.Windows Server 2003 and Windows /// XP: This value is not available until Windows XP with SP2 and Windows Server 2003 with SP1. /// /// /// /// PAGE_EXECUTE_WRITECOPY0x80 /// /// Allows views to be mapped for read-only, copy-on-write, or execute access. This value is equivalent to PAGE_EXECUTE_READ.The file /// handle that the hFile parameter specifies must be created with the GENERIC_READ and GENERIC_EXECUTE access rights.Windows Vista: /// This value is not available until Windows Vista with SP1.Windows Server 2003 and Windows XP: This value is not supported. /// /// /// /// PAGE_READONLY0x02 /// /// Allows views to be mapped for read-only or copy-on-write access. An attempt to write to a specific region results in an access /// violation.The file handle that the hFile parameter specifies must be created with the GENERIC_READ access right. /// /// /// /// PAGE_READWRITE0x04 /// /// Allows views to be mapped for read-only, copy-on-write, or read/write access.The file handle that the hFile parameter specifies /// must be created with the GENERIC_READ and GENERIC_WRITE access rights. /// /// /// /// PAGE_WRITECOPY0x08 /// /// Allows views to be mapped for read-only or copy-on-write access. This value is equivalent to PAGE_READONLY.The file handle that /// the hFile parameter specifies must be created with the GENERIC_READ access right. /// /// /// /// /// /// An application can specify one or more of the following attributes for the file mapping object by combining them with one of the /// preceding page protection values. /// /// /// /// /// Value /// Meaning /// /// /// SEC_COMMIT0x8000000 /// /// If the file mapping object is backed by the operating system paging file (the hfile parameter is INVALID_HANDLE_VALUE), specifies /// that when a view of the file is mapped into a process address space, the entire range of pages is committed rather than reserved. /// The system must have enough committable pages to hold the entire mapping. Otherwise, CreateFileMapping fails.This attribute has /// no effect for file mapping objects that are backed by executable image files or data files (the hfile parameter is a handle to a /// file).SEC_COMMIT cannot be combined with SEC_RESERVE.If no attribute is specified, SEC_COMMIT is assumed. /// /// /// /// SEC_IMAGE0x1000000 /// /// Specifies that the file that the hFile parameter specifies is an executable image file.The SEC_IMAGE attribute must be combined /// with a page protection value such as PAGE_READONLY. However, this page protection value has no effect on views of the executable /// image file. Page protection for views of an executable image file is determined by the executable file itself.No other attributes /// are valid with SEC_IMAGE. /// /// /// /// SEC_IMAGE_NO_EXECUTE0x11000000 /// /// Specifies that the file that the hFile parameter specifies is an executable image file that will not be executed and the loaded /// image file will have no forced integrity checks run. Additionally, mapping a view of a file mapping object created with the /// SEC_IMAGE_NO_EXECUTE attribute will not invoke driver callbacks registered using the PsSetLoadImageNotifyRoutine kernel API.The /// SEC_IMAGE_NO_EXECUTE attribute must be combined with the PAGE_READONLY page protection value. No other attributes are valid with /// SEC_IMAGE_NO_EXECUTE.Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003 and Windows XP: /// This value is not supported before Windows Server 2012 and Windows 8. /// /// /// /// SEC_LARGE_PAGES0x80000000 /// /// Enables large pages to be used for file mapping objects that are backed by the operating system paging file (the hfile parameter /// is INVALID_HANDLE_VALUE). This attribute is not supported for file mapping objects that are backed by executable image files or /// data files (the hFile parameter is a handle to an executable image or data file).The maximum size of the file mapping object must /// be a multiple of the minimum size of a large page returned by the GetLargePageMinimum function. If it is not, CreateFileMapping /// fails. When mapping a view of a file mapping object created with SEC_LARGE_PAGES, the base address and view size must also be /// multiples of the minimum large page size.SEC_LARGE_PAGES requires the SeLockMemoryPrivilege privilege to be enabled in the /// caller's token.If SEC_LARGE_PAGES is specified, SEC_COMMIT must also be specified.Windows Server 2003: This value is not /// supported until Windows Server 2003 with SP1.Windows XP: This value is not supported. /// /// /// /// SEC_NOCACHE0x10000000 /// /// Sets all pages to be non-cachable.Applications should not use this attribute except when explicitly required for a device. Using /// the interlocked functions with memory that is mapped with SEC_NOCACHE can result in an EXCEPTION_ILLEGAL_INSTRUCTION /// exception.SEC_NOCACHE requires either the SEC_RESERVE or SEC_COMMIT attribute to be set. /// /// /// /// SEC_RESERVE0x4000000 /// /// If the file mapping object is backed by the operating system paging file (the hfile parameter is INVALID_HANDLE_VALUE), specifies /// that when a view of the file is mapped into a process address space, the entire range of pages is reserved for later use by the /// process rather than committed.Reserved pages can be committed in subsequent calls to the VirtualAlloc function. After the pages /// are committed, they cannot be freed or decommitted with the VirtualFree function.This attribute has no effect for file mapping /// objects that are backed by executable image files or data files (the hfile parameter is a handle to a file).SEC_RESERVE cannot be /// combined with SEC_COMMIT. /// /// /// /// SEC_WRITECOMBINE0x40000000 /// /// Sets all pages to be write-combined.Applications should not use this attribute except when explicitly required for a device. /// Using the interlocked functions with memory that is mapped with SEC_WRITECOMBINE can result in an EXCEPTION_ILLEGAL_INSTRUCTION /// exception.SEC_WRITECOMBINE requires either the SEC_RESERVE or SEC_COMMIT attribute to be set.Windows Server 2003 and Windows XP: /// This flag is not supported until Windows Vista. /// /// /// /// /// /// The high-order DWORD of the maximum size of the file mapping object. /// /// The low-order DWORD of the maximum size of the file mapping object. /// /// If this parameter and dwMaximumSizeHigh are 0 (zero), the maximum size of the file mapping object is equal to the current size of /// the file that hFile identifies. /// /// /// An attempt to map a file with a length of 0 (zero) fails with an error code of ERROR_FILE_INVALID. Applications should /// test for files with a length of 0 (zero) and reject those files. /// /// /// /// The name of the file mapping object. /// /// If this parameter matches the name of an existing mapping object, the function requests access to the object with the protection /// that flProtect specifies. /// /// If this parameter is NULL, the file mapping object is created without a name. /// /// If lpName matches the name of an existing event, semaphore, mutex, waitable timer, or job object, the function fails, and the /// GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same namespace. /// /// /// The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session namespace. The /// remainder of the name can contain any character except the backslash character (\). Creating a file mapping object in the global /// namespace from a session other than session zero requires the SeCreateGlobalPrivilege privilege. For more information, see Kernel /// Object Namespaces. /// /// /// Fast user switching is implemented by using Terminal Services sessions. The first user to log on uses session 0 (zero), the next /// user to log on uses session 1 (one), and so on. Kernel object names must follow the guidelines that are outlined for Terminal /// Services so that applications can support multiple users. /// /// /// /// If the function succeeds, the return value is a handle to the newly created file mapping object. /// /// If the object exists before the function call, the function returns a handle to the existing object (with its current size, not /// the specified size), and GetLastError returns ERROR_ALREADY_EXISTS. /// /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// // HANDLE WINAPI CreateFileMapping( _In_ HANDLE hFile, _In_opt_ LPSECURITY_ATTRIBUTES lpAttributes, _In_ DWORD flProtect, _In_ DWORD // dwMaximumSizeHigh, _In_ DWORD dwMaximumSizeLow, _In_opt_ LPCTSTR lpName); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("WinBase.h", MSDNShortId = "aa366537")] public static extern SafeHSECTION CreateFileMapping([In] HFILE hFile, [In, Optional] SECURITY_ATTRIBUTES lpAttributes, MEM_PROTECTION flProtect, [Optional] uint dwMaximumSizeHigh, [Optional] uint dwMaximumSizeLow, [Optional] string lpName); /// Creates or opens a named or unnamed file mapping object for a specified file from a Windows Store app. /// /// A handle to the file from which to create a file mapping object. /// /// The file must be opened with access rights that are compatible with the protection flags that the flProtect parameter specifies. /// It is not required, but it is recommended that files you intend to map be opened for exclusive access. For more information, see /// File Security and Access Rights. /// /// /// If hFile is INVALID_HANDLE_VALUE, the calling process must also specify a size for the file mapping object in the /// dwMaximumSizeHigh and dwMaximumSizeLow parameters. In this scenario, CreateFileMappingFromApp creates a file mapping /// object of a specified size that is backed by the system paging file instead of by a file in the file system. /// /// /// /// /// A pointer to a SECURITY_ATTRIBUTES structure that determines whether a returned handle can be inherited by child /// processes. The lpSecurityDescriptor member of the SECURITY_ATTRIBUTES structure specifies a security descriptor for /// a new file mapping object. /// /// /// If SecurityAttributes is NULL, the handle cannot be inherited and the file mapping object gets a default security /// descriptor. The access control lists (ACL) in the default security descriptor for a file mapping object come from the primary or /// impersonation token of the creator. For more information, see File Mapping Security and Access Rights. /// /// /// /// /// Specifies the page protection of the file mapping object. All mapped views of the object must be compatible with this protection. /// /// This parameter can be one of the following values. /// /// /// /// Value /// Meaning /// /// /// PAGE_READONLY0x02 /// /// Allows views to be mapped for read-only or copy-on-write access. An attempt to write to a specific region results in an access /// violation.The file handle that the hFile parameter specifies must be created with the GENERIC_READ access right. /// /// /// /// PAGE_READWRITE0x04 /// /// Allows views to be mapped for read-only, copy-on-write, or read/write access.The file handle that the hFile parameter specifies /// must be created with the GENERIC_READ and GENERIC_WRITE access rights. /// /// /// /// PAGE_WRITECOPY0x08 /// /// Allows views to be mapped for read-only or copy-on-write access. This value is equivalent to PAGE_READONLY.The file handle that /// the hFile parameter specifies must be created with the GENERIC_READ access right. /// /// /// /// /// /// An application can specify one or more of the following attributes for the file mapping object by combining them with one of the /// preceding page protection values. /// /// /// /// /// Value /// Meaning /// /// /// SEC_COMMIT0x8000000 /// /// If the file mapping object is backed by the operating system paging file (the hfile parameter is INVALID_HANDLE_VALUE), specifies /// that when a view of the file is mapped into a process address space, the entire range of pages is committed rather than reserved. /// The system must have enough committable pages to hold the entire mapping. Otherwise, CreateFileMappingFromApp fails.This /// attribute has no effect for file mapping objects that are backed by executable image files or data files (the hfile parameter is /// a handle to a file).SEC_COMMIT cannot be combined with SEC_RESERVE.If no attribute is specified, SEC_COMMIT is assumed. /// /// /// /// SEC_IMAGE_NO_EXECUTE0x11000000 /// /// Specifies that the file that the hFile parameter specifies is an executable image file that will not be executed and the loaded /// image file will have no forced integrity checks run. Additionally, mapping a view of a file mapping object created with the /// SEC_IMAGE_NO_EXECUTE attribute will not invoke driver callbacks registered using the PsSetLoadImageNotifyRoutine kernel API.The /// SEC_IMAGE_NO_EXECUTE attribute must be combined with the PAGE_READONLY page protection value. No other attributes are valid with SEC_IMAGE_NO_EXECUTE. /// /// /// /// SEC_LARGE_PAGES0x80000000 /// /// Enables large pages to be used for file mapping objects that are backed by the operating system paging file (the hfile parameter /// is INVALID_HANDLE_VALUE). This attribute is not supported for file mapping objects that are backed by executable image files or /// data files (the hFile parameter is a handle to an executable image or data file).The maximum size of the file mapping object must /// be a multiple of the minimum size of a large page returned by the GetLargePageMinimum function. If it is not, /// CreateFileMappingFromApp fails. When mapping a view of a file mapping object created with SEC_LARGE_PAGES, the base address and /// view size must also be multiples of the minimum large page size.SEC_LARGE_PAGES requires the SeLockMemoryPrivilege privilege to /// be enabled in the caller's token.If SEC_LARGE_PAGES is specified, SEC_COMMIT must also be specified. /// /// /// /// SEC_NOCACHE0x10000000 /// /// Sets all pages to be non-cachable.Applications should not use this attribute except when explicitly required for a device. Using /// the interlocked functions with memory that is mapped with SEC_NOCACHE can result in an EXCEPTION_ILLEGAL_INSTRUCTION /// exception.SEC_NOCACHE requires either the SEC_RESERVE or SEC_COMMIT attribute to be set. /// /// /// /// SEC_RESERVE0x4000000 /// /// If the file mapping object is backed by the operating system paging file (the hfile parameter is INVALID_HANDLE_VALUE), specifies /// that when a view of the file is mapped into a process address space, the entire range of pages is reserved for later use by the /// process rather than committed.Reserved pages can be committed in subsequent calls to the VirtualAlloc function. After the pages /// are committed, they cannot be freed or decommitted with the VirtualFree function.This attribute has no effect for file mapping /// objects that are backed by executable image files or data files (the hfile parameter is a handle to a file).SEC_RESERVE cannot be /// combined with SEC_COMMIT. /// /// /// /// SEC_WRITECOMBINE0x40000000 /// /// Sets all pages to be write-combined.Applications should not use this attribute except when explicitly required for a device. /// Using the interlocked functions with memory that is mapped with SEC_WRITECOMBINE can result in an EXCEPTION_ILLEGAL_INSTRUCTION /// exception.SEC_WRITECOMBINE requires either the SEC_RESERVE or SEC_COMMIT attribute to be set. /// /// /// /// /// /// /// The maximum size of the file mapping object. /// /// An attempt to map a file with a length of 0 (zero) fails with an error code of ERROR_FILE_INVALID. Applications should /// test for files with a length of 0 (zero) and reject those files. /// /// /// /// The name of the file mapping object. /// /// If this parameter matches the name of an existing mapping object, the function requests access to the object with the protection /// that flProtect specifies. /// /// If this parameter is NULL, the file mapping object is created without a name. /// /// If lpName matches the name of an existing event, semaphore, mutex, waitable timer, or job object, the function fails, and the /// GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same namespace. /// /// /// The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session namespace. The /// remainder of the name can contain any character except the backslash character (\). Creating a file mapping object in the global /// namespace from a session other than session zero requires the SeCreateGlobalPrivilege privilege. For more information, see Kernel /// Object Namespaces. /// /// /// Fast user switching is implemented by using Terminal Services sessions. The first user to log on uses session 0 (zero), the next /// user to log on uses session 1 (one), and so on. Kernel object names must follow the guidelines that are outlined for Terminal /// Services so that applications can support multiple users. /// /// /// /// If the function succeeds, the return value is a handle to the newly created file mapping object. /// /// If the object exists before the function call, the function returns a handle to the existing object (with its current size, not /// the specified size), and GetLastError returns ERROR_ALREADY_EXISTS. /// /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// // HANDLE WINAPI CreateFileMappingFromApp( _In_ HANDLE hFile, _In_opt_ PSECURITY_ATTRIBUTES SecurityAttributes, _In_ ULONG // PageProtection, _In_ ULONG64 MaximumSize, _In_opt_ PCWSTR Name); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)] [PInvokeData("MemoryApi.h", MSDNShortId = "hh994453")] public static extern SafeHSECTION CreateFileMappingFromApp([In] HFILE hFile, [In, Optional] SECURITY_ATTRIBUTES SecurityAttributes, MEM_PROTECTION PageProtection, ulong MaximumSize, [Optional] string Name); /// /// Creates or opens a named or unnamed file mapping object for a specified file and specifies the NUMA node for the physical memory. /// /// /// A handle to the file from which to create a file mapping object. /// /// The file must be opened with access rights that are compatible with the protection flags that the flProtect parameter specifies. /// It is not required, but it is recommended that files you intend to map be opened for exclusive access. For more information, see /// File Security and Access Rights. /// /// /// If hFile is INVALID_HANDLE_VALUE, the calling process must also specify a size for the file mapping object in the /// dwMaximumSizeHigh and dwMaximumSizeLow parameters. In this scenario, CreateFileMappingNuma creates a file mapping object /// of a specified size that is backed by the system paging file instead of by a file in the file system. /// /// /// /// /// A pointer to a SECURITY_ATTRIBUTES structure that determines whether a returned handle can be inherited by child /// processes. The lpSecurityDescriptor member of the SECURITY_ATTRIBUTES structure specifies a security descriptor for /// a new file mapping object. /// /// /// If lpFileMappingAttributes is NULL, the handle cannot be inherited and the file mapping object gets a default security /// descriptor. The access control lists (ACL) in the default security descriptor for a file mapping object come from the primary or /// impersonation token of the creator. For more information, see File Mapping Security and Access Rights. /// /// /// /// /// Specifies the page protection of the file mapping object. All mapped views of the object must be compatible with this protection. /// /// This parameter can be one of the following values. /// /// /// /// Value /// Meaning /// /// /// PAGE_EXECUTE_READ0x20 /// /// Allows views to be mapped for read-only, copy-on-write, or execute access.The file handle that the hFile parameter specifies must /// be created with the GENERIC_READ and GENERIC_EXECUTE access rights. /// /// /// /// PAGE_EXECUTE_READWRITE0x40 /// /// Allows views to be mapped for read-only, copy-on-write, read/write or execute access.The file handle that the hFile parameter /// specifies must be created with the GENERIC_READ, GENERIC_WRITE, and GENERIC_EXECUTE access rights. /// /// /// /// PAGE_EXECUTE_WRITECOPY0x80 /// /// Allows views to be mapped for read-only, copy-on-write, or execute access. This value is equivalent to PAGE_EXECUTE_READ.The file /// handle that the hFile parameter specifies must be created with the GENERIC_READ and GENERIC_EXECUTE access rights.Windows Vista: /// This value is not available until Windows Vista with SP1. /// /// /// /// PAGE_READONLY0x02 /// /// Allows views to be mapped for read-only or copy-on-write access. An attempt to write to a specific region results in an access /// violation.The file handle that the hFile parameter specifies must be created with the GENERIC_READ access right. /// /// /// /// PAGE_READWRITE0x04 /// /// Allows views to be mapped for read-only, copy-on-write, or read/write access.The file handle that the hFile parameter specifies /// must be created with the GENERIC_READ and GENERIC_WRITE access rights. /// /// /// /// PAGE_WRITECOPY0x08 /// /// Allows views to be mapped for read-only or copy-on-write access. This value is equivalent to PAGE_READONLY.The file handle that /// the hFile parameter specifies must be created with the GENERIC_READ access right. /// /// /// /// /// /// An application can specify one or more of the following attributes for the file mapping object by combining them with one of the /// preceding page protection values. /// /// /// /// /// Value /// Meaning /// /// /// SEC_COMMIT0x8000000 /// Allocates physical storage in memory or the paging file for all pages. This is the default setting. /// /// /// SEC_IMAGE0x1000000 /// /// Sets the file that is specified to be an executable image file.The SEC_IMAGE attribute must be combined with a page protection /// value such as PAGE_READONLY. However, this page protection value has no effect on views of the executable image file. Page /// protection for views of an executable image file is determined by the executable file itself.No other attributes are valid with SEC_IMAGE. /// /// /// /// SEC_IMAGE_NO_EXECUTE0x11000000 /// /// Specifies that the file that the hFile parameter specifies is an executable image file that will not be executed and the loaded /// image file will have no forced integrity checks run. Additionally, mapping a view of a file mapping object created with the /// SEC_IMAGE_NO_EXECUTE attribute will not invoke driver callbacks registered using the PsSetLoadImageNotifyRoutine kernel API.The /// SEC_IMAGE_NO_EXECUTE attribute must be combined with the PAGE_READONLY page protection value. No other attributes are valid with /// SEC_IMAGE_NO_EXECUTE.Windows Server 2008 R2, Windows 7, Windows Server 2008 and Windows Vista: This value is not supported before /// Windows Server 2012 and Windows 8. /// /// /// /// SEC_LARGE_PAGES0x80000000 /// /// Enables large pages to be used when mapping images or backing from the pagefile, but not when mapping data for regular files. Be /// sure to specify the maximum size of the file mapping object as the minimum size of a large page reported by the /// GetLargePageMinimum function and to enable the SeLockMemoryPrivilege privilege. /// /// /// /// SEC_NOCACHE0x10000000 /// /// Sets all pages to noncachable.Applications should not use this flag except when explicitly required for a device. Using the /// interlocked functions with memory mapped with SEC_NOCACHE can result in an EXCEPTION_ILLEGAL_INSTRUCTION exception.SEC_NOCACHE /// requires either SEC_RESERVE or SEC_COMMIT to be set. /// /// /// /// SEC_RESERVE0x4000000 /// /// Reserves all pages without allocating physical storage.The reserved range of pages cannot be used by any other allocation /// operations until the range of pages is released.Reserved pages can be identified in subsequent calls to the VirtualAllocExNuma /// function. This attribute is valid only if the hFile parameter is INVALID_HANDLE_VALUE (that is, a file mapping object that is /// backed by the system paging file). /// /// /// /// SEC_WRITECOMBINE0x40000000 /// /// Sets all pages to be write-combined.Applications should not use this attribute except when explicitly required for a device. /// Using the interlocked functions with memory that is mapped with SEC_WRITECOMBINE can result in an EXCEPTION_ILLEGAL_INSTRUCTION /// exception.SEC_WRITECOMBINE requires either the SEC_RESERVE or SEC_COMMIT attribute to be set. /// /// /// /// /// /// The high-order DWORD of the maximum size of the file mapping object. /// /// The low-order DWORD of the maximum size of the file mapping object. /// /// If this parameter and the dwMaximumSizeHigh parameter are 0 (zero), the maximum size of the file mapping object is equal to the /// current size of the file that the hFile parameter identifies. /// /// /// An attempt to map a file with a length of 0 (zero) fails with an error code of ERROR_FILE_INVALID. Applications should /// test for files with a length of 0 (zero) and reject those files. /// /// /// /// The name of the file mapping object. /// /// If this parameter matches the name of an existing file mapping object, the function requests access to the object with the /// protection that the flProtect parameter specifies. /// /// If this parameter is NULL, the file mapping object is created without a name. /// /// If the lpName parameter matches the name of an existing event, semaphore, mutex, waitable timer, or job object, the function /// fails and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same namespace. /// /// /// The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session namespace. The /// remainder of the name can contain any character except the backslash character (\). Creating a file mapping object in the global /// namespace requires the SeCreateGlobalPrivilege privilege. For more information, see Kernel Object Namespaces. /// /// /// Fast user switching is implemented by using Terminal Services sessions. The first user to log on uses session 0 (zero), the next /// user to log on uses session 1 (one), and so on. Kernel object names must follow the guidelines so that applications can support /// multiple users. /// /// /// /// The NUMA node where the physical memory should reside. /// /// /// /// Value /// Meaning /// /// /// NUMA_NO_PREFERRED_NODE = 0xffffffff /// No NUMA node is preferred. This is the same as calling the CreateFileMapping function. /// /// /// /// /// /// If the function succeeds, the return value is a handle to the file mapping object. /// /// If the object exists before the function call, the function returns a handle to the existing object (with its current size, not /// the specified size) and the GetLastError function returns ERROR_ALREADY_EXISTS. /// /// /// If the function fails, the return value is NULL. To get extended error information, call the GetLastError function. /// /// // HANDLE WINAPI CreateFileMappingNuma( _In_ HANDLE hFile, _In_opt_ LPSECURITY_ATTRIBUTES lpFileMappingAttributes, _In_ DWORD // flProtect, _In_ DWORD dwMaximumSizeHigh, _In_ DWORD dwMaximumSizeLow, _In_opt_ LPCTSTR lpName, _In_ DWORD nndPreferred); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("WinBase.h", MSDNShortId = "aa366539")] public static extern SafeHSECTION CreateFileMappingNuma([In] HFILE hFile, [In, Optional] SECURITY_ATTRIBUTES lpFileMappingAttributes, MEM_PROTECTION flProtect, [Optional] uint dwMaximumSizeHigh, [Optional] uint dwMaximumSizeLow, [Optional] string lpName, uint nndPreferred); /// /// Creates a memory resource notification object. /// /// /// /// The memory condition under which the object is to be signaled. This parameter can be one of the following values from the /// MEMORY_RESOURCE_NOTIFICATION_TYPE enumeration. /// /// /// /// /// Value /// Meaning /// /// /// LowMemoryResourceNotification0 /// Available physical memory is running low. /// /// /// HighMemoryResourceNotification1 /// Available physical memory is high. /// /// /// /// /// /// If the function succeeds, the return value is a handle to a memory resource notification object. /// If the function fails, the return value is NULL. To get extended information, call GetLastError. /// // HANDLE WINAPI CreateMemoryResourceNotification( _In_ MEMORY_RESOURCE_NOTIFICATION_TYPE NotificationType); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366541")] public static extern SafeMemoryResourceNotification CreateMemoryResourceNotification(MEMORY_RESOURCE_NOTIFICATION_TYPE NotificationType); /// /// Discards the memory contents of a range of memory pages, without decommitting the memory. The contents of discarded memory is /// undefined and must be rewritten by the application. /// /// Page-aligned starting address of the memory to discard. /// Size, in bytes, of the memory region to discard. Size must be an integer multiple of the system page size. /// ERROR_SUCCESS if successful; a System Error Code otherwise. // DWORD WINAPI DiscardVirtualMemory( _In_ PVOID VirtualAddress, _In_ SIZE_T Size); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dn781432")] public static extern uint DiscardVirtualMemory(IntPtr VirtualAddress, SizeT Size); /// Fills a block of memory with a specified value. /// A pointer to the starting address of the block of memory to fill. /// /// The size of the block of memory to fill, in bytes. This value must be less than the size of the Destination buffer. /// /// The byte value with which to fill the memory block. // void FillMemory( [out] PVOID Destination, [in] SIZE_T Length, [in] BYTE Fill); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366561(v=vs.85).aspx [PInvokeData("WinBase.h", MSDNShortId = "aa366561")] [DllImport(Lib.Kernel32, EntryPoint = "RtlFillMemory", SetLastError = false)] public static extern void FillMemory(IntPtr Destination, SizeT Length, byte Fill); /// Writes to the disk a byte range within a mapped view of a file. /// /// A pointer to the base address of the byte range to be flushed to the disk representation of the mapped file. /// /// /// The number of bytes to be flushed. If dwNumberOfBytesToFlush is zero, the file is flushed from the base address to the end of the mapping. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI FlushViewOfFile( _In_ LPCVOID lpBaseAddress, _In_ SIZE_T dwNumberOfBytesToFlush); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366563")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FlushViewOfFile([In] IntPtr lpBaseAddress, SizeT dwNumberOfBytesToFlush); /// /// /// Frees physical memory pages that are allocated previously by using AllocateUserPhysicalPages or /// AllocateUserPhysicalPagesNuma. If any of these pages are currently mapped in the Address Windowing Extensions (AWE) /// region, they are automatically unmapped by this call. This does not affect the virtual address space that is occupied by a /// specified Address Windowing Extensions (AWE) region. /// /// /// 64-bit Windows on Itanium-based systems: Due to the difference in page sizes, FreeUserPhysicalPages is not /// supported for 32-bit applications. /// /// /// /// The handle to a process. /// The function frees memory within the virtual address space of this process. /// /// /// The size of the physical memory to free, in pages. /// On return, if the function fails, this parameter indicates the number of pages that are freed. /// /// A pointer to an array of page frame numbers of the allocated memory to be freed. /// /// If the function succeeds, the return value is TRUE. /// /// If the function fails, the return value is FALSE. In this case, the NumberOfPages parameter reflect how many pages have /// actually been released. To get extended error information, call GetLastError. /// /// // BOOL WINAPI FreeUserPhysicalPages( _In_ HANDLE hProcess, _Inout_ PULONG_PTR NumberOfPages, _In_ PULONG_PTR UserPfnArray); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366566")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FreeUserPhysicalPages([In] HPROCESS hProcess, ref SizeT NumberOfPages, [In] IntPtr[] UserPfnArray); /// Retrieves the minimum size of a large page. /// /// If the processor supports large pages, the return value is the minimum size of a large page. /// If the processor does not support large pages, the return value is zero. /// // SIZE_T WINAPI GetLargePageMinimum(void); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366568")] public static extern SizeT GetLargePageMinimum(); /// Gets the memory error handling capabilities of the system. /// /// A PULONG that receives one or more of the following flags. /// /// /// /// Value /// Meaning /// /// /// MEHC_PATROL_SCRUBBER_PRESENT = 1 /// The hardware can detect and report failed memory. /// /// /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI GetMemoryErrorHandlingCapabilities( _Out_ PULONG Capabilities); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "hh691012")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetMemoryErrorHandlingCapabilities(out uint Capabilities); /// Retrieves the minimum and maximum working set sizes of the specified process. /// /// /// A handle to the process whose working set sizes will be obtained. The handle must have the PROCESS_QUERY_INFORMATION or /// PROCESS_QUERY_LIMITED_INFORMATION access right. For more information, see Process Security and Access Rights. /// /// Windows Server 2003 and Windows XP: The handle must have the PROCESS_QUERY_INFORMATION access right. /// /// /// A pointer to a variable that receives the minimum working set size of the specified process, in bytes. The virtual memory manager /// attempts to keep at least this much memory resident in the process whenever the process is active. /// /// /// A pointer to a variable that receives the maximum working set size of the specified process, in bytes. The virtual memory manager /// attempts to keep no more than this much memory resident in the process whenever the process is active when memory is in short supply. /// /// The flags that control the enforcement of the minimum and maximum working set sizes. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI GetProcessWorkingSetSize( _In_ HANDLE hProcess, _Out_ PSIZE_T lpMinimumWorkingSetSize, _Out_ PSIZE_T lpMaximumWorkingSetSize); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms683226")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetProcessWorkingSetSizeEx([In] HPROCESS hProcess, [Out] out SizeT lpMinimumWorkingSetSize, [Out] out SizeT lpMaximumWorkingSetSize, out QUOTA_LIMITS_HARDWS Flags); /// Retrieves the current size limits for the working set of the system cache. /// /// A pointer to a variable that receives the minimum size of the file cache, in bytes. The virtual memory manager attempts to keep /// at least this much memory resident in the system file cache, if there is a previous call to the SetSystemFileCacheSize /// function with the FILE_CACHE_MIN_HARD_ENABLE flag. /// /// /// A pointer to a variable that receives the maximum size of the file cache, in bytes. The virtual memory manager enforces this /// limit only if there is a previous call to SetSystemFileCacheSize with the FILE_CACHE_MAX_HARD_ENABLE flag. /// /// /// The flags that indicate which of the file cache limits are enabled. /// /// /// /// Value /// Meaning /// /// /// FILE_CACHE_MAX_HARD_ENABLE = 0x1 /// The maximum size limit is enabled. If this flag is not present, this limit is disabled. /// /// /// FILE_CACHE_MIN_HARD_ENABLE = 0x4 /// The minimum size limit is enabled. If this flag is not present, this limit is disabled. /// /// /// /// /// /// If the function succeeds, the return value is a nonzero value. /// If the function fails, the return value is 0 (zero). To get extended error information, call GetLastError. /// // BOOL WINAPI GetSystemFileCacheSize( _Out_ PSIZE_T lpMinimumFileCacheSize, _Out_ PSIZE_T lpMaximumFileCacheSize, _Out_ PDWORD lpFlags); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa965224")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetSystemFileCacheSize(out SizeT lpMinimumFileCacheSize, out SizeT lpMaximumFileCacheSize, out FILE_CACHE_LIMITS lpFlags); /// /// Retrieves the addresses of the pages that are written to in a region of virtual memory. /// /// 64-bit Windows on Itanium-based systems: Due to the difference in page sizes, GetWriteWatch is not supported for /// 32-bit applications. /// /// /// /// Indicates whether the function resets the write-tracking state. /// /// To reset the write-tracking state, set this parameter to WRITE_WATCH_FLAG_RESET. If this parameter is 0 (zero), /// GetWriteWatch does not reset the write-tracking state. For more information, see the Remarks section of this topic. /// /// /// /// The base address of the memory region for which to retrieve write-tracking information. /// This address must be in a memory region that is allocated by the VirtualAlloc function using MEM_WRITE_WATCH. /// /// The size of the memory region for which to retrieve write-tracking information, in bytes. /// /// A pointer to a buffer that receives an array of page addresses in the memory region. /// /// The addresses indicate the pages that have been written to since the region has been allocated or the write-tracking state has /// been reset. /// /// /// /// On input, this variable indicates the size of the lpAddresses array, in array elements. /// On output, the variable receives the number of page addresses that are returned in the array. /// /// A pointer to a variable that receives the page size, in bytes. /// /// If the function succeeds, the return value is 0 (zero). /// If the function fails, the return value is a nonzero value. /// // UINT WINAPI GetWriteWatch( _In_ DWORD dwFlags, _In_ PVOID lpBaseAddress, _In_ SIZE_T dwRegionSize, _Out_ PVOID *lpAddresses, // _Inout_ PULONG_PTR lpdwCount, _Out_ PULONG lpdwGranularity); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366573")] public static extern uint GetWriteWatch(WRITE_WATCH dwFlags, [In] IntPtr lpBaseAddress, SizeT dwRegionSize, out IntPtr lpAddresses, ref UIntPtr lpdwCount, [Out] out uint lpdwGranularity); /// /// Maps previously allocated physical memory pages at a specified address in an Address Windowing Extensions (AWE) region. /// To perform batch mapping and unmapping of multiple regions, use the MapUserPhysicalPagesScatter function. /// /// 64-bit Windows on Itanium-based systems: Due to the difference in page sizes, MapUserPhysicalPages is not supported /// for 32-bit applications. /// /// /// /// A pointer to the starting address of the region of memory to remap. /// /// The value of lpAddress must be within the address range that the VirtualAlloc function returns when the Address Windowing /// Extensions (AWE) region is allocated. /// /// /// /// The size of the physical memory and virtual address space for which to establish translations, in pages. /// The virtual address range is contiguous starting at lpAddress. The physical frames are specified by the UserPfnArray. /// The total number of pages cannot extend from the starting address beyond the end of the range that is specified in AllocateUserPhysicalPages. /// /// /// A pointer to an array of physical page frame numbers. /// /// These frames are mapped by the argument lpAddress on return from this function. The size of the memory that is allocated should /// be at least the NumberOfPages times the size of the data type ULONG_PTR. /// /// /// Do not attempt to modify this buffer. It contains operating system data, and corruption could be catastrophic. The information in /// the buffer is not useful to an application. /// /// /// If this parameter is NULL, the specified address range is unmapped. Also, the specified physical pages are not freed, and /// you must call FreeUserPhysicalPages to free them. /// /// /// /// If the function succeeds, the return value is TRUE. /// /// If the function fails, the return value is FALSE and no mapping is done—partial or otherwise. To get extended error /// information, call GetLastError. /// /// // BOOL WINAPI MapUserPhysicalPages( _In_ PVOID lpAddress, _In_ ULONG_PTR NumberOfPages, _In_ PULONG_PTR UserPfnArray); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366753")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool MapUserPhysicalPages([In] IntPtr lpAddress, SizeT NumberOfPages, [In] IntPtr[] UserPfnArray); /// /// Maps previously allocated physical memory pages at a specified address in an Address Windowing Extensions (AWE) region. /// /// 64-bit Windows on Itanium-based systems: Due to the difference in page sizes, MapUserPhysicalPagesScatter is not /// supported for 32-bit applications. /// /// /// /// A pointer to an array of starting addresses of the regions of memory to remap. /// /// Each entry in VirtualAddresses must be within the address range that the VirtualAlloc function returns when the Address /// Windowing Extensions (AWE) region is allocated. The value in NumberOfPages indicates the size of the array. Entries can be from /// multiple Address Windowing Extensions (AWE) regions. /// /// /// /// The size of the physical memory and virtual address space for which to establish translations, in pages. /// The array at VirtualAddresses specifies the virtual address range. /// /// /// A pointer to an array of values that indicates how each corresponding page in VirtualAddresses should be treated. /// /// A 0 (zero) indicates that the corresponding entry in VirtualAddresses should be unmapped, and any nonzero value that it has /// should be mapped. /// /// If this parameter is NULL, then every address in the VirtualAddresses array is unmapped. /// The value in NumberOfPages indicates the size of the array. /// /// /// If the function succeeds, the return value is TRUE. /// /// If the function fails, the return value is FALSE, and the function does not map or unmap—partial or otherwise. To get /// extended error information, call GetLastError. /// /// // BOOL WINAPI MapUserPhysicalPagesScatter( _In_ PVOID *VirtualAddresses, _In_ ULONG_PTR NumberOfPages, _In_ PULONG_PTR PageArray); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366755(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366755")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool MapUserPhysicalPagesScatter([In] IntPtr VirtualAddresses, SizeT NumberOfPages, [In] IntPtr[] PageArray); /// /// Maps a view of a file mapping into the address space of a calling process. /// /// To specify a suggested base address for the view, use the MapViewOfFileEx function. However, this practice is not recommended. /// /// /// /// A handle to a file mapping object. The CreateFileMapping and OpenFileMapping functions return this handle. /// /// /// /// The type of access to a file mapping object, which determines the protection of the pages. This parameter can be one of the /// following values. /// /// /// /// /// Value /// Meaning /// /// /// FILE_MAP_ALL_ACCESS /// /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or /// PAGE_EXECUTE_READWRITE protection.When used with the MapViewOfFile function, FILE_MAP_ALL_ACCESS is equivalent to FILE_MAP_WRITE. /// /// /// /// FILE_MAP_COPY /// /// A copy-on-write view of the file is mapped. The file mapping object must have been created with PAGE_READONLY, PAGE_READ_EXECUTE, /// PAGE_WRITECOPY, PAGE_EXECUTE_WRITECOPY, PAGE_READWRITE, or PAGE_EXECUTE_READWRITE protection.When a process writes to a /// copy-on-write page, the system copies the original page to a new page that is private to the process. The new page is backed by /// the paging file. The protection of the new page changes from copy-on-write to read/write.When copy-on-write access is specified, /// the system and process commit charge taken is for the entire view because the calling process can potentially write to every page /// in the view, making all pages private. The contents of the new page are never written back to the original file and are lost when /// the view is unmapped. /// /// /// /// FILE_MAP_READ /// /// A read-only view of the file is mapped. An attempt to write to the file view results in an access violation.The file mapping /// object must have been created with PAGE_READONLY, PAGE_READWRITE, PAGE_EXECUTE_READ, or PAGE_EXECUTE_READWRITE protection. /// /// /// /// FILE_MAP_WRITE /// /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or /// PAGE_EXECUTE_READWRITE protection.When used with MapViewOfFile, (FILE_MAP_WRITE | FILE_MAP_READ) and FILE_MAP_ALL_ACCESS are /// equivalent to FILE_MAP_WRITE. /// /// /// /// /// Each of the preceding values can be combined with the following value. /// /// /// /// Value /// Meaning /// /// /// FILE_MAP_EXECUTE /// /// An executable view of the file is mapped (mapped memory can be run as code). The file mapping object must have been created with /// PAGE_EXECUTE_READ, PAGE_EXECUTE_WRITECOPY, or PAGE_EXECUTE_READWRITE protection.Windows Server 2003 and Windows XP: This value is /// available starting with Windows XP with SP2 and Windows Server 2003 with SP1. /// /// /// /// /// /// For file mapping objects created with the SEC_IMAGE attribute, the dwDesiredAccess parameter has no effect and should be /// set to any valid value such as FILE_MAP_READ. /// /// For more information about access to file mapping objects, see File Mapping Security and Access Rights. /// /// A high-order DWORD of the file offset where the view begins. /// /// A low-order DWORD of the file offset where the view is to begin. The combination of the high and low offsets must specify /// an offset within the file mapping. They must also match the memory allocation granularity of the system. That is, the offset must /// be a multiple of the allocation granularity. To obtain the memory allocation granularity of the system, use the /// GetSystemInfo function, which fills in the members of a SYSTEM_INFO structure. /// /// /// The number of bytes of a file mapping to map to the view. All bytes must be within the maximum size specified by /// CreateFileMapping. If this parameter is 0 (zero), the mapping extends from the specified offset to the end of the file mapping. /// /// /// If the function succeeds, the return value is the starting address of the mapped view. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// // LPVOID WINAPI MapViewOfFile( _In_ HANDLE hFileMappingObject, _In_ DWORD dwDesiredAccess, _In_ DWORD dwFileOffsetHigh, _In_ DWORD // dwFileOffsetLow, _In_ SIZE_T dwNumberOfBytesToMap); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366761")] public static extern IntPtr MapViewOfFile([In] HSECTION hFileMappingObject, FILE_MAP dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap); /// /// Maps a view of a file or a pagefile-backed section into the address space of the specified process. /// /// Using this function, you can: for new allocations, specify a range of virtual address space and a power-of-2 alignment /// restriction; specify an arbitrary number of extended parameters; specify a preferred NUMA node for the physical memory as an /// extended parameter; and specify a placeholder operation (specifically, replacement). /// /// To specify the NUMA node, see the ExtendedParameters parameter. /// /// A HANDLE to a section that is to be mapped into the address space of the specified process. /// A HANDLE to a process into which the section will be mapped. /// /// The desired base address of the view. The address is rounded down to the nearest 64k boundary. If this parameter is NULL, /// the system picks the base address. /// /// The offset from the beginning of the section. This must be 64k aligned. /// /// The number of bytes to map. A value of zero (0) specifies that the entire section is to be mapped. /// The size must always be a multiple of the page size. /// /// /// The type of memory allocation. This parameter can be zero (0) or one of the following values. /// /// /// Value /// Meaning /// /// /// MEM_RESERVE 0x00002000 /// Maps a reserved view. /// /// /// MEM_REPLACE_PLACEHOLDER 0x00004000 /// /// Replaces a placeholder with a mapped view. Only data/pf-backed section views are supported (no images, physical memory, etc.). /// When you replace a placeholder, BaseAddress and ViewSize must exactly match those of the placeholder. After you replace a /// placeholder with a mapped view, to free that mapped view back to a placeholder, see the UnmapFlags parameter of UnmapViewOfFileEx /// and UnmapViewOfFile2. A placeholder is a type of reserved memory region. /// /// /// /// MEM_LARGE_PAGES 0x20000000 /// Maps a large page view. See large page support. /// /// /// /// /// The desired page protection. /// /// For file-mapping objects created with the SEC_IMAGE attribute, the PageProtection parameter has no effect, and should be /// set to any valid value such as PAGE_READONLY. /// /// /// /// An optional pointer to one or more extended parameters of type MEM_EXTENDED_PARAMETER. Each of those extended parameter values /// can itself have a Type field of either MemExtendedParameterAddressRequirements or MemExtendedParameterNumaNode. If /// no MemExtendedParameterNumaNode extended parameter is provided, then the behavior is the same as for the /// VirtualAlloc/MapViewOfFile functions (that is, the preferred NUMA node for the physical pages is determined based on the ideal /// processor of the thread that first accesses the memory). /// /// The number of extended parameters pointed to by ExtendedParameters. /// /// Returns the base address of the mapped view, if successful. Otherwise, returns NULL and extended error status is available /// using GetLastError. /// /// /// /// This API helps support high-performance games, and server applications, which have particular requirements around managing their /// virtual address space. For example, mapping memory on top of a previously reserved region; this is useful for implementing an /// automatically wrapping ring buffer. And allocating memory with specific alignment; for example, to enable your application to /// commit large/huge page-mapped regions on demand. /// /// Examples /// For a code example, see Scenario 1 in Virtual2Alloc. /// // https://docs.microsoft.com/en-us/windows/desktop/api/memoryapi/nf-memoryapi-mapviewoffile3 // PVOID MapViewOfFile3( HANDLE FileMapping, HANDLE Process, PVOID BaseAddress, ULONG64 Offset, SIZE_T ViewSize, ULONG AllocationType, ULONG PageProtection, MEM_EXTENDED_PARAMETER *ExtendedParameters, ULONG ParameterCount ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("memoryapi.h", MSDNShortId = "585D7BA1-688F-4F24-8D8D-46A2FC137193")] public static extern IntPtr MapViewOfFile3([In] HSECTION FileMapping, [In] HPROCESS Process, [In] IntPtr BaseAddress, ulong Offset, SizeT ViewSize, MEM_ALLOCATION_TYPE AllocationType, MEM_PROTECTION PageProtection, [In] MEM_EXTENDED_PARAMETER[] ExtendedParameters, uint ParameterCount); /// /// /// Maps a view of a file mapping into the address space of a calling process. A caller can optionally specify a suggested base /// memory address for the view. /// /// To specify the NUMA node for the physical memory, see MapViewOfFileExNuma. /// /// /// A handle to a file mapping object. The CreateFileMapping and OpenFileMapping functions return this handle. /// /// /// /// The type of access to a file mapping object, which determines the page protection of the pages. This parameter can be one of the /// following values. /// /// /// /// /// Value /// Meaning /// /// /// FILE_MAP_ALL_ACCESS /// /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or /// PAGE_EXECUTE_READWRITE protection.When used with the MapViewOfFileEx function, FILE_MAP_ALL_ACCESS is equivalent to FILE_MAP_WRITE. /// /// /// /// FILE_MAP_COPY /// /// A copy-on-write view of the file is mapped. The file mapping object must have been created with PAGE_READONLY, PAGE_READ_EXECUTE, /// PAGE_WRITECOPY, PAGE_EXECUTE_WRITECOPY, PAGE_READWRITE, or PAGE_EXECUTE_READWRITE protection.When a process writes to a /// copy-on-write page, the system copies the original page to a new page that is private to the process. The new page is backed by /// the paging file. The protection of the new page changes from copy-on-write to read/write.When copy-on-write access is specified, /// the system and process commit charge taken is for the entire view because the calling process can potentially write to every page /// in the view, making all pages private. The contents of the new page are never written back to the original file and are lost when /// the view is unmapped. /// /// /// /// FILE_MAP_READ /// /// A read-only view of the file is mapped. An attempt to write to the file view results in an access violation.The file mapping /// object must have been created with PAGE_READONLY, PAGE_READWRITE, PAGE_EXECUTE_READ, or PAGE_EXECUTE_READWRITE protection. /// /// /// /// FILE_MAP_WRITE /// /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE or /// PAGE_EXECUTE_READWRITE protection.When used with MapViewOfFileEx, (FILE_MAP_WRITE | FILE_MAP_READ) and FILE_MAP_ALL_ACCESS are /// equivalent to FILE_MAP_WRITE. /// /// /// /// /// Each of the preceding values can be combined with the following value. /// /// /// /// Value /// Meaning /// /// /// FILE_MAP_EXECUTE /// /// An executable view of the file is mapped (mapped memory can be run as code). The file mapping object must have been created with /// PAGE_EXECUTE_READ, PAGE_EXECUTE_WRITECOPY, or PAGE_EXECUTE_READWRITE protection.Windows Server 2003 and Windows XP: This value is /// available starting with Windows XP with SP2 and Windows Server 2003 with SP1. /// /// /// /// /// /// For file mapping objects created with the SEC_IMAGE attribute, the dwDesiredAccess parameter has no effect and should be /// set to any valid value such as FILE_MAP_READ. /// /// For more information about access to file mapping objects, see File Mapping Security and Access Rights. /// /// The high-order DWORD of the file offset where the view is to begin. /// /// The low-order DWORD of the file offset where the view is to begin. The combination of the high and low offsets must /// specify an offset within the file mapping. They must also match the memory allocation granularity of the system. That is, the /// offset must be a multiple of the allocation granularity. To obtain the memory allocation granularity of the system, use the /// GetSystemInfo function, which fills in the members of a SYSTEM_INFO structure. /// /// /// The number of bytes of a file mapping to map to a view. All bytes must be within the maximum size specified by /// CreateFileMapping. If this parameter is 0 (zero), the mapping extends from the specified offset to the end of the file mapping. /// /// /// /// A pointer to the memory address in the calling process address space where mapping begins. This must be a multiple of the /// system's memory allocation granularity, or the function fails. To determine the memory allocation granularity of the system, use /// the GetSystemInfo function. If there is not enough address space at the specified address, the function fails. /// /// /// If lpBaseAddress is NULL, the operating system chooses the mapping address. In this scenario, the function is equivalent /// to the MapViewOfFile function. /// /// /// While it is possible to specify an address that is safe now (not used by the operating system), there is no guarantee that the /// address will remain safe over time. Therefore, it is better to let the operating system choose the address. In this case, you /// would not store pointers in the memory mapped file, you would store offsets from the base of the file mapping so that the mapping /// can be used at any address. /// /// /// /// If the function succeeds, the return value is the starting address of the mapped view. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// // LPVOID WINAPI MapViewOfFileEx( _In_ HANDLE hFileMappingObject, _In_ DWORD dwDesiredAccess, _In_ DWORD dwFileOffsetHigh, _In_ DWORD // dwFileOffsetLow, _In_ SIZE_T dwNumberOfBytesToMap, _In_opt_ LPVOID lpBaseAddress); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366763")] public static extern IntPtr MapViewOfFileEx([In] HSECTION hFileMappingObject, FILE_MAP dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap, [In] IntPtr lpBaseAddress); /// Maps a view of a file mapping into the address space of a calling Windows Store app. /// /// A handle to a file mapping object. The CreateFileMappingFromApp function returns this handle. /// /// /// /// The type of access to a file mapping object, which determines the protection of the pages. This parameter can be one of the /// following values. /// /// /// /// /// Value /// Meaning /// /// /// FILE_MAP_ALL_ACCESS /// /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE protection.When used /// with the MapViewOfFileFromApp function, FILE_MAP_ALL_ACCESS is equivalent to FILE_MAP_WRITE. /// /// /// /// FILE_MAP_COPY /// /// A copy-on-write view of the file is mapped. The file mapping object must have been created with PAGE_READONLY, PAGE_READ_EXECUTE, /// PAGE_WRITECOPY, or PAGE_READWRITE protection.When a process writes to a copy-on-write page, the system copies the original page /// to a new page that is private to the process. The new page is backed by the paging file. The protection of the new page changes /// from copy-on-write to read/write.When copy-on-write access is specified, the system and process commit charge taken is for the /// entire view because the calling process can potentially write to every page in the view, making all pages private. The contents /// of the new page are never written back to the original file and are lost when the view is unmapped. /// /// /// /// FILE_MAP_READ /// /// A read-only view of the file is mapped. An attempt to write to the file view results in an access violation.The file mapping /// object must have been created with PAGE_READONLY, PAGE_READWRITE, PAGE_EXECUTE_READ, or PAGE_EXECUTE_READWRITE protection. /// /// /// /// FILE_MAP_WRITE /// /// A read/write view of the file is mapped. The file mapping object must have been created with PAGE_READWRITE protection.When used /// with MapViewOfFileFromApp, (FILE_MAP_WRITE | FILE_MAP_READ) and FILE_MAP_ALL_ACCESS are equivalent to FILE_MAP_WRITE. /// /// /// /// /// For more information about access to file mapping objects, see File Mapping Security and Access Rights. /// /// /// The file offset where the view is to begin. The offset must specify an offset within the file mapping. They must also match the /// memory allocation granularity of the system. That is, the offset must be a multiple of the allocation granularity. To obtain the /// memory allocation granularity of the system, use the GetSystemInfo function, which fills in the members of a /// SYSTEM_INFO structure. /// /// /// The number of bytes of a file mapping to map to the view. All bytes must be within the maximum size specified by /// CreateFileMappingFromApp. If this parameter is 0 (zero), the mapping extends from the specified offset to the end of the /// file mapping. /// /// /// If the function succeeds, the return value is the starting address of the mapped view. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// // PVOID WINAPI MapViewOfFileFromApp( _In_ HANDLE hFileMappingObject, _In_ ULONG DesiredAccess, _In_ ULONG64 FileOffset, _In_ SIZE_T NumberOfBytesToMap); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("MemoryApi.h", MSDNShortId = "hh994454")] public static extern IntPtr MapViewOfFileFromApp([In] HSECTION hFileMappingObject, FILE_MAP DesiredAccess, ulong FileOffset, SizeT NumberOfBytesToMap); /// /// Maps a view of a file mapping into the address space of a calling Windows Store app. /// /// Using this function, you can: for new allocations, specify a range of virtual address space and a power-of-2 alignment /// restriction; specify an arbitrary number of extended parameters; specify a preferred NUMA node for the physical memory as an /// extended parameter; and specify a placeholder operation (specifically, replacement). /// /// To specify the NUMA node, see the ExtendedParameters parameter. /// /// A HANDLE to a section that is to be mapped into the address space of the specified process. /// A HANDLE to a process into which the section will be mapped. /// /// The desired base address of the view. The address is rounded down to the nearest 64k boundary. If this parameter is NULL, /// the system picks the base address. /// /// The offset from the beginning of the section. This must be 64k aligned. /// /// The number of bytes to map. A value of zero (0) specifies that the entire section is to be mapped. /// The size must always be a multiple of the page size. /// /// /// The type of memory allocation. This parameter can be zero (0) or one of the following values. /// /// /// Value /// Meaning /// /// /// MEM_RESERVE 0x00002000 /// Maps a reserved view. /// /// /// MEM_REPLACE_PLACEHOLDER 0x00004000 /// /// Replaces a placeholder with a mapped view. Only data/pf-backed section views are supported (no images, physical memory, etc.). /// When you replace a placeholder, BaseAddress and ViewSize must exactly match those of the placeholder. After you replace a /// placeholder with a mapped view, to free that mapped view back to a placeholder, see the UnmapFlags parameter of UnmapViewOfFileEx /// and UnmapViewOfFile2. A placeholder is a type of reserved memory region. /// /// /// /// MEM_LARGE_PAGES 0x20000000 /// Maps a large page view. See large page support. /// /// /// /// /// The desired page protection. /// /// For file-mapping objects created with the SEC_IMAGE attribute, the PageProtection parameter has no effect, and should be /// set to any valid value such as PAGE_READONLY. /// /// /// /// An optional pointer to one or more extended parameters of type MEM_EXTENDED_PARAMETER. Each of those extended parameter values /// can itself have a Type field of either MemExtendedParameterAddressRequirements or MemExtendedParameterNumaNode. If /// no MemExtendedParameterNumaNode extended parameter is provided, then the behavior is the same as for the /// VirtualAlloc/MapViewOfFile functions (that is, the preferred NUMA node for the physical pages is determined based on the ideal /// processor of the thread that first accesses the memory). /// /// The number of extended parameters pointed to by ExtendedParameters. /// /// Returns the base address of the mapped view, if successful. Otherwise, returns NULL and extended error status is available /// using GetLastError. /// /// /// /// This API helps support high-performance games, and server applications, which have particular requirements around managing their /// virtual address space. For example, mapping memory on top of a previously reserved region; this is useful for implementing an /// automatically wrapping ring buffer. And allocating memory with specific alignment; for example, to enable your application to /// commit large/huge page-mapped regions on demand. /// /// /// With one important exception, file views derived from any file mapping object that is backed by the same file are coherent or /// identical at a specific time. Coherency is guaranteed for views within a process and for views that are mapped by different processes. /// /// /// The exception is related to remote files. Although MapViewOfFile3FromApp works with remote files, it does not keep them /// coherent. For example, if two computers both map a file as writable, and both change the same page, each computer only sees its /// own writes to the page. When the data gets updated on the disk, it is not merged. /// /// You can only successfully request executable protection if your app has the codeGeneration capability. /// Examples /// For a code example, see Scenario 1 in Virtual2Alloc. /// // https://docs.microsoft.com/en-us/windows/desktop/api/memoryapi/nf-memoryapi-mapviewoffile3fromapp // PVOID MapViewOfFile3FromApp( HANDLE FileMapping, HANDLE Process, PVOID BaseAddress, ULONG64 Offset, SIZE_T ViewSize, ULONG AllocationType, ULONG PageProtection, MEM_EXTENDED_PARAMETER *ExtendedParameters, ULONG ParameterCount ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("memoryapi.h", MSDNShortId = "5E10E1B2-69D9-4F68-8F06-D411CF7FE2ED")] public static extern IntPtr MapViewOfFile3FromApp([In] HSECTION FileMapping, [In] HPROCESS Process, [In] IntPtr BaseAddress, ulong Offset, SizeT ViewSize, MEM_ALLOCATION_TYPE AllocationType, MEM_PROTECTION PageProtection, [In] MEM_EXTENDED_PARAMETER[] ExtendedParameters, uint ParameterCount); /// Maps a view of a file or a pagefile-backed section into the address space of the specified process. /// A HANDLE to a section that is to be mapped into the address space of the specified process. /// A HANDLE to a process into which the section will be mapped. /// The offset from the beginning of the section. This must be 64k aligned. /// /// The desired base address of the view. The address is rounded down to the nearest 64k boundary. If this parameter is NULL, /// the system picks the base address. /// /// The number of bytes to map. A value of zero (0) specifies that the entire section is to be mapped. /// The type of allocation. This parameter can be zero (0) or one of the following constant values: /// The desired page protection. /// The preferred NUMA node for this memory. /// /// Returns the base address of the mapped view, if successful. Otherwise, returns NULL and extended error status is available /// using GetLastError. /// // PVOID WINAPI MapViewOfFileNuma2( _In_ HANDLE FileMappingHandle, _In_ HANDLE ProcessHandle, _In_ ULONG64 Offset, _In_opt_ PVOID // BaseAddress, _In_ SIZE_T ViewSize, _In_ ULONG AllocationType, _In_ ULONG PageProtection, _In_ ULONG PreferredNode); [DllImport("Api-ms-win-core-memory-l1-1-5.dll", SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "mt492558")] public static extern IntPtr MapViewOfFileNuma2([In] HSECTION FileMappingHandle, [In] HPROCESS ProcessHandle, ulong Offset, IntPtr BaseAddress, SizeT ViewSize, MEM_ALLOCATION_TYPE AllocationType, MEM_PROTECTION PageProtection, uint PreferredNode); /// /// /// Indicates that the data contained in a range of memory pages is no longer needed by the application and can be discarded by the /// system if necessary. /// /// /// The specified pages will be marked as inaccessible, removed from the process working set, and will not be written to the paging file. /// /// To later reclaim offered pages, call ReclaimVirtualMemory. /// /// Page-aligned starting address of the memory to offer. /// Size, in bytes, of the memory region to offer. Size must be an integer multiple of the system page size. /// /// /// Priority indicates how important the offered memory is to the application. A higher priority increases the probability that the /// offered memory can be reclaimed intact when calling ReclaimVirtualMemory. The system typically discards lower priority /// memory before discarding higher priority memory. Priority must be one of the following values. /// /// /// /// /// Value /// Meaning /// /// /// VMOfferPriorityVeryLow0x00001000 /// The offered memory is very low priority, and should be the first discarded. /// /// /// VMOfferPriorityLow0x00002000 /// The offered memory is low priority. /// /// /// VMOfferPriorityBelowNormal0x00002000 /// The offered memory is below normal priority. /// /// /// VMOfferPriorityNormal0x00002000 /// The offered memory is of normal priority to the application, and should be the last discarded. /// /// /// /// /// ERROR_SUCCESS if successful; a System Error Code otherwise. // DWORD WINAPI OfferVirtualMemory( _In_ PVOID VirtualAddress, _In_ SIZE_T Size, _In_ OFFER_PRIORITY Priority); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dn781436")] public static extern uint OfferVirtualMemory(IntPtr VirtualAddress, SizeT Size, OFFER_PRIORITY Priority); /// Opens a named file mapping object. /// /// The access to the file mapping object. This access is checked against any security descriptor on the target file mapping object. /// For a list of values, see File Mapping Security and Access Rights. /// /// /// If this parameter is TRUE, a process created by the CreateProcess function can inherit the handle; otherwise, the /// handle cannot be inherited. /// /// /// The name of the file mapping object to be opened. If there is an open handle to a file mapping object by this name and the /// security descriptor on the mapping object does not conflict with the dwDesiredAccess parameter, the open operation succeeds. The /// name can have a "Global\" or "Local\" prefix to explicitly open an object in the global or session namespace. The remainder of /// the name can contain any character except the backslash character (\). For more information, see Kernel Object Namespaces. Fast /// user switching is implemented using Terminal Services sessions. The first user to log on uses session 0, the next user to log on /// uses session 1, and so on. Kernel object names must follow the guidelines outlined for Terminal Services so that applications can /// support multiple users. /// /// /// If the function succeeds, the return value is an open handle to the specified file mapping object. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// // HANDLE WINAPI OpenFileMapping( _In_ DWORD dwDesiredAccess, _In_ BOOL bInheritHandle, _In_ LPCTSTR lpName); [DllImport(Lib.Kernel32, SetLastError = true, CharSet = CharSet.Auto)] [PInvokeData("WinBase.h", MSDNShortId = "aa366791")] public static extern SafeHSECTION OpenFileMapping(FILE_MAP dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, string lpName); /// Opens a named file mapping object. /// /// The access to the file mapping object. This access is checked against any security descriptor on the target file mapping object. /// For a list of values, see File Mapping Security and Access Rights. You can only open the file mapping object for /// FILE_MAP_EXECUTE access if your app has the codeGeneration capability. /// /// /// If this parameter is TRUE, a process created by the CreateProcess function can inherit the handle; otherwise, the /// handle cannot be inherited. /// /// /// The name of the file mapping object to be opened. If there is an open handle to a file mapping object by this name and the /// security descriptor on the mapping object does not conflict with the DesiredAccess parameter, the open operation succeeds. The /// name can have a "Global\" or "Local\" prefix to explicitly open an object in the global or session namespace. The remainder of /// the name can contain any character except the backslash character (\). For more information, see Kernel Object Namespaces. Fast /// user switching is implemented using Terminal Services sessions. The first user to log on uses session 0, the next user to log on /// uses session 1, and so on. Kernel object names must follow the guidelines outlined for Terminal Services so that applications can /// support multiple users. /// /// /// If the function succeeds, the return value is an open handle to the specified file mapping object. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// // HANDLE WINAPI OpenFileMappingFromApp( _In_ ULONG DesiredAccess, _In_ BOOL InheritHandle, _In_ PCWSTR Name); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)] [PInvokeData("MemoryApi.h", MSDNShortId = "mt169844")] public static extern SafeHSECTION OpenFileMappingFromApp(FILE_MAP DesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool InheritHandle, string Name); /// /// Provides an efficient mechanism to bring into memory potentially discontiguous virtual address ranges in a process address space. /// /// /// Handle to the process whose virtual address ranges are to be prefetched. Use the GetCurrentProcess function to use the /// current process. /// /// Number of entries in the array pointed to by the VirtualAddresses parameter. /// /// Pointer to an array of WIN32_MEMORY_RANGE_ENTRY structures which each specify a virtual address range to be prefetched. /// The virtual address ranges may cover any part of the process address space accessible by the target process. /// /// Reserved. Must be 0. /// /// If the function succeeds, the return value is a nonzero value. /// If the function fails, the return value is 0 (zero). To get extended error information, call GetLastError. /// // BOOL WINAPI PrefetchVirtualMemory( _In_ HANDLE hProcess, _In_ ULONG_PTR NumberOfEntries, _In_ PWIN32_MEMORY_RANGE_ENTRY // VirtualAddresses, _In_ ULONG Flags); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "hh780543")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool PrefetchVirtualMemory(HPROCESS hProcess, UIntPtr NumberOfEntries, IntPtr VirtualAddresses, uint Flags); /// Retrieves the state of the specified memory resource object. /// /// A handle to a memory resource notification object. The CreateMemoryResourceNotification function returns this handle. /// /// /// The memory pointed to by this parameter receives the state of the memory resource notification object. The value of this /// parameter is set to TRUE if the specified memory condition exists, and FALSE if the specified memory condition does /// not exist. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. For more error information, call GetLastError. /// // BOOL WINAPI QueryMemoryResourceNotification( _In_ HANDLE ResourceNotificationHandle, _Out_ PBOOL ResourceState); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366799")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool QueryMemoryResourceNotification([In] SafeMemoryResourceNotification ResourceNotificationHandle, [Out, MarshalAs(UnmanagedType.Bool)] out bool ResourceState); /// /// The QueryVirtualMemoryInformation function returns information about a page or a set of pages within the virtual address /// space of the specified process. /// /// A handle for the process in whose context the pages to be queried reside. /// /// The address of the region of pages to be queried. This value is rounded down to the next host-page-address boundary. /// /// /// The memory information class about which to retrieve information. The only supported value is MemoryRegionInfo. /// /// /// A pointer to a buffer that receives the specified information. /// /// If the MemoryInformationClass parameter has a value of MemoryRegionInfo, this parameter must point to a /// WIN32_MEMORY_REGION_INFORMATION structure. /// /// /// Specifies the length in bytes of the memory information buffer. /// /// An optional pointer which, if specified, receives the number of bytes placed in the memory information buffer. /// /// Returns TRUE on success. Returns FALSE for failure. To get extended error information, call GetLastError. // BOOL WINAPI QueryVirtualMemoryInformation( _In_ HANDLE Process, _In_ const VOID *VirtualAddress, _In_ // WIN32_MEMORY_INFORMATION_CLASS MemoryInformationClass, _Out_ _writes_bytes_(MemoryInformationSize) PVOID MemoryInformation, _In_ // SIZE_T MemoryInformationSize, _Out_opt_ PSIZE_T ReturnSize); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("MemoryApi.h", MSDNShortId = "mt845761")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool QueryVirtualMemoryInformation([In] HPROCESS Process, IntPtr VirtualAddress, WIN32_MEMORY_INFORMATION_CLASS MemoryInformationClass, IntPtr MemoryInformation, SizeT MemoryInformationSize, out SizeT ReturnSize); /// /// Reads data from an area of memory in a specified process. The entire area to be read must be accessible or the operation fails. /// /// /// A handle to the process with memory that is being read. The handle must have PROCESS_VM_READ access to the process. /// /// /// A pointer to the base address in the specified process from which to read. Before any data transfer occurs, the system verifies /// that all data in the base address and memory of the specified size is accessible for read access, and if it is not accessible the /// function fails. /// /// A pointer to a buffer that receives the contents from the address space of the specified process. /// The number of bytes to be read from the specified process. /// /// A pointer to a variable that receives the number of bytes transferred into the specified buffer. If lpNumberOfBytesRead is /// NULL, the parameter is ignored. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is 0 (zero). To get extended error information, call GetLastError. /// The function fails if the requested read operation crosses into an area of the process that is inaccessible. /// // BOOL WINAPI ReadProcessMemory( _In_ HANDLE hProcess, _In_ LPCVOID lpBaseAddress, _Out_ LPVOID lpBuffer, _In_ SIZE_T nSize, _Out_ // SIZE_T *lpNumberOfBytesRead); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms680553")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool ReadProcessMemory([In] HPROCESS hProcess, [In] IntPtr lpBaseAddress, IntPtr lpBuffer, SizeT nSize, out SizeT lpNumberOfBytesRead); /// /// Reclaims a range of memory pages that were offered to the system with OfferVirtualMemory. /// /// If the offered memory has been discarded, the contents of the memory region is undefined and must be rewritten by the /// application. If the offered memory has not been discarded, it is reclaimed intact. /// /// /// Page-aligned starting address of the memory to reclaim. /// Size, in bytes, of the memory region to reclaim. Size must be an integer multiple of the system page size. /// /// Returns ERROR_SUCCESS if successful and the memory was reclaimed intact. /// /// Returns ERROR_BUSY if successful but the memory was discarded and must be rewritten by the application. In this case, the /// contents of the memory region is undefined. /// /// Returns a System Error Code otherwise. /// // DWORD WINAPI ReclaimVirtualMemory( _In_ PVOID VirtualAddress, _In_ SIZE_T Size); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dn781437")] public static extern uint ReclaimVirtualMemory(IntPtr VirtualAddress, SizeT Size); /// /// Registers a bad memory notification that is called when one or more bad memory pages are detected and the system cannot remove at /// least one of them (for example if the pages contains modified data that has not yet been written to the pagefile.) /// /// A pointer to the application-defined BadMemoryCallbackRoutine function to register. /// /// Registration handle that represents the callback notification. Can be passed to the UnregisterBadMemoryNotification /// function when no longer needed. /// // PVOID WINAPI RegisterBadMemoryNotification( _In_ PBAD_MEMORY_CALLBACK_ROUTINE Callback); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "hh691013")] public static extern IntPtr RegisterBadMemoryNotification(BadMemoryCallbackRoutine Callback); /// /// /// Resets the write-tracking state for a region of virtual memory. Subsequent calls to the GetWriteWatch function only report /// pages that are written to since the reset operation. /// /// /// 64-bit Windows on Itanium-based systems: Due to the difference in page sizes, ResetWriteWatch is not supported for /// 32-bit applications. /// /// /// /// A pointer to the base address of the memory region for which to reset the write-tracking state. /// This address must be in a memory region that is allocated by the VirtualAlloc function with MEM_WRITE_WATCH. /// /// The size of the memory region for which to reset the write-tracking information, in bytes. /// /// If the function succeeds, the return value is 0 (zero). /// If the function fails, the return value is a nonzero value. /// // UINT WINAPI ResetWriteWatch( _In_ LPVOID lpBaseAddress, _In_ SIZE_T dwRegionSize); [DllImport(Lib.Kernel32, SetLastError = false, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366874")] public static extern uint ResetWriteWatch([In] IntPtr lpBaseAddress, SizeT dwRegionSize); /// /// /// [Some information relates to pre-released product which may be substantially modified before it's commercially released. /// Microsoft makes no warranties, express or implied, with respect to the information provided here.] /// /// /// Provides CFG with a list of valid indirect call targets and specifies whether they should be marked valid or not. The valid call /// target information is provided as a list of offsets relative to a virtual memory range(start and size of the range). The call /// targets specified should be 16-byte aligned and in ascendingorder. /// /// /// The handle to the target process. /// The start of the virtual memory region whose call targets are being marked valid. /// The size of the virtual memory region. /// The number of offsets relative to the virtual memory ranges. /// A list of offsets and flags relative to the virtual memory ranges. /// /// TRUE if the operation was successful; otherwise, FALSE. To retrieve error values for this function, call GetLastError. /// // WINAPI SetProcessValidCallTargets( _In_ HANDLE hProcess, _In_ PVOID VirtualAddress, _In_ SIZE_T RegionSize, _In_ ULONG // NumberOfOffsets, _Inout_ PCFG_CALL_TARGET_INFO OffsetInformation); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "dn934202")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetProcessValidCallTargets(HPROCESS hProcess, IntPtr VirtualAddress, SizeT RegionSize, uint NumberOfOffsets, [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] CFG_CALL_TARGET_INFO[] OffsetInformation); /// Sets the minimum and maximum working set sizes for the specified process. /// /// A handle to the process whose working set sizes is to be set. /// The handle must have PROCESS_SET_QUOTA access rights. For more information, see Process Security and Access Rights. /// /// /// /// The minimum working set size for the process, in bytes. The virtual memory manager attempts to keep at least this much memory /// resident in the process whenever the process is active. /// /// /// This parameter must be greater than zero but less than or equal to the maximum working set size. The default size is 50 pages /// (for example, this is 204,800 bytes on systems with a 4K page size). If the value is greater than zero but less than 20 pages, /// the minimum value is set to 20 pages. /// /// /// If both dwMinimumWorkingSetSize and dwMaximumWorkingSetSize have the value ( SIZE_T)–1, the function removes as many pages /// as possible from the working set of the specified process. /// /// /// /// /// The maximum working set size for the process, in bytes. The virtual memory manager attempts to keep no more than this much memory /// resident in the process whenever the process is active and available memory is low. /// /// /// This parameter must be greater than or equal to 13 pages (for example, 53,248 on systems with a 4K page size), and less than the /// system-wide maximum (number of available pages minus 512 pages). The default size is 345 pages (for example, this is 1,413,120 /// bytes on systems with a 4K page size). /// /// /// If both dwMinimumWorkingSetSize and dwMaximumWorkingSetSize have the value ( SIZE_T)–1, the function removes as many pages /// as possible from the working set of the specified process. For details, see Remarks. /// /// /// /// The flags that control the enforcement of the minimum and maximum working set sizes. /// /// /// /// Value /// Meaning /// /// /// QUOTA_LIMITS_HARDWS_MIN_DISABLE0x00000002 /// /// The working set may fall below the minimum working set limit if memory demands are high.This flag cannot be used with QUOTA_LIMITS_HARDWS_MIN_ENABLE. /// /// /// /// QUOTA_LIMITS_HARDWS_MIN_ENABLE0x00000001 /// The working set will not fall below the minimum working set limit.This flag cannot be used with QUOTA_LIMITS_HARDWS_MIN_DISABLE. /// /// /// QUOTA_LIMITS_HARDWS_MAX_DISABLE0x00000008 /// The working set may exceed the maximum working set limit if there is abundant memory.This flag cannot be used with QUOTA_LIMITS_HARDWS_MAX_ENABLE. /// /// /// QUOTA_LIMITS_HARDWS_MAX_ENABLE0x00000004 /// The working set will not exceed the maximum working set limit.This flag cannot be used with QUOTA_LIMITS_HARDWS_MAX_DISABLE. /// /// /// /// /// /// If the function is succeeds, the return value is nonzero. /// /// If the function fails, the return value is zero. To get extended error information, call GetLastError. If the function /// fails, the return value is zero. To get extended error information, call GetLastError. /// /// // BOOL WINAPI SetProcessWorkingSetSizeEx( _In_ HANDLE hProcess, _In_ SIZE_T dwMinimumWorkingSetSize, _In_ SIZE_T // dwMaximumWorkingSetSize, _In_ DWORD Flags); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms686237")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetProcessWorkingSetSizeEx([In] HPROCESS hProcess, SizeT dwMinimumWorkingSetSize, SizeT dwMaximumWorkingSetSize, QUOTA_LIMITS_HARDWS Flags); /// Limits the size of the working set for the file system cache. /// /// /// The minimum size of the file cache, in bytes. The virtual memory manager attempts to keep at least this much memory resident in /// the system file cache. /// /// To flush the cache, specify . /// /// /// /// The maximum size of the file cache, in bytes. The virtual memory manager enforces this limit only if this call or a previous call /// to SetSystemFileCacheSize specifies FILE_CACHE_MAX_HARD_ENABLE. /// /// To flush the cache, specify . /// /// /// /// The flags that enable or disable the file cache limits. If this parameter is 0 (zero), the size limits retain the current /// setting, which is either disabled or enabled. /// /// /// /// /// Value /// Meaning /// /// /// FILE_CACHE_MAX_HARD_DISABLE0x2 /// Disable the maximum size limit.The FILE_CACHE_MAX_HARD_DISABLE and FILE_CACHE_MAX_HARD_ENABLE flags are mutually exclusive. /// /// /// FILE_CACHE_MAX_HARD_ENABLE0x1 /// Enable the maximum size limit.The FILE_CACHE_MAX_HARD_DISABLE and FILE_CACHE_MAX_HARD_ENABLE flags are mutually exclusive. /// /// /// FILE_CACHE_MIN_HARD_DISABLE0x8 /// Disable the minimum size limit.The FILE_CACHE_MIN_HARD_DISABLE and FILE_CACHE_MIN_HARD_ENABLE flags are mutually exclusive. /// /// /// FILE_CACHE_MIN_HARD_ENABLE0x4 /// Enable the minimum size limit.The FILE_CACHE_MIN_HARD_DISABLE and FILE_CACHE_MIN_HARD_ENABLE flags are mutually exclusive. /// /// /// /// /// /// If the function succeeds, the return value is a nonzero value. /// If the function fails, the return value is 0 (zero). To get extended error information, call GetLastError. /// // BOOL WINAPI SetSystemFileCacheSize( _In_ SIZE_T MinimumFileCacheSize, _In_ SIZE_T MaximumFileCacheSize, _In_ DWORD Flags); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa965240")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool SetSystemFileCacheSize(SizeT MinimumFileCacheSize, SizeT MaximumFileCacheSize, FILE_CACHE_LIMITS Flags); /// Unmaps a mapped view of a file from the calling process's address space. /// /// A pointer to the base address of the mapped view of a file that is to be unmapped. This value must be identical to the value /// returned by a previous call to the MapViewOfFile or MapViewOfFileEx function. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI UnmapViewOfFile( _In_ LPCVOID lpBaseAddress); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366882")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnmapViewOfFile([In] IntPtr lpBaseAddress); /// Unmaps a previously mapped view of a file or a pagefile-backed section. /// A HANDLE to the process from which the section will be unmapped. /// /// The base address of a previously mapped view that is to be unmapped. This value must be identical to the value returned by a /// previous call to MapViewOfFile2. /// /// /// MEM_UNMAP_WITH_TRANSIENT_BOOST (1) or zero (0). MEM_UNMAP_WITH_TRANSIENT_BOOST should be used if the pages backing this view /// should be temporarily boosted (with automatic short term decay) because another thread will access them shortly. /// /// [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("MemoryApi.h", MSDNShortId = "mt492559")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnmapViewOfFile2([In] HPROCESS ProcessHandle, IntPtr BaseAddress, uint UnmapFlags); /// This is an extended version of UnmapViewOfFile that takes an additional flags parameter. /// /// A pointer to the base address of the mapped view of a file that is to be unmapped. This value must be identical to the value /// returned by a previous call to the MapViewOfFile or MapViewOfFileEx function. /// /// /// The only supported flag is MEM_UNMAP_WITH_TRANSIENT_BOOST (0x1), which specifies that the priority of the pages being unmapped /// should be temporarily boosted because the caller expects that these pages will be accessed again shortly. For more information /// about memory priorities, see the SetThreadInformation(ThreadMemoryPriority) function. /// /// /// If the function succeeds, the return value is a nonzero value. /// If the function fails, the return value is 0 (zero). To get extended error information, call GetLastError. /// [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("MemoryApi.h", MSDNShortId = "mt670639")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnmapViewOfFileEx(IntPtr BaseAddress, uint UnmapFlags); /// Closes the specified bad memory notification handle. /// Registration handle returned from the RegisterBadMemoryNotification function. /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI UnregisterBadMemoryNotification( _In_ PVOID RegistrationHandle); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "hh691014")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnregisterBadMemoryNotification(IntPtr RegistrationHandle); /// /// /// Reserves, commits, or changes the state of a region of pages in the virtual address space of the calling process. Memory /// allocated by this function is automatically initialized to zero. /// /// To allocate memory in the address space of another process, use the VirtualAllocEx function. /// /// /// /// The starting address of the region to allocate. If the memory is being reserved, the specified address is rounded down to the /// nearest multiple of the allocation granularity. If the memory is already reserved and is being committed, the address is rounded /// down to the next page boundary. To determine the size of a page and the allocation granularity on the host computer, use the /// GetSystemInfo function. If this parameter is NULL, the system determines where to allocate the region. /// /// /// If this address is within an enclave that you have not initialized by calling InitializeEnclave, VirtualAlloc /// allocates a page of zeros for the enclave at that address. The page must be previously uncommitted, and will not be measured with /// the EEXTEND instruction of the Intel Software Guard Extensions programming model. /// /// /// If the address in within an enclave that you initialized, then the allocation operation fails with the /// ERROR_INVALID_ADDRESS error. /// /// /// /// The size of the region, in bytes. If the lpAddress parameter is NULL, this value is rounded up to the next page boundary. /// Otherwise, the allocated pages include all pages containing one or more bytes in the range from lpAddress to lpAddress+dwSize. /// This means that a 2-byte range straddling a page boundary causes both pages to be included in the allocated region. /// /// /// The type of memory allocation. This parameter must contain one of the following values. /// /// /// /// Value /// Meaning /// /// /// MEM_COMMIT0x00001000 /// /// Allocates memory charges (from the overall size of memory and the paging files on disk) for the specified reserved memory pages. /// The function also guarantees that when the caller later initially accesses the memory, the contents will be zero. Actual physical /// pages are not allocated unless/until the virtual addresses are actually accessed.To reserve and commit pages in one step, call /// VirtualAlloc with .Attempting to commit a specific address range by specifying MEM_COMMIT without MEM_RESERVE and a non-NULL /// lpAddress fails unless the entire range has already been reserved. The resulting error code is ERROR_INVALID_ADDRESS.An attempt /// to commit a page that is already committed does not cause the function to fail. This means that you can commit pages without /// first determining the current commitment state of each page.If lpAddress specifies an address within an enclave, flAllocationType /// must be MEM_COMMIT. /// /// /// /// MEM_RESERVE0x00002000 /// /// Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging /// file on disk.You can commit reserved pages in subsequent calls to the VirtualAlloc function. To reserve and commit pages in one /// step, call VirtualAlloc with MEM_COMMIT | MEM_RESERVE.Other memory allocation functions, such as malloc and LocalAlloc, cannot /// use a reserved range of memory until it is released. /// /// /// /// MEM_RESET0x00080000 /// /// Indicates that data in the memory range specified by lpAddress and dwSize is no longer of interest. The pages should not be read /// from or written to the paging file. However, the memory block will be used again later, so it should not be decommitted. This /// value cannot be used with any other value.Using this value does not guarantee that the range operated on with MEM_RESET will /// contain zeros. If you want the range to contain zeros, decommit the memory and then recommit it.When you specify MEM_RESET, the /// VirtualAlloc function ignores the value of flProtect. However, you must still set flProtect to a valid protection value, such as /// PAGE_NOACCESS.VirtualAlloc returns an error if you use MEM_RESET and the range of memory is mapped to a file. A shared view is /// only acceptable if it is mapped to a paging file. /// /// /// /// MEM_RESET_UNDO0x1000000 /// /// MEM_RESET_UNDO should only be called on an address range to which MEM_RESET was successfully applied earlier. It indicates that /// the data in the specified memory range specified by lpAddress and dwSize is of interest to the caller and attempts to reverse the /// effects of MEM_RESET. If the function succeeds, that means all data in the specified address range is intact. If the function /// fails, at least some of the data in the address range has been replaced with zeroes.This value cannot be used with any other /// value. If MEM_RESET_UNDO is called on an address range which was not MEM_RESET earlier, the behavior is undefined. When you /// specify MEM_RESET, the VirtualAlloc function ignores the value of flProtect. However, you must still set flProtect to a valid /// protection value, such as PAGE_NOACCESS.Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server /// 2003 and Windows XP: The MEM_RESET_UNDO flag is not supported until Windows 8 and Windows Server 2012. /// /// /// /// /// This parameter can also specify the following values as indicated. /// /// /// /// Value /// Meaning /// /// /// MEM_LARGE_PAGES0x20000000 /// /// Allocates memory using large page support.The size and alignment must be a multiple of the large-page minimum. To obtain this /// value, use the GetLargePageMinimum function.If you specify this value, you must also specify MEM_RESERVE and MEM_COMMIT. /// /// /// /// MEM_PHYSICAL0x00400000 /// /// Reserves an address range that can be used to map Address Windowing Extensions (AWE) pages.This value must be used with /// MEM_RESERVE and no other values. /// /// /// /// MEM_TOP_DOWN0x00100000 /// /// Allocates memory at the highest possible address. This can be slower than regular allocations, especially when there are many allocations. /// /// /// /// MEM_WRITE_WATCH0x00200000 /// /// Causes the system to track pages that are written to in the allocated region. If you specify this value, you must also specify /// MEM_RESERVE.To retrieve the addresses of the pages that have been written to since the region was allocated or the write-tracking /// state was reset, call the GetWriteWatch function. To reset the write-tracking state, call GetWriteWatch or ResetWriteWatch. The /// write-tracking feature remains enabled for the memory region until the region is freed. /// /// /// /// /// /// /// /// The memory protection for the region of pages to be allocated. If the pages are being committed, you can specify any one of the /// memory protection constants. /// /// If lpAddress specifies an address within an enclave, flProtect cannot be any of the following values: /// /// /// If the function succeeds, the return value is the base address of the allocated region of pages. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// // LPVOID WINAPI VirtualAlloc( _In_opt_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD flAllocationType, _In_ DWORD flProtect); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366887")] public static extern IntPtr VirtualAlloc([In] IntPtr lpAddress, SizeT dwSize, MEM_ALLOCATION_TYPE flAllocationType, MEM_PROTECTION flProtect); /// /// /// Reserves, commits, or changes the state of a region of memory within the virtual address space of a specified process. The /// function initializes the memory it allocates to zero. /// /// /// Using this function, you can: for new allocations, specify a range of virtual address space and a power-of-2 alignment /// restriction; specify an arbitrary number of extended parameters; specify a preferred NUMA node for the physical memory as an /// extended parameter; and specify a placeholder operation (specifically, replacement). /// /// To specify the NUMA node, see the ExtendedParameters parameter. /// /// /// The handle to a process. The function allocates memory within the virtual address space of this process. /// /// The handle must have the PROCESS_VM_OPERATION access right. For more information, see Process Security and Access Rights. /// /// /// /// The pointer that specifies a desired starting address for the region of pages that you want to allocate. /// /// If an explicit base address is specified, then it must be a multiple of the system allocation granularity. To determine the size /// of a page and the allocation granularity on the host computer, use the GetSystemInfo function. /// /// If BaseAddress is NULL, the function determines where to allocate the region. /// /// If this address is within an enclave that you have not initialized by calling InitializeEnclave, VirtualAlloc2 allocates a /// page of zeros for the enclave at that address. The page must be previously uncommitted, and will not be measured with the EEXTEND /// instruction of the Intel Software Guard Extensions programming model. /// /// /// If the address in within an enclave that you initialized, then the allocation operation fails with the /// ERROR_INVALID_ADDRESS error. /// /// /// /// The size of the region of memory to allocate, in bytes. /// The size must always be a multiple of the page size. /// /// If BaseAddress is not NULL, the function allocates all pages that contain one or more bytes in the range from BaseAddress /// to BaseAddress+Size. This means, for example, that a 2-byte range that straddles a page boundary causes the function to allocate /// both pages. /// /// /// /// The type of memory allocation. This parameter must contain one of the following values. /// /// /// Value /// Meaning /// /// /// MEM_COMMIT 0x00001000 /// /// Allocates memory charges (from the overall size of memory and the paging files on disk) for the specified reserved memory pages. /// The function also guarantees that when the caller later initially accesses the memory, the contents will be zero. Actual physical /// pages are not allocated unless/until the virtual addresses are actually accessed. To reserve and commit pages in one step, call /// VirtualAlloc2 with . Attempting to commit a specific address range by specifying MEM_COMMIT without MEM_RESERVE and a non-NULL /// BaseAddress fails unless the entire range has already been reserved. The resulting error code is ERROR_INVALID_ADDRESS. An /// attempt to commit a page that is already committed does not cause the function to fail. This means that you can commit pages /// without first determining the current commitment state of each page. If BaseAddress specifies an address within an enclave, /// AllocationType must be MEM_COMMIT. /// /// /// /// MEM_RESERVE 0x00002000 /// /// Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging /// file on disk. You commit reserved pages by calling VirtualAlloc2 again with MEM_COMMIT. To reserve and commit pages in one step, /// call VirtualAlloc2 with . Other memory allocation functions, such as malloc and LocalAlloc, cannot use reserved memory until it /// has been released. /// /// /// /// MEM_REPLACE_PLACEHOLDER 0x00004000 /// /// Replaces a placeholder with a normal private allocation. Only data/pf-backed section views are supported (no images, physical /// memory, etc.). When you replace a placeholder, BaseAddress and Size must exactly match those of the placeholder. After you /// replace a placeholder with a private allocation, to free that allocation back to a placeholder, see the dwFreeType parameter of /// VirtualFree and VirtualFreeEx. A placeholder is a type of reserved memory region. /// /// /// /// MEM_RESERVE_PLACEHOLDER 0x00040000 /// /// To create a placeholder, call VirtualAlloc2 with and PageProtection set to PAGE_NOACCESS. To free/split/coalesce a placeholder, /// see the dwFreeType parameter of VirtualFree and VirtualFreeEx. A placeholder is a type of reserved memory region. /// /// /// /// MEM_RESET 0x00080000 /// /// Indicates that data in the memory range specified by BaseAddress and Size is no longer of interest. The pages should not be read /// from or written to the paging file. However, the memory block will be used again later, so it should not be decommitted. This /// value cannot be used with any other value. Using this value does not guarantee that the range operated on with MEM_RESET will /// contain zeros. If you want the range to contain zeros, decommit the memory and then recommit it. When you use MEM_RESET, the /// VirtualAlloc2 function ignores the value of fProtect. However, you must still set fProtect to a valid protection value, such as /// PAGE_NOACCESS. VirtualAlloc2 returns an error if you use MEM_RESET and the range of memory is mapped to a file. A shared view is /// only acceptable if it is mapped to a paging file. /// /// /// /// MEM_RESET_UNDO 0x1000000 /// /// MEM_RESET_UNDO should only be called on an address range to which MEM_RESET was successfully applied earlier. It indicates that /// the data in the specified memory range specified by BaseAddress and Size is of interest to the caller and attempts to reverse the /// effects of MEM_RESET. If the function succeeds, that means all data in the specified address range is intact. If the function /// fails, at least some of the data in the address range has been replaced with zeroes. This value cannot be used with any other /// value. If MEM_RESET_UNDO is called on an address range which was not MEM_RESET earlier, the behavior is undefined. When you /// specify MEM_RESET, the VirtualAlloc2 function ignores the value of PageProtection. However, you must still set PageProtection to /// a valid protection value, such as PAGE_NOACCESS. Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows /// Server 2003 and Windows XP: The MEM_RESET_UNDO flag is not supported until Windows 8 and Windows Server 2012. /// /// /// /// This parameter can also specify the following values as indicated. /// /// /// Value /// Meaning /// /// /// MEM_LARGE_PAGES 0x20000000 /// /// Allocates memory using large page support. The size and alignment must be a multiple of the large-page minimum. To obtain this /// value, use the GetLargePageMinimum function. If you specify this value, you must also specify MEM_RESERVE and MEM_COMMIT. /// /// /// /// MEM_PHYSICAL 0x00400000 /// /// Reserves an address range that can be used to map Address Windowing Extensions (AWE) pages. This value must be used with /// MEM_RESERVE and no other values. /// /// /// /// MEM_TOP_DOWN 0x00100000 /// /// Allocates memory at the highest possible address. This can be slower than regular allocations, especially when there are many allocations. /// /// /// /// /// /// /// The memory protection for the region of pages to be allocated. If the pages are being committed, you can specify any one of the /// memory protection constants. /// /// If BaseAddress specifies an address within an enclave, PageProtection cannot be any of the following values: /// /// /// PAGE_NOACCESS /// /// /// PAGE_GUARD /// /// /// PAGE_NOCACHE /// /// /// PAGE_WRITECOMBINE /// /// /// /// /// /// An optional pointer to one or more extended parameters of type MEM_EXTENDED_PARAMETER. Each of those extended parameter values /// can itself have a Type field of either MemExtendedParameterAddressRequirements or MemExtendedParameterNumaNode. If /// no MemExtendedParameterNumaNode extended parameter is provided, then the behavior is the same as for the /// VirtualAlloc/MapViewOfFile functions (that is, the preferred NUMA node for the physical pages is determined based on the ideal /// processor of the thread that first accesses the memory). /// /// /// /// The number of extended parameters pointed to by ExtendedParameters. /// /// /// If the function succeeds, the return value is the base address of the allocated region of pages. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// /// /// /// This API helps support high-performance games, and server applications, which have particular requirements around managing their /// virtual address space. For example, mapping memory on top of a previously reserved region; this is useful for implementing an /// automatically wrapping ring buffer. And allocating memory with specific alignment; for example, to enable your application to /// commit large/huge page-mapped regions on demand. /// /// Each page has an associated page state. The VirtualAlloc2 function can perform the following operations: /// /// /// Commit a region of reserved pages /// /// /// Reserve a region of free pages /// /// /// Simultaneously reserve and commit a region of free pages /// /// /// /// VirtualAlloc2 cannot reserve a reserved page. It can commit a page that is already committed. This means you can commit a /// range of pages, regardless of whether they have already been committed, and the function will not fail. /// /// /// You can use VirtualAlloc2 to reserve a block of pages and then make additional calls to VirtualAlloc2 to commit /// individual pages from the reserved block. This enables a process to reserve a range of its virtual address space without /// consuming physical storage until it is needed. /// /// /// If the lpAddress parameter is not NULL, the function uses the lpAddress and dwSize parameters to compute the region of /// pages to be allocated. The current state of the entire range of pages must be compatible with the type of allocation specified by /// the flAllocationType parameter. Otherwise, the function fails and none of the pages is allocated. This compatibility requirement /// does not preclude committing an already committed page; see the preceding list. /// /// /// To execute dynamically generated code, use VirtualAlloc2 to allocate memory, and the VirtualProtectEx function to grant /// PAGE_EXECUTE access. /// /// /// The VirtualAlloc2 function can be used to reserve an Address Windowing Extensions (AWE) region of memory within the /// virtual address space of a specified process. This region of memory can then be used to map physical pages into and out of /// virtual memory as required by the application. The MEM_PHYSICAL and MEM_RESERVE values must be set in the /// AllocationType parameter. The MEM_COMMIT value must not be set. The page protection must be set to PAGE_READWRITE. /// /// /// The VirtualFreeEx function can decommit a committed page, releasing the page's storage, or it can simultaneously decommit and /// release a committed page. It can also release a reserved page, making it a free page. /// /// /// When creating a region that will be executable, the calling program bears responsibility for ensuring cache coherency via an /// appropriate call to FlushInstructionCache once the code has been set in place. Otherwise attempts to execute code out of the /// newly executable region may produce unpredictable results. /// /// Examples /// Scenario 1. Create a circular buffer by mapping two adjacent views of the same shared memory section. /// Scenario 2. Specify a preferred NUMA node when allocating memory. /// Scenario 3. Allocate memory in a specific virtual address range (below 4GB, in this example) and with specific alignment. /// // https://docs.microsoft.com/en-us/windows/desktop/api/memoryapi/nf-memoryapi-virtualalloc2 PVOID VirtualAlloc2( HANDLE Process, // PVOID BaseAddress, SIZE_T Size, ULONG AllocationType, ULONG PageProtection, MEM_EXTENDED_PARAMETER *ExtendedParameters, ULONG // ParameterCount ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("memoryapi.h", MSDNShortId = "5021062F-E414-49A1-8B70-BE2A57A90E54")] public static extern IntPtr VirtualAlloc2(SafeHANDLE Process, IntPtr BaseAddress, SizeT Size, MEM_ALLOCATION_TYPE AllocationType, MEM_PROTECTION PageProtection, MEM_EXTENDED_PARAMETER[] ExtendedParameters, uint ParameterCount); /// /// /// Reserves, commits, or changes the state of a region of pages in the virtual address space of the calling process. Memory /// allocated by this function is automatically initialized to zero. /// /// /// Using this function, you can: for new allocations, specify a range of virtual address space and a power-of-2 alignment /// restriction; specify an arbitrary number of extended parameters; specify a preferred NUMA node for the physical memory as an /// extended parameter; and specify a placeholder operation (specifically, replacement). /// /// To specify the NUMA node, see the ExtendedParameters parameter. /// /// /// The handle to a process. The function allocates memory within the virtual address space of this process. /// /// The handle must have the PROCESS_VM_OPERATION access right. For more information, see Process Security and Access Rights. /// /// /// /// The pointer that specifies a desired starting address for the region of pages that you want to allocate. /// /// If an explicit base address is specified, then it must be a multiple of the system allocation granularity. To determine the size /// of a page and the allocation granularity on the host computer, use the GetSystemInfo function. /// /// If BaseAddress is NULL, the function determines where to allocate the region. /// /// /// The size of the region of memory to allocate, in bytes. /// The size must always be a multiple of the page size. /// /// If BaseAddress is not NULL, the function allocates all pages that contain one or more bytes in the range from BaseAddress /// to BaseAddress+Size. This means, for example, that a 2-byte range that straddles a page boundary causes the function to allocate /// both pages. /// /// /// /// The type of memory allocation. This parameter must contain one of the following values. /// /// /// Value /// Meaning /// /// /// MEM_COMMIT 0x00001000 /// /// Allocates memory charges (from the overall size of memory and the paging files on disk) for the specified reserved memory pages. /// The function also guarantees that when the caller later initially accesses the memory, the contents will be zero. Actual physical /// pages are not allocated unless/until the virtual addresses are actually accessed. To reserve and commit pages in one step, call /// Virtual2AllocFromApp with . Attempting to commit a specific address range by specifying MEM_COMMIT without MEM_RESERVE and a /// non-NULL BaseAddress fails unless the entire range has already been reserved. The resulting error code is ERROR_INVALID_ADDRESS. /// An attempt to commit a page that is already committed does not cause the function to fail. This means that you can commit pages /// without first determining the current commitment state of each page. /// /// /// /// MEM_RESERVE 0x00002000 /// /// Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging /// file on disk. You can commit reserved pages in subsequent calls to the Virtual2AllocFromApp function. To reserve and commit pages /// in one step, call Virtual2AllocFromApp with MEM_COMMIT | MEM_RESERVE. Other memory allocation functions, such as malloc and /// LocalAlloc, cannot use a reserved range of memory until it is released. /// /// /// /// MEM_REPLACE_PLACEHOLDER 0x00004000 /// /// Replaces a placeholder with a normal private allocation. Only data/pf-backed section views are supported (no images, physical /// memory, etc.). When you replace a placeholder, BaseAddress and Size must exactly match those of the placeholder. After you /// replace a placeholder with a private allocation, to free that allocation back to a placeholder, see the dwFreeType parameter of /// VirtualFree and VirtualFreeEx. A placeholder is a type of reserved memory region. /// /// /// /// MEM_RESERVE_PLACEHOLDER 0x00040000 /// /// To create a placeholder, call VirtualAlloc2 with and PageProtection set to PAGE_NOACCESS. To free/split/coalesce a placeholder, /// see the dwFreeType parameter of VirtualFree and VirtualFreeEx. A placeholder is a type of reserved memory region. /// /// /// /// MEM_RESET 0x00080000 /// /// Indicates that data in the memory range specified by BaseAddress and Size is no longer of interest. The pages should not be read /// from or written to the paging file. However, the memory block will be used again later, so it should not be decommitted. This /// value cannot be used with any other value. Using this value does not guarantee that the range operated on with MEM_RESET will /// contain zeros. If you want the range to contain zeros, decommit the memory and then recommit it. When you specify MEM_RESET, the /// Virtual2AllocFromApp function ignores the value of Protection. However, you must still set Protection to a valid protection /// value, such as PAGE_NOACCESS. Virtual2AllocFromApp returns an error if you use MEM_RESET and the range of memory is mapped to a /// file. A shared view is only acceptable if it is mapped to a paging file. /// /// /// /// MEM_RESET_UNDO 0x1000000 /// /// MEM_RESET_UNDO should only be called on an address range to which MEM_RESET was successfully applied earlier. It indicates that /// the data in the specified memory range specified by BaseAddress and Size is of interest to the caller and attempts to reverse the /// effects of MEM_RESET. If the function succeeds, that means all data in the specified address range is intact. If the function /// fails, at least some of the data in the address range has been replaced with zeroes. This value cannot be used with any other /// value. If MEM_RESET_UNDO is called on an address range which was not MEM_RESET earlier, the behavior is undefined. When you /// specify MEM_RESET, the Virtual2AllocFromApp function ignores the value of Protection. However, you must still set Protection to a /// valid protection value, such as PAGE_NOACCESS. /// /// /// /// This parameter can also specify the following values as indicated. /// /// /// Value /// Meaning /// /// /// MEM_LARGE_PAGES 0x20000000 /// /// Allocates memory using large page support. The size and alignment must be a multiple of the large-page minimum. To obtain this /// value, use the GetLargePageMinimum function. If you specify this value, you must also specify MEM_RESERVE and MEM_COMMIT. /// /// /// /// MEM_PHYSICAL 0x00400000 /// /// Reserves an address range that can be used to map Address Windowing Extensions (AWE) pages. This value must be used with /// MEM_RESERVE and no other values. /// /// /// /// MEM_TOP_DOWN 0x00100000 /// /// Allocates memory at the highest possible address. This can be slower than regular allocations, especially when there are many allocations. /// /// /// /// MEM_WRITE_WATCH 0x00200000 /// /// Causes the system to track pages that are written to in the allocated region. If you specify this value, you must also specify /// MEM_RESERVE. To retrieve the addresses of the pages that have been written to since the region was allocated or the /// write-tracking state was reset, call the GetWriteWatch function. To reset the write-tracking state, call GetWriteWatch or /// ResetWriteWatch. The write-tracking feature remains enabled for the memory region until the region is freed. /// /// /// /// /// /// /// The memory protection for the region of pages to be allocated. If the pages are being committed, you can specify one of the /// memory protection constants. The following constants generate an error: /// /// /// /// PAGE_EXECUTE /// /// /// PAGE_EXECUTE_READ /// /// /// PAGE_EXECUTE_READWRITE /// /// /// PAGE_EXECUTE_WRITECOPY /// /// /// /// /// /// An optional pointer to one or more extended parameters of type MEM_EXTENDED_PARAMETER. Each of those extended parameter values /// can itself have a Type field of either MemExtendedParameterAddressRequirements or MemExtendedParameterNumaNode. If /// no MemExtendedParameterNumaNode extended parameter is provided, then the behavior is the same as for the /// VirtualAlloc/MapViewOfFile functions (that is, the preferred NUMA node for the physical pages is determined based on the ideal /// processor of the thread that first accesses the memory). /// /// /// /// The number of extended parameters pointed to by ExtendedParameters. /// /// /// If the function succeeds, the return value is the base address of the allocated region of pages. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// /// /// /// This API helps support high-performance games, and server applications, which have particular requirements around managing their /// virtual address space. For example, mapping memory on top of a previously reserved region; this is useful for implementing an /// automatically wrapping ring buffer. And allocating memory with specific alignment; for example, to enable your application to /// commit large/huge page-mapped regions on demand. /// /// /// You can call Virtual2AllocFromApp from Windows Store apps with just-in-time (JIT) capabilities to use JIT functionality. /// The app must include the codeGeneration capability in the app manifest file to use JIT capabilities. /// /// Each page has an associated page state. The Virtual2AllocFromApp function can perform the following operations: /// /// /// Commit a region of reserved pages /// /// /// Reserve a region of free pages /// /// /// Simultaneously reserve and commit a region of free pages /// /// /// /// Virtual2AllocFromApp cannot reserve a reserved page. It can commit a page that is already committed. This means you can /// commit a range of pages, regardless of whether they have already been committed, and the function will not fail. /// /// /// You can use Virtual2AllocFromApp to reserve a block of pages and then make additional calls to Virtual2AllocFromApp /// to commit individual pages from the reserved block. This enables a process to reserve a range of its virtual address space /// without consuming physical storage until it is needed. /// /// /// If the BaseAddress parameter is not NULL, the function uses the BaseAddress and Size parameters to compute the region of /// pages to be allocated. The current state of the entire range of pages must be compatible with the type of allocation specified by /// the AllocationType parameter. Otherwise, the function fails and none of the pages are allocated. This compatibility requirement /// does not preclude committing an already committed page, as mentioned previously. /// /// Virtual2AllocFromApp does not allow the creation of executable pages. /// /// The Virtual2AllocFromApp function can be used to reserve an Address Windowing Extensions (AWE) region of memory within the /// virtual address space of a specified process. This region of memory can then be used to map physical pages into and out of /// virtual memory as required by the application. The MEM_PHYSICAL and MEM_RESERVE values must be set in the /// AllocationType parameter. The MEM_COMMIT value must not be set. The page protection must be set to PAGE_READWRITE. /// /// /// The VirtualFree function can decommit a committed page, releasing the page's storage, or it can simultaneously decommit and /// release a committed page. It can also release a reserved page, making it a free page. /// /// /// When creating a region that will be executable, the calling program bears responsibility for ensuring cache coherency via an /// appropriate call to FlushInstructionCache once the code has been set in place. Otherwise attempts to execute code out of the /// newly executable region may produce unpredictable results. /// /// Examples /// For code examples, see Virtual2Alloc. /// // https://docs.microsoft.com/en-us/windows/desktop/api/memoryapi/nf-memoryapi-virtualalloc2fromapp PVOID VirtualAlloc2FromApp( // HANDLE Process, PVOID BaseAddress, SIZE_T Size, ULONG AllocationType, ULONG PageProtection, MEM_EXTENDED_PARAMETER // *ExtendedParameters, ULONG ParameterCount ); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("memoryapi.h", MSDNShortId = "84896A75-A917-4CA1-A417-650428E1FBFD")] public static extern IntPtr VirtualAlloc2FromApp(SafeHANDLE Process, IntPtr BaseAddress, SizeT Size, MEM_ALLOCATION_TYPE AllocationType, MEM_PROTECTION PageProtection, MEM_EXTENDED_PARAMETER[] ExtendedParameters, uint ParameterCount); /// /// /// Reserves, commits, or changes the state of a region of memory within the virtual address space of a specified process. The /// function initializes the memory it allocates to zero. /// /// To specify the NUMA node for the physical memory, see VirtualAllocExNuma. /// /// /// The handle to a process. The function allocates memory within the virtual address space of this process. /// /// The handle must have the PROCESS_VM_OPERATION access right. For more information, see Process Security and Access Rights. /// /// /// /// The pointer that specifies a desired starting address for the region of pages that you want to allocate. /// If you are reserving memory, the function rounds this address down to the nearest multiple of the allocation granularity. /// /// If you are committing memory that is already reserved, the function rounds this address down to the nearest page boundary. To /// determine the size of a page and the allocation granularity on the host computer, use the GetSystemInfo function. /// /// If lpAddress is NULL, the function determines where to allocate the region. /// /// If this address is within an enclave that you have not initialized by calling InitializeEnclave, VirtualAllocEx /// allocates a page of zeros for the enclave at that address. The page must be previously uncommitted, and will not be measured with /// the EEXTEND instruction of the Intel Software Guard Extensions programming model. /// /// /// If the address in within an enclave that you initialized, then the allocation operation fails with the /// ERROR_INVALID_ADDRESS error. /// /// /// /// The size of the region of memory to allocate, in bytes. /// If lpAddress is NULL, the function rounds dwSize up to the next page boundary. /// /// If lpAddress is not NULL, the function allocates all pages that contain one or more bytes in the range from lpAddress to /// lpAddress+dwSize. This means, for example, that a 2-byte range that straddles a page boundary causes the function to allocate /// both pages. /// /// /// /// The type of memory allocation. This parameter must contain one of the following values. /// /// /// /// Value /// Meaning /// /// /// MEM_COMMIT0x00001000 /// /// Allocates memory charges (from the overall size of memory and the paging files on disk) for the specified reserved memory pages. /// The function also guarantees that when the caller later initially accesses the memory, the contents will be zero. Actual physical /// pages are not allocated unless/until the virtual addresses are actually accessed.To reserve and commit pages in one step, call /// VirtualAllocEx with .Attempting to commit a specific address range by specifying MEM_COMMIT without MEM_RESERVE and a non-NULL /// lpAddress fails unless the entire range has already been reserved. The resulting error code is ERROR_INVALID_ADDRESS.An attempt /// to commit a page that is already committed does not cause the function to fail. This means that you can commit pages without /// first determining the current commitment state of each page.If lpAddress specifies an address within an enclave, flAllocationType /// must be MEM_COMMIT. /// /// /// /// MEM_RESERVE0x00002000 /// /// Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging /// file on disk.You commit reserved pages by calling VirtualAllocEx again with MEM_COMMIT. To reserve and commit pages in one step, /// call VirtualAllocEx with .Other memory allocation functions, such as malloc and LocalAlloc, cannot use reserved memory until it /// has been released. /// /// /// /// MEM_RESET0x00080000 /// /// Indicates that data in the memory range specified by lpAddress and dwSize is no longer of interest. The pages should not be read /// from or written to the paging file. However, the memory block will be used again later, so it should not be decommitted. This /// value cannot be used with any other value.Using this value does not guarantee that the range operated on with MEM_RESET will /// contain zeros. If you want the range to contain zeros, decommit the memory and then recommit it.When you use MEM_RESET, the /// VirtualAllocEx function ignores the value of fProtect. However, you must still set fProtect to a valid protection value, such as /// PAGE_NOACCESS.VirtualAllocEx returns an error if you use MEM_RESET and the range of memory is mapped to a file. A shared view is /// only acceptable if it is mapped to a paging file. /// /// /// /// MEM_RESET_UNDO0x1000000 /// /// MEM_RESET_UNDO should only be called on an address range to which MEM_RESET was successfully applied earlier. It indicates that /// the data in the specified memory range specified by lpAddress and dwSize is of interest to the caller and attempts to reverse the /// effects of MEM_RESET. If the function succeeds, that means all data in the specified address range is intact. If the function /// fails, at least some of the data in the address range has been replaced with zeroes.This value cannot be used with any other /// value. If MEM_RESET_UNDO is called on an address range which was not MEM_RESET earlier, the behavior is undefined. When you /// specify MEM_RESET, the VirtualAllocEx function ignores the value of flProtect. However, you must still set flProtect to a valid /// protection value, such as PAGE_NOACCESS.Windows Server 2008 R2, Windows 7, Windows Server 2008, Windows Vista, Windows Server /// 2003 and Windows XP: The MEM_RESET_UNDO flag is not supported until Windows 8 and Windows Server 2012. /// /// /// /// /// This parameter can also specify the following values as indicated. /// /// /// /// Value /// Meaning /// /// /// MEM_LARGE_PAGES0x20000000 /// /// Allocates memory using large page support.The size and alignment must be a multiple of the large-page minimum. To obtain this /// value, use the GetLargePageMinimum function.If you specify this value, you must also specify MEM_RESERVE and MEM_COMMIT. /// /// /// /// MEM_PHYSICAL0x00400000 /// /// Reserves an address range that can be used to map Address Windowing Extensions (AWE) pages.This value must be used with /// MEM_RESERVE and no other values. /// /// /// /// MEM_TOP_DOWN0x00100000 /// /// Allocates memory at the highest possible address. This can be slower than regular allocations, especially when there are many allocations. /// /// /// /// /// /// /// /// The memory protection for the region of pages to be allocated. If the pages are being committed, you can specify any one of the /// memory protection constants. /// /// If lpAddress specifies an address within an enclave, flProtect cannot be any of the following values: /// /// /// If the function succeeds, the return value is the base address of the allocated region of pages. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// // LPVOID WINAPI VirtualAllocEx( _In_ HANDLE hProcess, _In_opt_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD flAllocationType, // _In_ DWORD flProtect); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366890")] public static extern IntPtr VirtualAllocEx([In] HPROCESS hProcess, [In] IntPtr lpAddress, SizeT dwSize, MEM_ALLOCATION_TYPE flAllocationType, MEM_PROTECTION flProtect); /// /// Reserves, commits, or changes the state of a region of memory within the virtual address space of the specified process, and /// specifies the NUMA node for the physical memory. /// /// /// The handle to a process. The function allocates memory within the virtual address space of this process. /// /// The handle must have the PROCESS_VM_OPERATION access right. For more information, see Process Security and Access Rights. /// /// /// /// The pointer that specifies a desired starting address for the region of pages that you want to allocate. /// If you are reserving memory, the function rounds this address down to the nearest multiple of the allocation granularity. /// /// If you are committing memory that is already reserved, the function rounds this address down to the nearest page boundary. To /// determine the size of a page and the allocation granularity on the host computer, use the GetSystemInfo function. /// /// If lpAddress is NULL, the function determines where to allocate the region. /// /// /// The size of the region of memory to be allocated, in bytes. /// If lpAddress is NULL, the function rounds dwSize up to the next page boundary. /// /// If lpAddress is not NULL, the function allocates all pages that contain one or more bytes in the range from lpAddress to . /// This means, for example, that a 2-byte range that straddles a page boundary causes the function to allocate both pages. /// /// /// /// The type of memory allocation. This parameter must contain one of the following values. /// /// /// /// Value /// Meaning /// /// /// MEM_COMMIT0x00001000 /// /// Allocates memory charges (from the overall size of memory and the paging files on disk) for the specified reserved memory pages. /// The function also guarantees that when the caller later initially accesses the memory, the contents will be zero. Actual physical /// pages are not allocated unless/until the virtual addresses are actually accessed.To reserve and commit pages in one step, call /// the function with .Attempting to commit a specific address range by specifying MEM_COMMIT without MEM_RESERVE and a non-NULL /// lpAddress fails unless the entire range has already been reserved. The resulting error code is ERROR_INVALID_ADDRESS.An attempt /// to commit a page that is already committed does not cause the function to fail. This means that you can commit pages without /// first determining the current commitment state of each page. /// /// /// /// MEM_RESERVE0x00002000 /// /// Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging /// file on disk.You commit reserved pages by calling the function again with MEM_COMMIT. To reserve and commit pages in one step, /// call the function with .Other memory allocation functions, such as malloc and LocalAlloc, cannot use reserved memory until it has /// been released. /// /// /// /// MEM_RESET0x00080000 /// /// Indicates that data in the memory range specified by lpAddress and dwSize is no longer of interest. The pages should not be read /// from or written to the paging file. However, the memory block will be used again later, so it should not be decommitted. This /// value cannot be used with any other value.Using this value does not guarantee that the range operated on with MEM_RESET will /// contain zeros. If you want the range to contain zeros, decommit the memory and then recommit it.When you use MEM_RESET, the /// function ignores the value of fProtect. However, you must still set fProtect to a valid protection value, such as /// PAGE_NOACCESS.The function returns an error if you use MEM_RESET and the range of memory is mapped to a file. A shared view is /// only acceptable if it is mapped to a paging file. /// /// /// /// MEM_RESET_UNDO0x1000000 /// /// MEM_RESET_UNDO should only be called on an address range to which MEM_RESET was successfully applied earlier. It indicates that /// the data in the specified memory range specified by lpAddress and dwSize is of interest to the caller and attempts to reverse the /// effects of MEM_RESET. If the function succeeds, that means all data in the specified address range is intact. If the function /// fails, at least some of the data in the address range has been replaced with zeroes.This value cannot be used with any other /// value. If MEM_RESET_UNDO is called on an address range which was not MEM_RESET earlier, the behavior is undefined. When you /// specify MEM_RESET, the VirtualAllocExNuma function ignores the value of flProtect. However, you must still set flProtect to a /// valid protection value, such as PAGE_NOACCESS.Windows Server 2008 R2, Windows 7, Windows Server 2008 and Windows /// Vista: The MEM_RESET_UNDO flag is not supported until Windows 8 and Windows Server 2012. /// /// /// /// /// This parameter can also specify the following values as indicated. /// /// /// /// Value /// Meaning /// /// /// MEM_LARGE_PAGES0x20000000 /// /// Allocates memory using large page support.The size and alignment must be a multiple of the large-page minimum. To obtain this /// value, use the GetLargePageMinimum function.If you specify this value, you must also specify MEM_RESERVE and MEM_COMMIT. /// /// /// /// MEM_PHYSICAL0x00400000 /// /// Reserves an address range that can be used to map Address Windowing Extensions (AWE) pages.This value must be used with /// MEM_RESERVE and no other values. /// /// /// /// MEM_TOP_DOWN0x00100000 /// Allocates memory at the highest possible address. /// /// /// /// /// /// /// The memory protection for the region of pages to be allocated. If the pages are being committed, you can specify any one of the /// memory protection constants. /// /// Protection attributes specified when protecting a page cannot conflict with those specified when allocating a page. /// /// /// The NUMA node where the physical memory should reside. /// /// Used only when allocating a new VA region (either committed or reserved). Otherwise this parameter is ignored when the API is /// used to commit pages in a region that already exists /// /// /// /// If the function succeeds, the return value is the base address of the allocated region of pages. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// // LPVOID WINAPI VirtualAllocExNuma( _In_ HANDLE hProcess, _In_opt_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD // flAllocationType, _In_ DWORD flProtect, _In_ DWORD nndPreferred); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366891")] public static extern IntPtr VirtualAllocExNuma([In] HPROCESS hProcess, [In] IntPtr lpAddress, SizeT dwSize, MEM_ALLOCATION_TYPE flAllocationType, MEM_PROTECTION flProtect, uint nndPreferred); /// /// Reserves, commits, or changes the state of a region of pages in the virtual address space of the calling process. Memory /// allocated by this function is automatically initialized to zero. /// /// /// The starting address of the region to allocate. If the memory is being reserved, the specified address is rounded down to the /// nearest multiple of the allocation granularity. If the memory is already reserved and is being committed, the address is rounded /// down to the next page boundary. To determine the size of a page and the allocation granularity on the host computer, use the /// GetSystemInfo function. If this parameter is NULL, the system determines where to allocate the region. /// /// /// The size of the region, in bytes. If the BaseAddress parameter is NULL, this value is rounded up to the next page /// boundary. Otherwise, the allocated pages include all pages containing one or more bytes in the range from BaseAddress to /// BaseAddress+Size. This means that a 2-byte range straddling a page boundary causes both pages to be included in the allocated region. /// /// /// The type of memory allocation. This parameter must contain one of the following values. /// /// /// /// Value /// Meaning /// /// /// MEM_COMMIT0x00001000 /// /// Allocates memory charges (from the overall size of memory and the paging files on disk) for the specified reserved memory pages. /// The function also guarantees that when the caller later initially accesses the memory, the contents will be zero. Actual physical /// pages are not allocated unless/until the virtual addresses are actually accessed.To reserve and commit pages in one step, call /// VirtualAllocFromApp with .Attempting to commit a specific address range by specifying MEM_COMMIT without MEM_RESERVE and a /// non-NULL BaseAddress fails unless the entire range has already been reserved. The resulting error code is /// ERROR_INVALID_ADDRESS.An attempt to commit a page that is already committed does not cause the function to fail. This means that /// you can commit pages without first determining the current commitment state of each page. /// /// /// /// MEM_RESERVE0x00002000 /// /// Reserves a range of the process's virtual address space without allocating any actual physical storage in memory or in the paging /// file on disk.You can commit reserved pages in subsequent calls to the VirtualAllocFromApp function. To reserve and commit pages /// in one step, call VirtualAllocFromApp with MEM_COMMIT | MEM_RESERVE.Other memory allocation functions, such as malloc and /// LocalAlloc, cannot use a reserved range of memory until it is released. /// /// /// /// MEM_RESET0x00080000 /// /// Indicates that data in the memory range specified by BaseAddress and Size is no longer of interest. The pages should not be read /// from or written to the paging file. However, the memory block will be used again later, so it should not be decommitted. This /// value cannot be used with any other value.Using this value does not guarantee that the range operated on with MEM_RESET will /// contain zeros. If you want the range to contain zeros, decommit the memory and then recommit it.When you specify MEM_RESET, the /// VirtualAllocFromApp function ignores the value of Protection. However, you must still set Protection to a valid protection value, /// such as PAGE_NOACCESS.VirtualAllocFromApp returns an error if you use MEM_RESET and the range of memory is mapped to a file. A /// shared view is only acceptable if it is mapped to a paging file. /// /// /// /// MEM_RESET_UNDO0x1000000 /// /// MEM_RESET_UNDO should only be called on an address range to which MEM_RESET was successfully applied earlier. It indicates that /// the data in the specified memory range specified by BaseAddress and Size is of interest to the caller and attempts to reverse the /// effects of MEM_RESET. If the function succeeds, that means all data in the specified address range is intact. If the function /// fails, at least some of the data in the address range has been replaced with zeroes.This value cannot be used with any other /// value. If MEM_RESET_UNDO is called on an address range which was not MEM_RESET earlier, the behavior is undefined. When you /// specify MEM_RESET, the VirtualAllocFromApp function ignores the value of Protection. However, you must still set Protection to a /// valid protection value, such as PAGE_NOACCESS. /// /// /// /// /// This parameter can also specify the following values as indicated. /// /// /// /// Value /// Meaning /// /// /// MEM_LARGE_PAGES0x20000000 /// /// Allocates memory using large page support.The size and alignment must be a multiple of the large-page minimum. To obtain this /// value, use the GetLargePageMinimum function.If you specify this value, you must also specify MEM_RESERVE and MEM_COMMIT. /// /// /// /// MEM_PHYSICAL0x00400000 /// /// Reserves an address range that can be used to map Address Windowing Extensions (AWE) pages.This value must be used with /// MEM_RESERVE and no other values. /// /// /// /// MEM_TOP_DOWN0x00100000 /// /// Allocates memory at the highest possible address. This can be slower than regular allocations, especially when there are many allocations. /// /// /// /// MEM_WRITE_WATCH0x00200000 /// /// Causes the system to track pages that are written to in the allocated region. If you specify this value, you must also specify /// MEM_RESERVE.To retrieve the addresses of the pages that have been written to since the region was allocated or the write-tracking /// state was reset, call the GetWriteWatch function. To reset the write-tracking state, call GetWriteWatch or ResetWriteWatch. The /// write-tracking feature remains enabled for the memory region until the region is freed. /// /// /// /// /// /// /// The memory protection for the region of pages to be allocated. If the pages are being committed, you can specify one of the /// memory protection constants. The following constants generate an error: /// /// /// If the function succeeds, the return value is the base address of the allocated region of pages. /// If the function fails, the return value is NULL. To get extended error information, call GetLastError. /// // PVOID WINAPI VirtualAllocFromApp( _In_opt_ PVOID BaseAddress, _In_ SIZE_T Size, _In_ ULONG AllocationType, _In_ ULONG Protection); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("MemoryApi.h", MSDNShortId = "mt169845")] public static extern IntPtr VirtualAllocFromApp([In] IntPtr BaseAddress, SizeT Size, MEM_ALLOCATION_TYPE AllocationType, MEM_PROTECTION Protection); /// /// Releases, decommits, or releases and decommits a region of pages within the virtual address space of the calling process. /// To free memory allocated in another process by the VirtualAllocEx function, use the VirtualFreeEx function. /// /// /// A pointer to the base address of the region of pages to be freed. /// /// If the dwFreeType parameter is MEM_RELEASE, this parameter must be the base address returned by the VirtualAlloc /// function when the region of pages is reserved. /// /// /// /// The size of the region of memory to be freed, in bytes. /// /// If the dwFreeType parameter is MEM_RELEASE, this parameter must be 0 (zero). The function frees the entire region that is /// reserved in the initial allocation call to VirtualAlloc. /// /// /// If the dwFreeType parameter is MEM_DECOMMIT, the function decommits all memory pages that contain one or more bytes in the /// range from the lpAddress parameter to . This means, for example, that a 2-byte region of memory that straddles a page boundary /// causes both pages to be decommitted. If lpAddress is the base address returned by VirtualAlloc and dwSize is 0 (zero), the /// function decommits the entire region that is allocated by VirtualAlloc. After that, the entire region is in the reserved state. /// /// /// /// The type of free operation. This parameter can be one of the following values. /// /// /// /// Value /// Meaning /// /// /// MEM_DECOMMIT0x4000 /// /// Decommits the specified region of committed pages. After the operation, the pages are in the reserved state. The function does /// not fail if you attempt to decommit an uncommitted page. This means that you can decommit a range of pages without first /// determining the current commitment state.Do not use this value with MEM_RELEASE.The MEM_DECOMMIT value is not supported when the /// lpAddress parameter provides the base address for an enclave. /// /// /// /// MEM_RELEASE0x8000 /// /// Releases the specified region of pages. After this operation, the pages are in the free state. If you specify this value, dwSize /// must be 0 (zero), and lpAddress must point to the base address returned by the VirtualAlloc function when the region is reserved. /// The function fails if either of these conditions is not met.If any pages in the region are committed currently, the function /// first decommits, and then releases them.The function does not fail if you attempt to release pages that are in different states, /// some reserved and some committed. This means that you can release a range of pages without first determining the current /// commitment state.Do not use this value with MEM_DECOMMIT. /// /// /// /// /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is 0 (zero). To get extended error information, call GetLastError. /// // BOOL WINAPI VirtualFree( _In_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD dwFreeType); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366892")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool VirtualFree([In] IntPtr lpAddress, SizeT dwSize, MEM_ALLOCATION_TYPE dwFreeType); /// /// Releases, decommits, or releases and decommits a region of memory within the virtual address space of a specified process. /// /// /// A handle to a process. The function frees memory within the virtual address space of the process. /// /// The handle must have the PROCESS_VM_OPERATION access right. For more information, see Process Security and Access Rights. /// /// /// /// A pointer to the starting address of the region of memory to be freed. /// /// If the dwFreeType parameter is MEM_RELEASE, lpAddress must be the base address returned by the VirtualAllocEx /// function when the region is reserved. /// /// /// /// The size of the region of memory to free, in bytes. /// /// If the dwFreeType parameter is MEM_RELEASE, dwSize must be 0 (zero). The function frees the entire region that is reserved /// in the initial allocation call to VirtualAllocEx. /// /// /// If dwFreeType is MEM_DECOMMIT, the function decommits all memory pages that contain one or more bytes in the range from /// the lpAddress parameter to . This means, for example, that a 2-byte region of memory that straddles a page boundary causes both /// pages to be decommitted. If lpAddress is the base address returned by VirtualAllocEx and dwSize is 0 (zero), the function /// decommits the entire region that is allocated by VirtualAllocEx. After that, the entire region is in the reserved state. /// /// /// /// The type of free operation. This parameter can be one of the following values. /// /// /// /// Value /// Meaning /// /// /// MEM_DECOMMIT0x4000 /// /// Decommits the specified region of committed pages. After the operation, the pages are in the reserved state. The function does /// not fail if you attempt to decommit an uncommitted page. This means that you can decommit a range of pages without first /// determining their current commitment state.Do not use this value with MEM_RELEASE.The MEM_DECOMMIT value is not supported when /// the lpAddress parameter provides the base address for an enclave. /// /// /// /// MEM_RELEASE0x8000 /// /// Releases the specified region of pages. After the operation, the pages are in the free state. If you specify this value, dwSize /// must be 0 (zero), and lpAddress must point to the base address returned by the VirtualAllocEx function when the region is /// reserved. The function fails if either of these conditions is not met.If any pages in the region are committed currently, the /// function first decommits, and then releases them.The function does not fail if you attempt to release pages that are in different /// states, some reserved and some committed. This means that you can release a range of pages without first determining the current /// commitment state.Do not use this value with MEM_DECOMMIT. /// /// /// /// /// /// /// If the function succeeds, the return value is a nonzero value. /// If the function fails, the return value is 0 (zero). To get extended error information, call GetLastError. /// // BOOL WINAPI VirtualFreeEx( _In_ HANDLE hProcess, _In_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD dwFreeType); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366894")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool VirtualFreeEx([In] HPROCESS hProcess, [In] IntPtr lpAddress, SizeT dwSize, MEM_ALLOCATION_TYPE dwFreeType); /// /// Locks the specified region of the process's virtual address space into physical memory, ensuring that subsequent access to the /// region will not incur a page fault. /// /// A pointer to the base address of the region of pages to be locked. /// /// The size of the region to be locked, in bytes. The region of affected pages includes all pages that contain one or more bytes in /// the range from the lpAddress parameter to . This means that a 2-byte range straddling a page boundary causes both pages to be locked. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI VirtualLock( _In_ LPVOID lpAddress, _In_ SIZE_T dwSize); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366895")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool VirtualLock([In] IntPtr lpAddress, SizeT dwSize); /// /// Changes the protection on a region of committed pages in the virtual address space of the calling process. /// To change the access protection of any process, use the VirtualProtectEx function. /// /// /// /// A pointer an address that describes the starting page of the region of pages whose access protection attributes are to be changed. /// /// /// All pages in the specified region must be within the same reserved region allocated when calling the VirtualAlloc or /// VirtualAllocEx function using MEM_RESERVE. The pages cannot span adjacent reserved regions that were allocated by /// separate calls to VirtualAlloc or VirtualAllocEx using MEM_RESERVE. /// /// /// /// The size of the region whose access protection attributes are to be changed, in bytes. The region of affected pages includes all /// pages containing one or more bytes in the range from the lpAddress parameter to . This means that a 2-byte range straddling a /// page boundary causes the protection attributes of both pages to be changed. /// /// /// The memory protection option. This parameter can be one of the memory protection constants. /// /// For mapped views, this value must be compatible with the access protection specified when the view was mapped (see /// MapViewOfFile, MapViewOfFileEx, and MapViewOfFileExNuma). /// /// /// /// A pointer to a variable that receives the previous access protection value of the first page in the specified region of pages. If /// this parameter is NULL or does not point to a valid variable, the function fails. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI VirtualProtect( _In_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD flNewProtect, _Out_ PDWORD lpflOldProtect); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366898")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool VirtualProtect([In] IntPtr lpAddress, SizeT dwSize, MEM_PROTECTION flNewProtect, [Out] out MEM_PROTECTION lpflOldProtect); /// Changes the protection on a region of committed pages in the virtual address space of a specified process. /// /// A handle to the process whose memory protection is to be changed. The handle must have the PROCESS_VM_OPERATION access /// right. For more information, see Process Security and Access Rights. /// /// /// A pointer to the base address of the region of pages whose access protection attributes are to be changed. /// /// All pages in the specified region must be within the same reserved region allocated when calling the VirtualAlloc or /// VirtualAllocEx function using MEM_RESERVE. The pages cannot span adjacent reserved regions that were allocated by /// separate calls to VirtualAlloc or VirtualAllocEx using MEM_RESERVE. /// /// /// /// The size of the region whose access protection attributes are changed, in bytes. The region of affected pages includes all pages /// containing one or more bytes in the range from the lpAddress parameter to . This means that a 2-byte range straddling a page /// boundary causes the protection attributes of both pages to be changed. /// /// /// The memory protection option. This parameter can be one of the memory protection constants. /// /// For mapped views, this value must be compatible with the access protection specified when the view was mapped (see /// MapViewOfFile, MapViewOfFileEx, and MapViewOfFileExNuma). /// /// /// /// A pointer to a variable that receives the previous access protection of the first page in the specified region of pages. If this /// parameter is NULL or does not point to a valid variable, the function fails. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI VirtualProtectEx( _In_ HANDLE hProcess, _In_ LPVOID lpAddress, _In_ SIZE_T dwSize, _In_ DWORD flNewProtect, _Out_ // PDWORD lpflOldProtect); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366899")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool VirtualProtectEx([In] HPROCESS hProcess, [In] IntPtr lpAddress, SizeT dwSize, MEM_PROTECTION flNewProtect, [Out] out MEM_PROTECTION lpflOldProtect); /// Changes the protection on a region of committed pages in the virtual address space of the calling process. /// /// /// A pointer an address that describes the starting page of the region of pages whose access protection attributes are to be changed. /// /// /// All pages in the specified region must be within the same reserved region allocated when calling the VirtualAlloc, /// VirtualAllocFromApp, or VirtualAllocEx function using MEM_RESERVE. The pages cannot span adjacent reserved /// regions that were allocated by separate calls to VirtualAlloc, VirtualAllocFromApp, or VirtualAllocEx using MEM_RESERVE. /// /// /// /// The size of the region whose access protection attributes are to be changed, in bytes. The region of affected pages includes all /// pages containing one or more bytes in the range from the Address parameter to . This means that a 2-byte range straddling a page /// boundary causes the protection attributes of both pages to be changed. /// /// /// The memory protection option. This parameter can be one of the memory protection constants. /// /// For mapped views, this value must be compatible with the access protection specified when the view was mapped (see /// MapViewOfFile, MapViewOfFileEx, and MapViewOfFileExNuma). /// /// The following constants generate an error: /// The following constants are allowed only for apps that have the codeGeneration capability: /// /// /// A pointer to a variable that receives the previous access protection value of the first page in the specified region of pages. If /// this parameter is NULL or does not point to a valid variable, the function fails. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI VirtualProtectFromApp( _In_ PVOID Address, _In_ SIZE_T Size, _In_ ULONG NewProtection, _Out_ PULONG OldProtection); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("MemoryApi.h", MSDNShortId = "mt169846")] public static extern bool VirtualProtectFromApp([In] IntPtr Address, SizeT Size, MEM_PROTECTION NewProtection, [Out] out MEM_PROTECTION OldProtection); /// /// Retrieves information about a range of pages in the virtual address space of the calling process. /// /// To retrieve information about a range of pages in the address space of another process, use the VirtualQueryEx function. /// /// /// /// /// A pointer to the base address of the region of pages to be queried. This value is rounded down to the next page boundary. To /// determine the size of a page on the host computer, use the GetSystemInfo function. /// /// /// If lpAddress specifies an address above the highest memory address accessible to the process, the function fails with ERROR_INVALID_PARAMETER. /// /// /// /// A pointer to a MEMORY_BASIC_INFORMATION structure in which information about the specified page range is returned. /// /// The size of the buffer pointed to by the lpBuffer parameter, in bytes. /// /// The return value is the actual number of bytes returned in the information buffer. /// /// If the function fails, the return value is zero. To get extended error information, call GetLastError. Possible error /// values include ERROR_INVALID_PARAMETER. /// /// // SIZE_T WINAPI VirtualQuery( _In_opt_ LPCVOID lpAddress, _Out_ PMEMORY_BASIC_INFORMATION lpBuffer, _In_ SIZE_T dwLength); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366902")] public static extern SizeT VirtualQuery([In] IntPtr lpAddress, IntPtr lpBuffer, SizeT dwLength); /// Retrieves information about a range of pages within the virtual address space of a specified process. /// /// A handle to the process whose memory information is queried. The handle must have been opened with the /// PROCESS_QUERY_INFORMATION access right, which enables using the handle to read information from the process object. For /// more information, see Process Security and Access Rights. /// /// /// /// A pointer to the base address of the region of pages to be queried. This value is rounded down to the next page boundary. To /// determine the size of a page on the host computer, use the GetSystemInfo function. /// /// /// If lpAddress specifies an address above the highest memory address accessible to the process, the function fails with ERROR_INVALID_PARAMETER. /// /// /// /// A pointer to a MEMORY_BASIC_INFORMATION structure in which information about the specified page range is returned. /// /// The size of the buffer pointed to by the lpBuffer parameter, in bytes. /// /// The return value is the actual number of bytes returned in the information buffer. /// /// If the function fails, the return value is zero. To get extended error information, call GetLastError. Possible error /// values include ERROR_INVALID_PARAMETER. /// /// // SIZE_T WINAPI VirtualQueryEx( _In_ HANDLE hProcess, _In_opt_ LPCVOID lpAddress, _Out_ PMEMORY_BASIC_INFORMATION lpBuffer, _In_ // SIZE_T dwLength); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366907")] public static extern SizeT VirtualQueryEx([In] HPROCESS hProcess, [In] IntPtr lpAddress, IntPtr lpBuffer, SizeT dwLength); /// /// Unlocks a specified range of pages in the virtual address space of a process, enabling the system to swap the pages out to the /// paging file if necessary. /// /// A pointer to the base address of the region of pages to be unlocked. /// /// The size of the region being unlocked, in bytes. The region of affected pages includes all pages containing one or more bytes in /// the range from the lpAddress parameter to . This means that a 2-byte range straddling a page boundary causes both pages to be unlocked. /// /// /// If the function succeeds, the return value is nonzero. /// If the function fails, the return value is zero. To get extended error information, call GetLastError. /// // BOOL WINAPI VirtualUnlock( _In_ LPVOID lpAddress, _In_ SIZE_T dwSize); https://msdn.microsoft.com/en-us/library/windows/desktop/aa366910(v=vs.85).aspx [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "aa366910")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool VirtualUnlock(IntPtr lpAddress, SizeT dwSize); /// /// Writes data to an area of memory in a specified process. The entire area to be written to must be accessible or the operation fails. /// /// /// A handle to the process memory to be modified. The handle must have PROCESS_VM_WRITE and PROCESS_VM_OPERATION access to the process. /// /// /// A pointer to the base address in the specified process to which data is written. Before data transfer occurs, the system verifies /// that all data in the base address and memory of the specified size is accessible for write access, and if it is not accessible, /// the function fails. /// /// A pointer to the buffer that contains data to be written in the address space of the specified process. /// The number of bytes to be written to the specified process. /// /// A pointer to a variable that receives the number of bytes transferred into the specified process. This parameter is optional. If /// lpNumberOfBytesWritten is NULL, the parameter is ignored. /// /// /// If the function succeeds, the return value is nonzero. /// /// If the function fails, the return value is 0 (zero). To get extended error information, call GetLastError. The function /// fails if the requested write operation crosses into an area of the process that is inaccessible. /// /// // BOOL WINAPI WriteProcessMemory( _In_ HANDLE hProcess, _In_ LPVOID lpBaseAddress, _In_ LPCVOID lpBuffer, _In_ SIZE_T nSize, _Out_ // SIZE_T *lpNumberOfBytesWritten); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms681674")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WriteProcessMemory([In] HPROCESS hProcess, [In] IntPtr lpBaseAddress, [In] IntPtr lpBuffer, SizeT nSize, out SizeT lpNumberOfBytesWritten); /// /// Writes data to an area of memory in a specified process. The entire area to be written to must be accessible or the operation fails. /// /// /// A handle to the process memory to be modified. The handle must have PROCESS_VM_WRITE and PROCESS_VM_OPERATION access to the process. /// /// /// A pointer to the base address in the specified process to which data is written. Before data transfer occurs, the system verifies /// that all data in the base address and memory of the specified size is accessible for write access, and if it is not accessible, /// the function fails. /// /// A pointer to the buffer that contains data to be written in the address space of the specified process. /// The number of bytes to be written to the specified process. /// /// A pointer to a variable that receives the number of bytes transferred into the specified process. This parameter is optional. If /// lpNumberOfBytesWritten is NULL, the parameter is ignored. /// /// /// If the function succeeds, the return value is nonzero. /// /// If the function fails, the return value is 0 (zero). To get extended error information, call GetLastError. The function /// fails if the requested write operation crosses into an area of the process that is inaccessible. /// /// // BOOL WINAPI WriteProcessMemory( _In_ HANDLE hProcess, _In_ LPVOID lpBaseAddress, _In_ LPCVOID lpBuffer, _In_ SIZE_T nSize, _Out_ // SIZE_T *lpNumberOfBytesWritten); [DllImport(Lib.Kernel32, SetLastError = true, ExactSpelling = true)] [PInvokeData("WinBase.h", MSDNShortId = "ms681674")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WriteProcessMemory([In] HPROCESS hProcess, [In] IntPtr lpBaseAddress, [In] byte[] lpBuffer, SizeT nSize, out SizeT lpNumberOfBytesWritten); /// Represents information about call targets for Control Flow Guard (CFG). // typedef struct _CFG_CALL_TARGET_INFO { ULONG_PTR Offset; ULONG_PTR Flags;} CFG_CALL_TARGET_INFO, *PCFG_CALL_TARGET_INFO; [PInvokeData("Ntmmapi.h", MSDNShortId = "mt219054")] public struct CFG_CALL_TARGET_INFO { /// /// Flags describing the operation to be performed on the address. If CFG_CALL_TARGET_VALID is set, then the address will /// be marked valid for CFG. Otherwise, it will be marked an invalid call target. /// public UIntPtr Flags; /// Offset relative to a provided (start) virtual address. This offset should be 16 byte aligned. public UIntPtr Offset; } /// /// /// Specifies a lowest and highest base address and alignment as part of an extended parameter to a function that manages virtual memory. /// /// /// /// Specifying a MEM_ADDRESS_REQUIREMENTS structure with all fields set to 0 is the same as not specifying one at all. /// // https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-_mem_address_requirements typedef struct // _MEM_ADDRESS_REQUIREMENTS { PVOID LowestStartingAddress; PVOID HighestEndingAddress; SIZE_T Alignment; } MEM_ADDRESS_REQUIREMENTS, *PMEM_ADDRESS_REQUIREMENTS; [PInvokeData("winnt.h", MSDNShortId = "1CAB4942-F0D2-4A60-9472-4EDF2FC9FA7A")] [StructLayout(LayoutKind.Sequential)] public struct MEM_ADDRESS_REQUIREMENTS { /// /// /// Specifies the lowest acceptable address. Calling VirtualAlloc2 or MapViewOfFile3, and specifying NULL for /// LowestStartingAddress, gives the same behavior as calling VirtualAlloc/MapViewOfFile. /// /// public IntPtr LowestStartingAddress; /// /// /// Specifies the highest acceptable address (inclusive). This address must not exceed lpMaximumApplicationAddress /// returned by GetSystemInfo. Calling VirtualAlloc2 or MapViewOfFile3, and specifying NULL for HighestEndingAddress, /// gives the same behavior as calling VirtualAlloc/MapViewOfFile. /// /// public IntPtr HighestEndingAddress; /// /// Specifies power-of-2 alignment. Specifying 0 aligns the returned address on the system allocation granularity. /// public SizeT Alignment; } /// Represents an extended parameter for a function that manages virtual memory. // https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-mem_extended_parameter typedef struct MEM_EXTENDED_PARAMETER { // struct { DWORD64 Type : MEM_EXTENDED_PARAMETER_TYPE_BITS; DWORD64 Reserved : 64 - MEM_EXTENDED_PARAMETER_TYPE_BITS; } // DUMMYSTRUCTNAME; union { DWORD64 ULong64; PVOID Pointer; SIZE_T Size; HANDLE Handle; DWORD ULong; } DUMMYUNIONNAME; } // MEM_EXTENDED_PARAMETER, *PMEM_EXTENDED_PARAMETER; [PInvokeData("winnt.h", MSDNShortId = "8D189F7E-83E7-4AF3-9E25-928C66666887")] [StructLayout(LayoutKind.Explicit, Pack = 8, Size = 16)] public struct MEM_EXTENDED_PARAMETER { /// /// A MEM_EXTENDED_PARAMETER_TYPE value that indicates the type of the parameter. /// /// If Type is set to MemExtendedParameterAddressRequirements, then Pointer must be a pointer to a caller-allocated /// structure that specifies the lowest and highest base address and alignment. /// /// If Type is set to MemExtendedParameterNumaNode, then ULong must be set to the desired node number. /// [FieldOffset(0)] public MEM_EXTENDED_PARAMETER_TYPE Type; /// A ULONGLONG value. [FieldOffset(8)] public ulong ULong64; /// /// If Type is set to MemExtendedParameterAddressRequirements, then Pointer must be a pointer to a caller-allocated /// MEM_ADDRESS_REQUIREMENTS structure that specifies the lowest and highest base address and alignment. /// [FieldOffset(8)] public IntPtr Pointer; /// A SIZE_T value. [FieldOffset(8)] public SizeT Size; /// A HANDLE value. [FieldOffset(8)] public IntPtr Handle; /// If Type is set to MemExtendedParameterNumaNode, then ULong must be set to the desired node number. [FieldOffset(8)] public uint ULong; } /// Specifies a range of memory. This structure is used by the PrefetchVirtualMemory function. // typedef struct _WIN32_MEMORY_RANGE_ENTRY { PVOID VirtualAddress; SIZE_T NumberOfBytes;} WIN32_MEMORY_RANGE_ENTRY, *PWIN32_MEMORY_RANGE_ENTRY; [PInvokeData("WinBase.h", MSDNShortId = "hh780544")] public struct WIN32_MEMORY_RANGE_ENTRY { /// public SizeT NumberOfBytes; /// public IntPtr VirtualAddress; } /// Provides a for that is disposed using . public class SafeHSECTION : SafeKernelHandle { /// Initializes a new instance of the class and assigns an existing handle. /// An object that represents the pre-existing handle to use. /// to reliably release the handle during the finalization phase; otherwise, (not recommended). public SafeHSECTION(IntPtr preexistingHandle, bool ownsHandle = true) : base(preexistingHandle, ownsHandle) { } /// Initializes a new instance of the class. private SafeHSECTION() : base() { } /// Performs an implicit conversion from to . /// The safe handle instance. /// The result of the conversion. public static implicit operator HSECTION(SafeHSECTION h) => h.handle; } /// /// Provides a to a memory resource notification object that releases its instance at disposal using CloseHandle. /// public class SafeMemoryResourceNotification : SafeSyncHandle { /// /// Initializes a new instance of the class and assigns an existing handle. /// /// An object that represents the pre-existing handle to use. /// /// to reliably release the handle during the finalization phase; otherwise, (not recommended). /// public SafeMemoryResourceNotification(IntPtr preexistingHandle, bool ownsHandle = true) : base(preexistingHandle, ownsHandle) { } } } }