process.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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 <array>
  6. #include <cstddef>
  7. #include <list>
  8. #include <string>
  9. #include <unordered_map>
  10. #include <vector>
  11. #include "common/common_types.h"
  12. #include "core/hle/kernel/address_arbiter.h"
  13. #include "core/hle/kernel/handle_table.h"
  14. #include "core/hle/kernel/mutex.h"
  15. #include "core/hle/kernel/process_capability.h"
  16. #include "core/hle/kernel/synchronization_object.h"
  17. #include "core/hle/result.h"
  18. namespace Core {
  19. class System;
  20. }
  21. namespace FileSys {
  22. class ProgramMetadata;
  23. }
  24. namespace Kernel {
  25. class KernelCore;
  26. class ResourceLimit;
  27. class Thread;
  28. class TLSPage;
  29. struct CodeSet;
  30. namespace Memory {
  31. class PageTable;
  32. }
  33. enum class MemoryRegion : u16 {
  34. APPLICATION = 1,
  35. SYSTEM = 2,
  36. BASE = 3,
  37. };
  38. /**
  39. * Indicates the status of a Process instance.
  40. *
  41. * @note These match the values as used by kernel,
  42. * so new entries should only be added if RE
  43. * shows that a new value has been introduced.
  44. */
  45. enum class ProcessStatus {
  46. Created,
  47. CreatedWithDebuggerAttached,
  48. Running,
  49. WaitingForDebuggerToAttach,
  50. DebuggerAttached,
  51. Exiting,
  52. Exited,
  53. DebugBreak,
  54. };
  55. class Process final : public SynchronizationObject {
  56. public:
  57. explicit Process(Core::System& system);
  58. ~Process() override;
  59. enum : u64 {
  60. /// Lowest allowed process ID for a kernel initial process.
  61. InitialKIPIDMin = 1,
  62. /// Highest allowed process ID for a kernel initial process.
  63. InitialKIPIDMax = 80,
  64. /// Lowest allowed process ID for a userland process.
  65. ProcessIDMin = 81,
  66. /// Highest allowed process ID for a userland process.
  67. ProcessIDMax = 0xFFFFFFFFFFFFFFFF,
  68. };
  69. // Used to determine how process IDs are assigned.
  70. enum class ProcessType {
  71. KernelInternal,
  72. Userland,
  73. };
  74. static constexpr std::size_t RANDOM_ENTROPY_SIZE = 4;
  75. static std::shared_ptr<Process> Create(Core::System& system, std::string name,
  76. ProcessType type);
  77. std::string GetTypeName() const override {
  78. return "Process";
  79. }
  80. std::string GetName() const override {
  81. return name;
  82. }
  83. static constexpr HandleType HANDLE_TYPE = HandleType::Process;
  84. HandleType GetHandleType() const override {
  85. return HANDLE_TYPE;
  86. }
  87. /// Gets a reference to the process' page table.
  88. Memory::PageTable& PageTable() {
  89. return *page_table;
  90. }
  91. /// Gets const a reference to the process' page table.
  92. const Memory::PageTable& PageTable() const {
  93. return *page_table;
  94. }
  95. /// Gets a reference to the process' handle table.
  96. HandleTable& GetHandleTable() {
  97. return handle_table;
  98. }
  99. /// Gets a const reference to the process' handle table.
  100. const HandleTable& GetHandleTable() const {
  101. return handle_table;
  102. }
  103. /// Gets a reference to the process' address arbiter.
  104. AddressArbiter& GetAddressArbiter() {
  105. return address_arbiter;
  106. }
  107. /// Gets a const reference to the process' address arbiter.
  108. const AddressArbiter& GetAddressArbiter() const {
  109. return address_arbiter;
  110. }
  111. /// Gets a reference to the process' mutex lock.
  112. Mutex& GetMutex() {
  113. return mutex;
  114. }
  115. /// Gets a const reference to the process' mutex lock
  116. const Mutex& GetMutex() const {
  117. return mutex;
  118. }
  119. /// Gets the address to the process' dedicated TLS region.
  120. VAddr GetTLSRegionAddress() const {
  121. return tls_region_address;
  122. }
  123. /// Gets the current status of the process
  124. ProcessStatus GetStatus() const {
  125. return status;
  126. }
  127. /// Gets the unique ID that identifies this particular process.
  128. u64 GetProcessID() const {
  129. return process_id;
  130. }
  131. /// Gets the title ID corresponding to this process.
  132. u64 GetTitleID() const {
  133. return program_id;
  134. }
  135. /// Gets the resource limit descriptor for this process
  136. std::shared_ptr<ResourceLimit> GetResourceLimit() const;
  137. /// Gets the ideal CPU core ID for this process
  138. u8 GetIdealCore() const {
  139. return ideal_core;
  140. }
  141. /// Gets the bitmask of allowed cores that this process' threads can run on.
  142. u64 GetCoreMask() const {
  143. return capabilities.GetCoreMask();
  144. }
  145. /// Gets the bitmask of allowed thread priorities.
  146. u64 GetPriorityMask() const {
  147. return capabilities.GetPriorityMask();
  148. }
  149. /// Gets the amount of secure memory to allocate for memory management.
  150. u32 GetSystemResourceSize() const {
  151. return system_resource_size;
  152. }
  153. /// Gets the amount of secure memory currently in use for memory management.
  154. u32 GetSystemResourceUsage() const {
  155. // On hardware, this returns the amount of system resource memory that has
  156. // been used by the kernel. This is problematic for Yuzu to emulate, because
  157. // system resource memory is used for page tables -- and yuzu doesn't really
  158. // have a way to calculate how much memory is required for page tables for
  159. // the current process at any given time.
  160. // TODO: Is this even worth implementing? Games may retrieve this value via
  161. // an SDK function that gets used + available system resource size for debug
  162. // or diagnostic purposes. However, it seems unlikely that a game would make
  163. // decisions based on how much system memory is dedicated to its page tables.
  164. // Is returning a value other than zero wise?
  165. return 0;
  166. }
  167. /// Whether this process is an AArch64 or AArch32 process.
  168. bool Is64BitProcess() const {
  169. return is_64bit_process;
  170. }
  171. /// Gets the total running time of the process instance in ticks.
  172. u64 GetCPUTimeTicks() const {
  173. return total_process_running_time_ticks;
  174. }
  175. /// Updates the total running time, adding the given ticks to it.
  176. void UpdateCPUTimeTicks(u64 ticks) {
  177. total_process_running_time_ticks += ticks;
  178. }
  179. /// Gets 8 bytes of random data for svcGetInfo RandomEntropy
  180. u64 GetRandomEntropy(std::size_t index) const {
  181. return random_entropy.at(index);
  182. }
  183. /// Retrieves the total physical memory available to this process in bytes.
  184. u64 GetTotalPhysicalMemoryAvailable() const;
  185. /// Retrieves the total physical memory available to this process in bytes,
  186. /// without the size of the personal system resource heap added to it.
  187. u64 GetTotalPhysicalMemoryAvailableWithoutSystemResource() const;
  188. /// Retrieves the total physical memory used by this process in bytes.
  189. u64 GetTotalPhysicalMemoryUsed() const;
  190. /// Retrieves the total physical memory used by this process in bytes,
  191. /// without the size of the personal system resource heap added to it.
  192. u64 GetTotalPhysicalMemoryUsedWithoutSystemResource() const;
  193. /// Gets the list of all threads created with this process as their owner.
  194. const std::list<const Thread*>& GetThreadList() const {
  195. return thread_list;
  196. }
  197. /// Insert a thread into the condition variable wait container
  198. void InsertConditionVariableThread(std::shared_ptr<Thread> thread);
  199. /// Remove a thread from the condition variable wait container
  200. void RemoveConditionVariableThread(std::shared_ptr<Thread> thread);
  201. /// Obtain all condition variable threads waiting for some address
  202. std::vector<std::shared_ptr<Thread>> GetConditionVariableThreads(VAddr cond_var_addr);
  203. /// Registers a thread as being created under this process,
  204. /// adding it to this process' thread list.
  205. void RegisterThread(const Thread* thread);
  206. /// Unregisters a thread from this process, removing it
  207. /// from this process' thread list.
  208. void UnregisterThread(const Thread* thread);
  209. /// Clears the signaled state of the process if and only if it's signaled.
  210. ///
  211. /// @pre The process must not be already terminated. If this is called on a
  212. /// terminated process, then ERR_INVALID_STATE will be returned.
  213. ///
  214. /// @pre The process must be in a signaled state. If this is called on a
  215. /// process instance that is not signaled, ERR_INVALID_STATE will be
  216. /// returned.
  217. ResultCode ClearSignalState();
  218. /**
  219. * Loads process-specifics configuration info with metadata provided
  220. * by an executable.
  221. *
  222. * @param metadata The provided metadata to load process specific info from.
  223. *
  224. * @returns RESULT_SUCCESS if all relevant metadata was able to be
  225. * loaded and parsed. Otherwise, an error code is returned.
  226. */
  227. ResultCode LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std::size_t code_size);
  228. /**
  229. * Starts the main application thread for this process.
  230. *
  231. * @param main_thread_priority The priority for the main thread.
  232. * @param stack_size The stack size for the main thread in bytes.
  233. */
  234. void Run(s32 main_thread_priority, u64 stack_size);
  235. /**
  236. * Prepares a process for termination by stopping all of its threads
  237. * and clearing any other resources.
  238. */
  239. void PrepareForTermination();
  240. void LoadModule(CodeSet code_set, VAddr base_addr);
  241. ///////////////////////////////////////////////////////////////////////////////////////////////
  242. // Thread-local storage management
  243. // Marks the next available region as used and returns the address of the slot.
  244. [[nodiscard]] VAddr CreateTLSRegion();
  245. // Frees a used TLS slot identified by the given address
  246. void FreeTLSRegion(VAddr tls_address);
  247. private:
  248. /// Checks if the specified thread should wait until this process is available.
  249. bool ShouldWait(const Thread* thread) const override;
  250. /// Acquires/locks this process for the specified thread if it's available.
  251. void Acquire(Thread* thread) override;
  252. /// Changes the process status. If the status is different
  253. /// from the current process status, then this will trigger
  254. /// a process signal.
  255. void ChangeStatus(ProcessStatus new_status);
  256. /// Allocates the main thread stack for the process, given the stack size in bytes.
  257. ResultCode AllocateMainThreadStack(std::size_t stack_size);
  258. /// Memory manager for this process
  259. std::unique_ptr<Memory::PageTable> page_table;
  260. /// Current status of the process
  261. ProcessStatus status{};
  262. /// The ID of this process
  263. u64 process_id = 0;
  264. /// Title ID corresponding to the process
  265. u64 program_id = 0;
  266. /// Specifies additional memory to be reserved for the process's memory management by the
  267. /// system. When this is non-zero, secure memory is allocated and used for page table allocation
  268. /// instead of using the normal global page tables/memory block management.
  269. u32 system_resource_size = 0;
  270. /// Resource limit descriptor for this process
  271. std::shared_ptr<ResourceLimit> resource_limit;
  272. /// The ideal CPU core for this process, threads are scheduled on this core by default.
  273. u8 ideal_core = 0;
  274. /// The Thread Local Storage area is allocated as processes create threads,
  275. /// each TLS area is 0x200 bytes, so one page (0x1000) is split up in 8 parts, and each part
  276. /// holds the TLS for a specific thread. This vector contains which parts are in use for each
  277. /// page as a bitmask.
  278. /// This vector will grow as more pages are allocated for new threads.
  279. std::vector<TLSPage> tls_pages;
  280. /// Contains the parsed process capability descriptors.
  281. ProcessCapabilities capabilities;
  282. /// Whether or not this process is AArch64, or AArch32.
  283. /// By default, we currently assume this is true, unless otherwise
  284. /// specified by metadata provided to the process during loading.
  285. bool is_64bit_process = true;
  286. /// Total running time for the process in ticks.
  287. u64 total_process_running_time_ticks = 0;
  288. /// Per-process handle table for storing created object handles in.
  289. HandleTable handle_table;
  290. /// Per-process address arbiter.
  291. AddressArbiter address_arbiter;
  292. /// The per-process mutex lock instance used for handling various
  293. /// forms of services, such as lock arbitration, and condition
  294. /// variable related facilities.
  295. Mutex mutex;
  296. /// Address indicating the location of the process' dedicated TLS region.
  297. VAddr tls_region_address = 0;
  298. /// Random values for svcGetInfo RandomEntropy
  299. std::array<u64, RANDOM_ENTROPY_SIZE> random_entropy{};
  300. /// List of threads that are running with this process as their owner.
  301. std::list<const Thread*> thread_list;
  302. /// List of threads waiting for a condition variable
  303. std::unordered_map<VAddr, std::list<std::shared_ptr<Thread>>> cond_var_threads;
  304. /// System context
  305. Core::System& system;
  306. /// Name of this process
  307. std::string name;
  308. /// Address of the top of the main thread's stack
  309. VAddr main_thread_stack_top{};
  310. /// Size of the main thread's stack
  311. std::size_t main_thread_stack_size{};
  312. /// Memory usage capacity for the process
  313. std::size_t memory_usage_capacity{};
  314. /// Process total image size
  315. std::size_t image_size{};
  316. };
  317. } // namespace Kernel