vm_manager.h 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. // Copyright 2015 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <map>
  6. #include <memory>
  7. #include <tuple>
  8. #include <vector>
  9. #include "common/common_types.h"
  10. #include "common/memory_hook.h"
  11. #include "common/page_table.h"
  12. #include "core/hle/result.h"
  13. #include "core/memory.h"
  14. namespace Core {
  15. class System;
  16. }
  17. namespace FileSys {
  18. enum class ProgramAddressSpaceType : u8;
  19. }
  20. namespace Kernel {
  21. enum class VMAType : u8 {
  22. /// VMA represents an unmapped region of the address space.
  23. Free,
  24. /// VMA is backed by a ref-counted allocate memory block.
  25. AllocatedMemoryBlock,
  26. /// VMA is backed by a raw, unmanaged pointer.
  27. BackingMemory,
  28. /// VMA is mapped to MMIO registers at a fixed PAddr.
  29. MMIO,
  30. // TODO(yuriks): Implement MemoryAlias to support MAP/UNMAP
  31. };
  32. /// Permissions for mapped memory blocks
  33. enum class VMAPermission : u8 {
  34. None = 0,
  35. Read = 1,
  36. Write = 2,
  37. Execute = 4,
  38. ReadWrite = Read | Write,
  39. ReadExecute = Read | Execute,
  40. WriteExecute = Write | Execute,
  41. ReadWriteExecute = Read | Write | Execute,
  42. // Used as a wildcard when checking permissions across memory ranges
  43. All = 0xFF,
  44. };
  45. constexpr VMAPermission operator|(VMAPermission lhs, VMAPermission rhs) {
  46. return static_cast<VMAPermission>(u32(lhs) | u32(rhs));
  47. }
  48. constexpr VMAPermission operator&(VMAPermission lhs, VMAPermission rhs) {
  49. return static_cast<VMAPermission>(u32(lhs) & u32(rhs));
  50. }
  51. constexpr VMAPermission operator^(VMAPermission lhs, VMAPermission rhs) {
  52. return static_cast<VMAPermission>(u32(lhs) ^ u32(rhs));
  53. }
  54. constexpr VMAPermission operator~(VMAPermission permission) {
  55. return static_cast<VMAPermission>(~u32(permission));
  56. }
  57. constexpr VMAPermission& operator|=(VMAPermission& lhs, VMAPermission rhs) {
  58. lhs = lhs | rhs;
  59. return lhs;
  60. }
  61. constexpr VMAPermission& operator&=(VMAPermission& lhs, VMAPermission rhs) {
  62. lhs = lhs & rhs;
  63. return lhs;
  64. }
  65. constexpr VMAPermission& operator^=(VMAPermission& lhs, VMAPermission rhs) {
  66. lhs = lhs ^ rhs;
  67. return lhs;
  68. }
  69. /// Attribute flags that can be applied to a VMA
  70. enum class MemoryAttribute : u32 {
  71. Mask = 0xFF,
  72. /// No particular qualities
  73. None = 0,
  74. /// Memory locked/borrowed for use. e.g. This would be used by transfer memory.
  75. Locked = 1,
  76. /// Memory locked for use by IPC-related internals.
  77. LockedForIPC = 2,
  78. /// Mapped as part of the device address space.
  79. DeviceMapped = 4,
  80. /// Uncached memory
  81. Uncached = 8,
  82. };
  83. constexpr MemoryAttribute operator|(MemoryAttribute lhs, MemoryAttribute rhs) {
  84. return static_cast<MemoryAttribute>(u32(lhs) | u32(rhs));
  85. }
  86. constexpr MemoryAttribute operator&(MemoryAttribute lhs, MemoryAttribute rhs) {
  87. return static_cast<MemoryAttribute>(u32(lhs) & u32(rhs));
  88. }
  89. constexpr MemoryAttribute operator^(MemoryAttribute lhs, MemoryAttribute rhs) {
  90. return static_cast<MemoryAttribute>(u32(lhs) ^ u32(rhs));
  91. }
  92. constexpr MemoryAttribute operator~(MemoryAttribute attribute) {
  93. return static_cast<MemoryAttribute>(~u32(attribute));
  94. }
  95. constexpr MemoryAttribute& operator|=(MemoryAttribute& lhs, MemoryAttribute rhs) {
  96. lhs = lhs | rhs;
  97. return lhs;
  98. }
  99. constexpr MemoryAttribute& operator&=(MemoryAttribute& lhs, MemoryAttribute rhs) {
  100. lhs = lhs & rhs;
  101. return lhs;
  102. }
  103. constexpr MemoryAttribute& operator^=(MemoryAttribute& lhs, MemoryAttribute rhs) {
  104. lhs = lhs ^ rhs;
  105. return lhs;
  106. }
  107. constexpr u32 ToSvcMemoryAttribute(MemoryAttribute attribute) {
  108. return static_cast<u32>(attribute & MemoryAttribute::Mask);
  109. }
  110. // clang-format off
  111. /// Represents memory states and any relevant flags, as used by the kernel.
  112. /// svcQueryMemory interprets these by masking away all but the first eight
  113. /// bits when storing memory state into a MemoryInfo instance.
  114. enum class MemoryState : u32 {
  115. Mask = 0xFF,
  116. FlagProtect = 1U << 8,
  117. FlagDebug = 1U << 9,
  118. FlagIPC0 = 1U << 10,
  119. FlagIPC3 = 1U << 11,
  120. FlagIPC1 = 1U << 12,
  121. FlagMapped = 1U << 13,
  122. FlagCode = 1U << 14,
  123. FlagAlias = 1U << 15,
  124. FlagModule = 1U << 16,
  125. FlagTransfer = 1U << 17,
  126. FlagQueryPhysicalAddressAllowed = 1U << 18,
  127. FlagSharedDevice = 1U << 19,
  128. FlagSharedDeviceAligned = 1U << 20,
  129. FlagIPCBuffer = 1U << 21,
  130. FlagMemoryPoolAllocated = 1U << 22,
  131. FlagMapProcess = 1U << 23,
  132. FlagUncached = 1U << 24,
  133. FlagCodeMemory = 1U << 25,
  134. // Wildcard used in range checking to indicate all states.
  135. All = 0xFFFFFFFF,
  136. // Convenience flag sets to reduce repetition
  137. IPCFlags = FlagIPC0 | FlagIPC3 | FlagIPC1,
  138. CodeFlags = FlagDebug | IPCFlags | FlagMapped | FlagCode | FlagQueryPhysicalAddressAllowed |
  139. FlagSharedDevice | FlagSharedDeviceAligned | FlagMemoryPoolAllocated,
  140. DataFlags = FlagProtect | IPCFlags | FlagMapped | FlagAlias | FlagTransfer |
  141. FlagQueryPhysicalAddressAllowed | FlagSharedDevice | FlagSharedDeviceAligned |
  142. FlagMemoryPoolAllocated | FlagIPCBuffer | FlagUncached,
  143. Unmapped = 0x00,
  144. Io = 0x01 | FlagMapped,
  145. Normal = 0x02 | FlagMapped | FlagQueryPhysicalAddressAllowed,
  146. Code = 0x03 | CodeFlags | FlagMapProcess,
  147. CodeData = 0x04 | DataFlags | FlagMapProcess | FlagCodeMemory,
  148. Heap = 0x05 | DataFlags | FlagCodeMemory,
  149. Shared = 0x06 | FlagMapped | FlagMemoryPoolAllocated,
  150. ModuleCode = 0x08 | CodeFlags | FlagModule | FlagMapProcess,
  151. ModuleCodeData = 0x09 | DataFlags | FlagModule | FlagMapProcess | FlagCodeMemory,
  152. IpcBuffer0 = 0x0A | FlagMapped | FlagQueryPhysicalAddressAllowed | FlagMemoryPoolAllocated |
  153. IPCFlags | FlagSharedDevice | FlagSharedDeviceAligned,
  154. Stack = 0x0B | FlagMapped | IPCFlags | FlagQueryPhysicalAddressAllowed |
  155. FlagSharedDevice | FlagSharedDeviceAligned | FlagMemoryPoolAllocated,
  156. ThreadLocal = 0x0C | FlagMapped | FlagMemoryPoolAllocated,
  157. TransferMemoryIsolated = 0x0D | IPCFlags | FlagMapped | FlagQueryPhysicalAddressAllowed |
  158. FlagSharedDevice | FlagSharedDeviceAligned | FlagMemoryPoolAllocated |
  159. FlagUncached,
  160. TransferMemory = 0x0E | FlagIPC3 | FlagIPC1 | FlagMapped | FlagQueryPhysicalAddressAllowed |
  161. FlagSharedDevice | FlagSharedDeviceAligned | FlagMemoryPoolAllocated,
  162. ProcessMemory = 0x0F | FlagIPC3 | FlagIPC1 | FlagMapped | FlagMemoryPoolAllocated,
  163. // Used to signify an inaccessible or invalid memory region with memory queries
  164. Inaccessible = 0x10,
  165. IpcBuffer1 = 0x11 | FlagIPC3 | FlagIPC1 | FlagMapped | FlagQueryPhysicalAddressAllowed |
  166. FlagSharedDevice | FlagSharedDeviceAligned | FlagMemoryPoolAllocated,
  167. IpcBuffer3 = 0x12 | FlagIPC3 | FlagMapped | FlagQueryPhysicalAddressAllowed |
  168. FlagSharedDeviceAligned | FlagMemoryPoolAllocated,
  169. KernelStack = 0x13 | FlagMapped,
  170. };
  171. // clang-format on
  172. constexpr MemoryState operator|(MemoryState lhs, MemoryState rhs) {
  173. return static_cast<MemoryState>(u32(lhs) | u32(rhs));
  174. }
  175. constexpr MemoryState operator&(MemoryState lhs, MemoryState rhs) {
  176. return static_cast<MemoryState>(u32(lhs) & u32(rhs));
  177. }
  178. constexpr MemoryState operator^(MemoryState lhs, MemoryState rhs) {
  179. return static_cast<MemoryState>(u32(lhs) ^ u32(rhs));
  180. }
  181. constexpr MemoryState operator~(MemoryState lhs) {
  182. return static_cast<MemoryState>(~u32(lhs));
  183. }
  184. constexpr MemoryState& operator|=(MemoryState& lhs, MemoryState rhs) {
  185. lhs = lhs | rhs;
  186. return lhs;
  187. }
  188. constexpr MemoryState& operator&=(MemoryState& lhs, MemoryState rhs) {
  189. lhs = lhs & rhs;
  190. return lhs;
  191. }
  192. constexpr MemoryState& operator^=(MemoryState& lhs, MemoryState rhs) {
  193. lhs = lhs ^ rhs;
  194. return lhs;
  195. }
  196. constexpr u32 ToSvcMemoryState(MemoryState state) {
  197. return static_cast<u32>(state & MemoryState::Mask);
  198. }
  199. struct MemoryInfo {
  200. u64 base_address;
  201. u64 size;
  202. u32 state;
  203. u32 attributes;
  204. u32 permission;
  205. u32 ipc_ref_count;
  206. u32 device_ref_count;
  207. };
  208. static_assert(sizeof(MemoryInfo) == 0x28, "MemoryInfo has incorrect size.");
  209. struct PageInfo {
  210. u32 flags;
  211. };
  212. /**
  213. * Represents a VMA in an address space. A VMA is a contiguous region of virtual addressing space
  214. * with homogeneous attributes across its extents. In this particular implementation each VMA is
  215. * also backed by a single host memory allocation.
  216. */
  217. struct VirtualMemoryArea {
  218. /// Gets the starting (base) address of this VMA.
  219. VAddr StartAddress() const {
  220. return base;
  221. }
  222. /// Gets the ending address of this VMA.
  223. VAddr EndAddress() const {
  224. return base + size - 1;
  225. }
  226. /// Virtual base address of the region.
  227. VAddr base = 0;
  228. /// Size of the region.
  229. u64 size = 0;
  230. VMAType type = VMAType::Free;
  231. VMAPermission permissions = VMAPermission::None;
  232. MemoryState state = MemoryState::Unmapped;
  233. MemoryAttribute attribute = MemoryAttribute::None;
  234. // Settings for type = AllocatedMemoryBlock
  235. /// Memory block backing this VMA.
  236. std::shared_ptr<std::vector<u8>> backing_block = nullptr;
  237. /// Offset into the backing_memory the mapping starts from.
  238. std::size_t offset = 0;
  239. // Settings for type = BackingMemory
  240. /// Pointer backing this VMA. It will not be destroyed or freed when the VMA is removed.
  241. u8* backing_memory = nullptr;
  242. // Settings for type = MMIO
  243. /// Physical address of the register area this VMA maps to.
  244. PAddr paddr = 0;
  245. Common::MemoryHookPointer mmio_handler = nullptr;
  246. /// Tests if this area can be merged to the right with `next`.
  247. bool CanBeMergedWith(const VirtualMemoryArea& next) const;
  248. };
  249. /**
  250. * Manages a process' virtual addressing space. This class maintains a list of allocated and free
  251. * regions in the address space, along with their attributes, and allows kernel clients to
  252. * manipulate it, adjusting the page table to match.
  253. *
  254. * This is similar in idea and purpose to the VM manager present in operating system kernels, with
  255. * the main difference being that it doesn't have to support swapping or memory mapping of files.
  256. * The implementation is also simplified by not having to allocate page frames. See these articles
  257. * about the Linux kernel for an explantion of the concept and implementation:
  258. * - http://duartes.org/gustavo/blog/post/how-the-kernel-manages-your-memory/
  259. * - http://duartes.org/gustavo/blog/post/page-cache-the-affair-between-memory-and-files/
  260. */
  261. class VMManager final {
  262. using VMAMap = std::map<VAddr, VirtualMemoryArea>;
  263. public:
  264. using VMAHandle = VMAMap::const_iterator;
  265. explicit VMManager(Core::System& system);
  266. ~VMManager();
  267. /// Clears the address space map, re-initializing with a single free area.
  268. void Reset(FileSys::ProgramAddressSpaceType type);
  269. /// Finds the VMA in which the given address is included in, or `vma_map.end()`.
  270. VMAHandle FindVMA(VAddr target) const;
  271. /// Indicates whether or not the given handle is within the VMA map.
  272. bool IsValidHandle(VMAHandle handle) const;
  273. // TODO(yuriks): Should these functions actually return the handle?
  274. /**
  275. * Maps part of a ref-counted block of memory at a given address.
  276. *
  277. * @param target The guest address to start the mapping at.
  278. * @param block The block to be mapped.
  279. * @param offset Offset into `block` to map from.
  280. * @param size Size of the mapping.
  281. * @param state MemoryState tag to attach to the VMA.
  282. */
  283. ResultVal<VMAHandle> MapMemoryBlock(VAddr target, std::shared_ptr<std::vector<u8>> block,
  284. std::size_t offset, u64 size, MemoryState state,
  285. VMAPermission perm = VMAPermission::ReadWrite);
  286. /**
  287. * Maps an unmanaged host memory pointer at a given address.
  288. *
  289. * @param target The guest address to start the mapping at.
  290. * @param memory The memory to be mapped.
  291. * @param size Size of the mapping.
  292. * @param state MemoryState tag to attach to the VMA.
  293. */
  294. ResultVal<VMAHandle> MapBackingMemory(VAddr target, u8* memory, u64 size, MemoryState state);
  295. /**
  296. * Finds the first free memory region of the given size within
  297. * the user-addressable ASLR memory region.
  298. *
  299. * @param size The size of the desired region in bytes.
  300. *
  301. * @returns If successful, the base address of the free region with
  302. * the given size.
  303. */
  304. ResultVal<VAddr> FindFreeRegion(u64 size) const;
  305. /**
  306. * Finds the first free address range that can hold a region of the desired size
  307. *
  308. * @param begin The starting address of the range.
  309. * This is treated as an inclusive beginning address.
  310. *
  311. * @param end The ending address of the range.
  312. * This is treated as an exclusive ending address.
  313. *
  314. * @param size The size of the free region to attempt to locate,
  315. * in bytes.
  316. *
  317. * @returns If successful, the base address of the free region with
  318. * the given size.
  319. *
  320. * @returns If unsuccessful, a result containing an error code.
  321. *
  322. * @pre The starting address must be less than the ending address.
  323. * @pre The size must not exceed the address range itself.
  324. */
  325. ResultVal<VAddr> FindFreeRegion(VAddr begin, VAddr end, u64 size) const;
  326. /**
  327. * Maps a memory-mapped IO region at a given address.
  328. *
  329. * @param target The guest address to start the mapping at.
  330. * @param paddr The physical address where the registers are present.
  331. * @param size Size of the mapping.
  332. * @param state MemoryState tag to attach to the VMA.
  333. * @param mmio_handler The handler that will implement read and write for this MMIO region.
  334. */
  335. ResultVal<VMAHandle> MapMMIO(VAddr target, PAddr paddr, u64 size, MemoryState state,
  336. Common::MemoryHookPointer mmio_handler);
  337. /// Unmaps a range of addresses, splitting VMAs as necessary.
  338. ResultCode UnmapRange(VAddr target, u64 size);
  339. /// Changes the permissions of the given VMA.
  340. VMAHandle Reprotect(VMAHandle vma, VMAPermission new_perms);
  341. /// Changes the permissions of a range of addresses, splitting VMAs as necessary.
  342. ResultCode ReprotectRange(VAddr target, u64 size, VMAPermission new_perms);
  343. ResultCode MirrorMemory(VAddr dst_addr, VAddr src_addr, u64 size, MemoryState state);
  344. /// Attempts to allocate a heap with the given size.
  345. ///
  346. /// @param size The size of the heap to allocate in bytes.
  347. ///
  348. /// @note If a heap is currently allocated, and this is called
  349. /// with a size that is equal to the size of the current heap,
  350. /// then this function will do nothing and return the current
  351. /// heap's starting address, as there's no need to perform
  352. /// any additional heap allocation work.
  353. ///
  354. /// @note If a heap is currently allocated, and this is called
  355. /// with a size less than the current heap's size, then
  356. /// this function will attempt to shrink the heap.
  357. ///
  358. /// @note If a heap is currently allocated, and this is called
  359. /// with a size larger than the current heap's size, then
  360. /// this function will attempt to extend the size of the heap.
  361. ///
  362. /// @returns A result indicating either success or failure.
  363. /// <p>
  364. /// If successful, this function will return a result
  365. /// containing the starting address to the allocated heap.
  366. /// <p>
  367. /// If unsuccessful, this function will return a result
  368. /// containing an error code.
  369. ///
  370. /// @pre The given size must lie within the allowable heap
  371. /// memory region managed by this VMManager instance.
  372. /// Failure to abide by this will result in ERR_OUT_OF_MEMORY
  373. /// being returned as the result.
  374. ///
  375. ResultVal<VAddr> SetHeapSize(u64 size);
  376. /// Maps memory at a given address.
  377. ///
  378. /// @param addr The virtual address to map memory at.
  379. /// @param size The amount of memory to map.
  380. ///
  381. /// @note The destination address must lie within the Map region.
  382. ///
  383. /// @note This function requires that SystemResourceSize be non-zero,
  384. /// however, this is just because if it were not then the
  385. /// resulting page tables could be exploited on hardware by
  386. /// a malicious program. SystemResource usage does not need
  387. /// to be explicitly checked or updated here.
  388. ResultCode MapPhysicalMemory(VAddr target, u64 size);
  389. /// Unmaps memory at a given address.
  390. ///
  391. /// @param addr The virtual address to unmap memory at.
  392. /// @param size The amount of memory to unmap.
  393. ///
  394. /// @note The destination address must lie within the Map region.
  395. ///
  396. /// @note This function requires that SystemResourceSize be non-zero,
  397. /// however, this is just because if it were not then the
  398. /// resulting page tables could be exploited on hardware by
  399. /// a malicious program. SystemResource usage does not need
  400. /// to be explicitly checked or updated here.
  401. ResultCode UnmapPhysicalMemory(VAddr target, u64 size);
  402. /// Maps a region of memory as code memory.
  403. ///
  404. /// @param dst_address The base address of the region to create the aliasing memory region.
  405. /// @param src_address The base address of the region to be aliased.
  406. /// @param size The total amount of memory to map in bytes.
  407. ///
  408. /// @pre Both memory regions lie within the actual addressable address space.
  409. ///
  410. /// @post After this function finishes execution, assuming success, then the address range
  411. /// [dst_address, dst_address+size) will alias the memory region,
  412. /// [src_address, src_address+size).
  413. /// <p>
  414. /// What this also entails is as follows:
  415. /// 1. The aliased region gains the Locked memory attribute.
  416. /// 2. The aliased region becomes read-only.
  417. /// 3. The aliasing region becomes read-only.
  418. /// 4. The aliasing region is created with a memory state of MemoryState::CodeModule.
  419. ///
  420. ResultCode MapCodeMemory(VAddr dst_address, VAddr src_address, u64 size);
  421. /// Unmaps a region of memory designated as code module memory.
  422. ///
  423. /// @param dst_address The base address of the memory region aliasing the source memory region.
  424. /// @param src_address The base address of the memory region being aliased.
  425. /// @param size The size of the memory region to unmap in bytes.
  426. ///
  427. /// @pre Both memory ranges lie within the actual addressable address space.
  428. ///
  429. /// @pre The memory region being unmapped has been previously been mapped
  430. /// by a call to MapCodeMemory.
  431. ///
  432. /// @post After execution of the function, if successful. the aliasing memory region
  433. /// will be unmapped and the aliased region will have various traits about it
  434. /// restored to what they were prior to the original mapping call preceding
  435. /// this function call.
  436. /// <p>
  437. /// What this also entails is as follows:
  438. /// 1. The state of the memory region will now indicate a general heap region.
  439. /// 2. All memory attributes for the memory region are cleared.
  440. /// 3. Memory permissions for the region are restored to user read/write.
  441. ///
  442. ResultCode UnmapCodeMemory(VAddr dst_address, VAddr src_address, u64 size);
  443. /// Queries the memory manager for information about the given address.
  444. ///
  445. /// @param address The address to query the memory manager about for information.
  446. ///
  447. /// @return A MemoryInfo instance containing information about the given address.
  448. ///
  449. MemoryInfo QueryMemory(VAddr address) const;
  450. /// Sets an attribute across the given address range.
  451. ///
  452. /// @param address The starting address
  453. /// @param size The size of the range to set the attribute on.
  454. /// @param mask The attribute mask
  455. /// @param attribute The attribute to set across the given address range
  456. ///
  457. /// @returns RESULT_SUCCESS if successful
  458. /// @returns ERR_INVALID_ADDRESS_STATE if the attribute could not be set.
  459. ///
  460. ResultCode SetMemoryAttribute(VAddr address, u64 size, MemoryAttribute mask,
  461. MemoryAttribute attribute);
  462. /**
  463. * Scans all VMAs and updates the page table range of any that use the given vector as backing
  464. * memory. This should be called after any operation that causes reallocation of the vector.
  465. */
  466. void RefreshMemoryBlockMappings(const std::vector<u8>* block);
  467. /// Dumps the address space layout to the log, for debugging
  468. void LogLayout() const;
  469. /// Gets the total memory usage, used by svcGetInfo
  470. u64 GetTotalPhysicalMemoryAvailable() const;
  471. /// Gets the address space base address
  472. VAddr GetAddressSpaceBaseAddress() const;
  473. /// Gets the address space end address
  474. VAddr GetAddressSpaceEndAddress() const;
  475. /// Gets the total address space address size in bytes
  476. u64 GetAddressSpaceSize() const;
  477. /// Gets the address space width in bits.
  478. u64 GetAddressSpaceWidth() const;
  479. /// Determines whether or not the given address range lies within the address space.
  480. bool IsWithinAddressSpace(VAddr address, u64 size) const;
  481. /// Gets the base address of the ASLR region.
  482. VAddr GetASLRRegionBaseAddress() const;
  483. /// Gets the end address of the ASLR region.
  484. VAddr GetASLRRegionEndAddress() const;
  485. /// Gets the size of the ASLR region
  486. u64 GetASLRRegionSize() const;
  487. /// Determines whether or not the specified address range is within the ASLR region.
  488. bool IsWithinASLRRegion(VAddr address, u64 size) const;
  489. /// Gets the base address of the code region.
  490. VAddr GetCodeRegionBaseAddress() const;
  491. /// Gets the end address of the code region.
  492. VAddr GetCodeRegionEndAddress() const;
  493. /// Gets the total size of the code region in bytes.
  494. u64 GetCodeRegionSize() const;
  495. /// Determines whether or not the specified range is within the code region.
  496. bool IsWithinCodeRegion(VAddr address, u64 size) const;
  497. /// Gets the base address of the heap region.
  498. VAddr GetHeapRegionBaseAddress() const;
  499. /// Gets the end address of the heap region;
  500. VAddr GetHeapRegionEndAddress() const;
  501. /// Gets the total size of the heap region in bytes.
  502. u64 GetHeapRegionSize() const;
  503. /// Gets the total size of the current heap in bytes.
  504. ///
  505. /// @note This is the current allocated heap size, not the size
  506. /// of the region it's allowed to exist within.
  507. ///
  508. u64 GetCurrentHeapSize() const;
  509. /// Determines whether or not the specified range is within the heap region.
  510. bool IsWithinHeapRegion(VAddr address, u64 size) const;
  511. /// Gets the base address of the map region.
  512. VAddr GetMapRegionBaseAddress() const;
  513. /// Gets the end address of the map region.
  514. VAddr GetMapRegionEndAddress() const;
  515. /// Gets the total size of the map region in bytes.
  516. u64 GetMapRegionSize() const;
  517. /// Determines whether or not the specified range is within the map region.
  518. bool IsWithinMapRegion(VAddr address, u64 size) const;
  519. /// Gets the base address of the stack region.
  520. VAddr GetStackRegionBaseAddress() const;
  521. /// Gets the end address of the stack region.
  522. VAddr GetStackRegionEndAddress() const;
  523. /// Gets the total size of the stack region in bytes.
  524. u64 GetStackRegionSize() const;
  525. /// Determines whether or not the given address range is within the stack region
  526. bool IsWithinStackRegion(VAddr address, u64 size) const;
  527. /// Gets the base address of the TLS IO region.
  528. VAddr GetTLSIORegionBaseAddress() const;
  529. /// Gets the end address of the TLS IO region.
  530. VAddr GetTLSIORegionEndAddress() const;
  531. /// Gets the total size of the TLS IO region in bytes.
  532. u64 GetTLSIORegionSize() const;
  533. /// Determines if the given address range is within the TLS IO region.
  534. bool IsWithinTLSIORegion(VAddr address, u64 size) const;
  535. /// Each VMManager has its own page table, which is set as the main one when the owning process
  536. /// is scheduled.
  537. Common::PageTable page_table{Memory::PAGE_BITS};
  538. private:
  539. using VMAIter = VMAMap::iterator;
  540. /// Converts a VMAHandle to a mutable VMAIter.
  541. VMAIter StripIterConstness(const VMAHandle& iter);
  542. /// Unmaps the given VMA.
  543. VMAIter Unmap(VMAIter vma);
  544. /**
  545. * Carves a VMA of a specific size at the specified address by splitting Free VMAs while doing
  546. * the appropriate error checking.
  547. */
  548. ResultVal<VMAIter> CarveVMA(VAddr base, u64 size);
  549. /**
  550. * Splits the edges of the given range of non-Free VMAs so that there is a VMA split at each
  551. * end of the range.
  552. */
  553. ResultVal<VMAIter> CarveVMARange(VAddr base, u64 size);
  554. /**
  555. * Splits a VMA in two, at the specified offset.
  556. * @returns the right side of the split, with the original iterator becoming the left side.
  557. */
  558. VMAIter SplitVMA(VMAIter vma, u64 offset_in_vma);
  559. /**
  560. * Checks for and merges the specified VMA with adjacent ones if possible.
  561. * @returns the merged VMA or the original if no merging was possible.
  562. */
  563. VMAIter MergeAdjacent(VMAIter vma);
  564. /**
  565. * Merges two adjacent VMAs.
  566. */
  567. void MergeAdjacentVMA(VirtualMemoryArea& left, const VirtualMemoryArea& right);
  568. /// Updates the pages corresponding to this VMA so they match the VMA's attributes.
  569. void UpdatePageTableForVMA(const VirtualMemoryArea& vma);
  570. /// Initializes memory region ranges to adhere to a given address space type.
  571. void InitializeMemoryRegionRanges(FileSys::ProgramAddressSpaceType type);
  572. /// Clears the underlying map and page table.
  573. void Clear();
  574. /// Clears out the VMA map, unmapping any previously mapped ranges.
  575. void ClearVMAMap();
  576. /// Clears out the page table
  577. void ClearPageTable();
  578. using CheckResults = ResultVal<std::tuple<MemoryState, VMAPermission, MemoryAttribute>>;
  579. /// Checks if an address range adheres to the specified states provided.
  580. ///
  581. /// @param address The starting address of the address range.
  582. /// @param size The size of the address range.
  583. /// @param state_mask The memory state mask.
  584. /// @param state The state to compare the individual VMA states against,
  585. /// which is done in the form of: (vma.state & state_mask) != state.
  586. /// @param permission_mask The memory permissions mask.
  587. /// @param permissions The permission to compare the individual VMA permissions against,
  588. /// which is done in the form of:
  589. /// (vma.permission & permission_mask) != permission.
  590. /// @param attribute_mask The memory attribute mask.
  591. /// @param attribute The memory attributes to compare the individual VMA attributes
  592. /// against, which is done in the form of:
  593. /// (vma.attributes & attribute_mask) != attribute.
  594. /// @param ignore_mask The memory attributes to ignore during the check.
  595. ///
  596. /// @returns If successful, returns a tuple containing the memory attributes
  597. /// (with ignored bits specified by ignore_mask unset), memory permissions, and
  598. /// memory state across the memory range.
  599. /// @returns If not successful, returns ERR_INVALID_ADDRESS_STATE.
  600. ///
  601. CheckResults CheckRangeState(VAddr address, u64 size, MemoryState state_mask, MemoryState state,
  602. VMAPermission permission_mask, VMAPermission permissions,
  603. MemoryAttribute attribute_mask, MemoryAttribute attribute,
  604. MemoryAttribute ignore_mask) const;
  605. /// Gets the amount of memory currently mapped (state != Unmapped) in a range.
  606. ResultVal<std::size_t> SizeOfAllocatedVMAsInRange(VAddr address, std::size_t size) const;
  607. /// Gets the amount of memory unmappable by UnmapPhysicalMemory in a range.
  608. ResultVal<std::size_t> SizeOfUnmappablePhysicalMemoryInRange(VAddr address,
  609. std::size_t size) const;
  610. /**
  611. * A map covering the entirety of the managed address space, keyed by the `base` field of each
  612. * VMA. It must always be modified by splitting or merging VMAs, so that the invariant
  613. * `elem.base + elem.size == next.base` is preserved, and mergeable regions must always be
  614. * merged when possible so that no two similar and adjacent regions exist that have not been
  615. * merged.
  616. */
  617. VMAMap vma_map;
  618. u32 address_space_width = 0;
  619. VAddr address_space_base = 0;
  620. VAddr address_space_end = 0;
  621. VAddr aslr_region_base = 0;
  622. VAddr aslr_region_end = 0;
  623. VAddr code_region_base = 0;
  624. VAddr code_region_end = 0;
  625. VAddr heap_region_base = 0;
  626. VAddr heap_region_end = 0;
  627. VAddr map_region_base = 0;
  628. VAddr map_region_end = 0;
  629. VAddr stack_region_base = 0;
  630. VAddr stack_region_end = 0;
  631. VAddr tls_io_region_base = 0;
  632. VAddr tls_io_region_end = 0;
  633. // Memory used to back the allocations in the regular heap. A single vector is used to cover
  634. // the entire virtual address space extents that bound the allocations, including any holes.
  635. // This makes deallocation and reallocation of holes fast and keeps process memory contiguous
  636. // in the emulator address space, allowing Memory::GetPointer to be reasonably safe.
  637. std::shared_ptr<std::vector<u8>> heap_memory;
  638. // The end of the currently allocated heap. This is not an inclusive
  639. // end of the range. This is essentially 'base_address + current_size'.
  640. VAddr heap_end = 0;
  641. // The current amount of memory mapped via MapPhysicalMemory.
  642. // This is used here (and in Nintendo's kernel) only for debugging, and does not impact
  643. // any behavior.
  644. u64 physical_memory_mapped = 0;
  645. Core::System& system;
  646. };
  647. } // namespace Kernel