process.h 13 KB

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