process.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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/handle_table.h"
  13. #include "core/hle/kernel/k_address_arbiter.h"
  14. #include "core/hle/kernel/k_condition_variable.h"
  15. #include "core/hle/kernel/k_synchronization_object.h"
  16. #include "core/hle/kernel/process_capability.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 KResourceLimit;
  27. class KThread;
  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 KSynchronizationObject {
  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. ResultCode SignalToAddress(VAddr address) {
  104. return condition_var.SignalToAddress(address);
  105. }
  106. ResultCode WaitForAddress(Handle handle, VAddr address, u32 tag) {
  107. return condition_var.WaitForAddress(handle, address, tag);
  108. }
  109. void SignalConditionVariable(u64 cv_key, int32_t count) {
  110. return condition_var.Signal(cv_key, count);
  111. }
  112. ResultCode WaitConditionVariable(VAddr address, u64 cv_key, u32 tag, s64 ns) {
  113. return condition_var.Wait(address, cv_key, tag, ns);
  114. }
  115. ResultCode SignalAddressArbiter(VAddr address, Svc::SignalType signal_type, s32 value,
  116. s32 count) {
  117. return address_arbiter.SignalToAddress(address, signal_type, value, count);
  118. }
  119. ResultCode WaitAddressArbiter(VAddr address, Svc::ArbitrationType arb_type, s32 value,
  120. s64 timeout) {
  121. return address_arbiter.WaitForAddress(address, arb_type, value, timeout);
  122. }
  123. /// Gets the address to the process' dedicated TLS region.
  124. VAddr GetTLSRegionAddress() const {
  125. return tls_region_address;
  126. }
  127. /// Gets the current status of the process
  128. ProcessStatus GetStatus() const {
  129. return status;
  130. }
  131. /// Gets the unique ID that identifies this particular process.
  132. u64 GetProcessID() const {
  133. return process_id;
  134. }
  135. /// Gets the title ID corresponding to this process.
  136. u64 GetTitleID() const {
  137. return program_id;
  138. }
  139. /// Gets the resource limit descriptor for this process
  140. std::shared_ptr<KResourceLimit> GetResourceLimit() const;
  141. /// Gets the ideal CPU core ID for this process
  142. u8 GetIdealCoreId() const {
  143. return ideal_core;
  144. }
  145. /// Checks if the specified thread priority is valid.
  146. bool CheckThreadPriority(s32 prio) const {
  147. return ((1ULL << prio) & GetPriorityMask()) != 0;
  148. }
  149. /// Gets the bitmask of allowed cores that this process' threads can run on.
  150. u64 GetCoreMask() const {
  151. return capabilities.GetCoreMask();
  152. }
  153. /// Gets the bitmask of allowed thread priorities.
  154. u64 GetPriorityMask() const {
  155. return capabilities.GetPriorityMask();
  156. }
  157. /// Gets the amount of secure memory to allocate for memory management.
  158. u32 GetSystemResourceSize() const {
  159. return system_resource_size;
  160. }
  161. /// Gets the amount of secure memory currently in use for memory management.
  162. u32 GetSystemResourceUsage() const {
  163. // On hardware, this returns the amount of system resource memory that has
  164. // been used by the kernel. This is problematic for Yuzu to emulate, because
  165. // system resource memory is used for page tables -- and yuzu doesn't really
  166. // have a way to calculate how much memory is required for page tables for
  167. // the current process at any given time.
  168. // TODO: Is this even worth implementing? Games may retrieve this value via
  169. // an SDK function that gets used + available system resource size for debug
  170. // or diagnostic purposes. However, it seems unlikely that a game would make
  171. // decisions based on how much system memory is dedicated to its page tables.
  172. // Is returning a value other than zero wise?
  173. return 0;
  174. }
  175. /// Whether this process is an AArch64 or AArch32 process.
  176. bool Is64BitProcess() const {
  177. return is_64bit_process;
  178. }
  179. [[nodiscard]] bool IsSuspended() const {
  180. return is_suspended;
  181. }
  182. void SetSuspended(bool suspended) {
  183. is_suspended = suspended;
  184. }
  185. /// Gets the total running time of the process instance in ticks.
  186. u64 GetCPUTimeTicks() const {
  187. return total_process_running_time_ticks;
  188. }
  189. /// Updates the total running time, adding the given ticks to it.
  190. void UpdateCPUTimeTicks(u64 ticks) {
  191. total_process_running_time_ticks += ticks;
  192. }
  193. /// Gets the process schedule count, used for thread yelding
  194. s64 GetScheduledCount() const {
  195. return schedule_count;
  196. }
  197. /// Increments the process schedule count, used for thread yielding.
  198. void IncrementScheduledCount() {
  199. ++schedule_count;
  200. }
  201. void IncrementThreadCount();
  202. void DecrementThreadCount();
  203. void SetRunningThread(s32 core, KThread* thread, u64 idle_count) {
  204. running_threads[core] = thread;
  205. running_thread_idle_counts[core] = idle_count;
  206. }
  207. void ClearRunningThread(KThread* thread) {
  208. for (size_t i = 0; i < running_threads.size(); ++i) {
  209. if (running_threads[i] == thread) {
  210. running_threads[i] = nullptr;
  211. }
  212. }
  213. }
  214. [[nodiscard]] KThread* GetRunningThread(s32 core) const {
  215. return running_threads[core];
  216. }
  217. bool ReleaseUserException(KThread* thread);
  218. [[nodiscard]] KThread* GetPinnedThread(s32 core_id) const {
  219. ASSERT(0 <= core_id && core_id < static_cast<s32>(Core::Hardware::NUM_CPU_CORES));
  220. return pinned_threads[core_id];
  221. }
  222. /// Gets 8 bytes of random data for svcGetInfo RandomEntropy
  223. u64 GetRandomEntropy(std::size_t index) const {
  224. return random_entropy.at(index);
  225. }
  226. /// Retrieves the total physical memory available to this process in bytes.
  227. u64 GetTotalPhysicalMemoryAvailable() const;
  228. /// Retrieves the total physical memory available to this process in bytes,
  229. /// without the size of the personal system resource heap added to it.
  230. u64 GetTotalPhysicalMemoryAvailableWithoutSystemResource() const;
  231. /// Retrieves the total physical memory used by this process in bytes.
  232. u64 GetTotalPhysicalMemoryUsed() const;
  233. /// Retrieves the total physical memory used by this process in bytes,
  234. /// without the size of the personal system resource heap added to it.
  235. u64 GetTotalPhysicalMemoryUsedWithoutSystemResource() const;
  236. /// Gets the list of all threads created with this process as their owner.
  237. const std::list<const KThread*>& GetThreadList() const {
  238. return thread_list;
  239. }
  240. /// Registers a thread as being created under this process,
  241. /// adding it to this process' thread list.
  242. void RegisterThread(const KThread* thread);
  243. /// Unregisters a thread from this process, removing it
  244. /// from this process' thread list.
  245. void UnregisterThread(const KThread* thread);
  246. /// Clears the signaled state of the process if and only if it's signaled.
  247. ///
  248. /// @pre The process must not be already terminated. If this is called on a
  249. /// terminated process, then ERR_INVALID_STATE will be returned.
  250. ///
  251. /// @pre The process must be in a signaled state. If this is called on a
  252. /// process instance that is not signaled, ERR_INVALID_STATE will be
  253. /// returned.
  254. ResultCode Reset();
  255. /**
  256. * Loads process-specifics configuration info with metadata provided
  257. * by an executable.
  258. *
  259. * @param metadata The provided metadata to load process specific info from.
  260. *
  261. * @returns RESULT_SUCCESS if all relevant metadata was able to be
  262. * loaded and parsed. Otherwise, an error code is returned.
  263. */
  264. ResultCode LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std::size_t code_size);
  265. /**
  266. * Starts the main application thread for this process.
  267. *
  268. * @param main_thread_priority The priority for the main thread.
  269. * @param stack_size The stack size for the main thread in bytes.
  270. */
  271. void Run(s32 main_thread_priority, u64 stack_size);
  272. /**
  273. * Prepares a process for termination by stopping all of its threads
  274. * and clearing any other resources.
  275. */
  276. void PrepareForTermination();
  277. void LoadModule(CodeSet code_set, VAddr base_addr);
  278. bool IsSignaled() const override;
  279. void Finalize() override {}
  280. void PinCurrentThread();
  281. void UnpinCurrentThread();
  282. KLightLock& GetStateLock() {
  283. return state_lock;
  284. }
  285. ///////////////////////////////////////////////////////////////////////////////////////////////
  286. // Thread-local storage management
  287. // Marks the next available region as used and returns the address of the slot.
  288. [[nodiscard]] VAddr CreateTLSRegion();
  289. // Frees a used TLS slot identified by the given address
  290. void FreeTLSRegion(VAddr tls_address);
  291. private:
  292. void PinThread(s32 core_id, KThread* thread) {
  293. ASSERT(0 <= core_id && core_id < static_cast<s32>(Core::Hardware::NUM_CPU_CORES));
  294. ASSERT(thread != nullptr);
  295. ASSERT(pinned_threads[core_id] == nullptr);
  296. pinned_threads[core_id] = thread;
  297. }
  298. void UnpinThread(s32 core_id, KThread* thread) {
  299. ASSERT(0 <= core_id && core_id < static_cast<s32>(Core::Hardware::NUM_CPU_CORES));
  300. ASSERT(thread != nullptr);
  301. ASSERT(pinned_threads[core_id] == thread);
  302. pinned_threads[core_id] = nullptr;
  303. }
  304. /// Changes the process status. If the status is different
  305. /// from the current process status, then this will trigger
  306. /// a process signal.
  307. void ChangeStatus(ProcessStatus new_status);
  308. /// Allocates the main thread stack for the process, given the stack size in bytes.
  309. ResultCode AllocateMainThreadStack(std::size_t stack_size);
  310. /// Memory manager for this process
  311. std::unique_ptr<Memory::PageTable> page_table;
  312. /// Current status of the process
  313. ProcessStatus status{};
  314. /// The ID of this process
  315. u64 process_id = 0;
  316. /// Title ID corresponding to the process
  317. u64 program_id = 0;
  318. /// Specifies additional memory to be reserved for the process's memory management by the
  319. /// system. When this is non-zero, secure memory is allocated and used for page table allocation
  320. /// instead of using the normal global page tables/memory block management.
  321. u32 system_resource_size = 0;
  322. /// Resource limit descriptor for this process
  323. std::shared_ptr<KResourceLimit> resource_limit;
  324. /// The ideal CPU core for this process, threads are scheduled on this core by default.
  325. u8 ideal_core = 0;
  326. /// The Thread Local Storage area is allocated as processes create threads,
  327. /// each TLS area is 0x200 bytes, so one page (0x1000) is split up in 8 parts, and each part
  328. /// holds the TLS for a specific thread. This vector contains which parts are in use for each
  329. /// page as a bitmask.
  330. /// This vector will grow as more pages are allocated for new threads.
  331. std::vector<TLSPage> tls_pages;
  332. /// Contains the parsed process capability descriptors.
  333. ProcessCapabilities capabilities;
  334. /// Whether or not this process is AArch64, or AArch32.
  335. /// By default, we currently assume this is true, unless otherwise
  336. /// specified by metadata provided to the process during loading.
  337. bool is_64bit_process = true;
  338. /// Total running time for the process in ticks.
  339. u64 total_process_running_time_ticks = 0;
  340. /// Per-process handle table for storing created object handles in.
  341. HandleTable handle_table;
  342. /// Per-process address arbiter.
  343. KAddressArbiter address_arbiter;
  344. /// The per-process mutex lock instance used for handling various
  345. /// forms of services, such as lock arbitration, and condition
  346. /// variable related facilities.
  347. KConditionVariable condition_var;
  348. /// Address indicating the location of the process' dedicated TLS region.
  349. VAddr tls_region_address = 0;
  350. /// Random values for svcGetInfo RandomEntropy
  351. std::array<u64, RANDOM_ENTROPY_SIZE> random_entropy{};
  352. /// List of threads that are running with this process as their owner.
  353. std::list<const KThread*> thread_list;
  354. /// Address of the top of the main thread's stack
  355. VAddr main_thread_stack_top{};
  356. /// Size of the main thread's stack
  357. std::size_t main_thread_stack_size{};
  358. /// Memory usage capacity for the process
  359. std::size_t memory_usage_capacity{};
  360. /// Process total image size
  361. std::size_t image_size{};
  362. /// Name of this process
  363. std::string name;
  364. /// Schedule count of this process
  365. s64 schedule_count{};
  366. bool is_signaled{};
  367. bool is_suspended{};
  368. std::atomic<s32> num_created_threads{};
  369. std::atomic<u16> num_threads{};
  370. u16 peak_num_threads{};
  371. std::array<KThread*, Core::Hardware::NUM_CPU_CORES> running_threads{};
  372. std::array<u64, Core::Hardware::NUM_CPU_CORES> running_thread_idle_counts{};
  373. std::array<KThread*, Core::Hardware::NUM_CPU_CORES> pinned_threads{};
  374. KThread* exception_thread{};
  375. KLightLock state_lock;
  376. /// System context
  377. Core::System& system;
  378. };
  379. } // namespace Kernel