process.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // Copyright 2015 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <memory>
  6. #include <random>
  7. #include "common/assert.h"
  8. #include "common/logging/log.h"
  9. #include "core/core.h"
  10. #include "core/file_sys/program_metadata.h"
  11. #include "core/hle/kernel/code_set.h"
  12. #include "core/hle/kernel/errors.h"
  13. #include "core/hle/kernel/kernel.h"
  14. #include "core/hle/kernel/process.h"
  15. #include "core/hle/kernel/resource_limit.h"
  16. #include "core/hle/kernel/scheduler.h"
  17. #include "core/hle/kernel/thread.h"
  18. #include "core/hle/kernel/vm_manager.h"
  19. #include "core/memory.h"
  20. #include "core/settings.h"
  21. namespace Kernel {
  22. namespace {
  23. /**
  24. * Sets up the primary application thread
  25. *
  26. * @param owner_process The parent process for the main thread
  27. * @param kernel The kernel instance to create the main thread under.
  28. * @param entry_point The address at which the thread should start execution
  29. * @param priority The priority to give the main thread
  30. */
  31. void SetupMainThread(Process& owner_process, KernelCore& kernel, VAddr entry_point, u32 priority) {
  32. // Setup page table so we can write to memory
  33. Memory::SetCurrentPageTable(&owner_process.VMManager().page_table);
  34. // Initialize new "main" thread
  35. const VAddr stack_top = owner_process.VMManager().GetTLSIORegionEndAddress();
  36. auto thread_res = Thread::Create(kernel, "main", entry_point, priority, 0,
  37. owner_process.GetIdealCore(), stack_top, owner_process);
  38. SharedPtr<Thread> thread = std::move(thread_res).Unwrap();
  39. // Register 1 must be a handle to the main thread
  40. const Handle guest_handle = owner_process.GetHandleTable().Create(thread).Unwrap();
  41. thread->SetGuestHandle(guest_handle);
  42. thread->GetContext().cpu_registers[1] = guest_handle;
  43. // Threads by default are dormant, wake up the main thread so it runs when the scheduler fires
  44. thread->ResumeFromWait();
  45. }
  46. } // Anonymous namespace
  47. SharedPtr<Process> Process::Create(Core::System& system, std::string&& name) {
  48. auto& kernel = system.Kernel();
  49. SharedPtr<Process> process(new Process(system));
  50. process->name = std::move(name);
  51. process->resource_limit = kernel.GetSystemResourceLimit();
  52. process->status = ProcessStatus::Created;
  53. process->program_id = 0;
  54. process->process_id = kernel.CreateNewProcessID();
  55. process->capabilities.InitializeForMetadatalessProcess();
  56. std::mt19937 rng(Settings::values.rng_seed.value_or(0));
  57. std::uniform_int_distribution<u64> distribution;
  58. std::generate(process->random_entropy.begin(), process->random_entropy.end(),
  59. [&] { return distribution(rng); });
  60. kernel.AppendNewProcess(process);
  61. return process;
  62. }
  63. SharedPtr<ResourceLimit> Process::GetResourceLimit() const {
  64. return resource_limit;
  65. }
  66. ResultCode Process::ClearSignalState() {
  67. if (status == ProcessStatus::Exited) {
  68. LOG_ERROR(Kernel, "called on a terminated process instance.");
  69. return ERR_INVALID_STATE;
  70. }
  71. if (!is_signaled) {
  72. LOG_ERROR(Kernel, "called on a process instance that isn't signaled.");
  73. return ERR_INVALID_STATE;
  74. }
  75. is_signaled = false;
  76. return RESULT_SUCCESS;
  77. }
  78. ResultCode Process::LoadFromMetadata(const FileSys::ProgramMetadata& metadata) {
  79. program_id = metadata.GetTitleID();
  80. ideal_core = metadata.GetMainThreadCore();
  81. is_64bit_process = metadata.Is64BitProgram();
  82. vm_manager.Reset(metadata.GetAddressSpaceType());
  83. const auto& caps = metadata.GetKernelCapabilities();
  84. const auto capability_init_result =
  85. capabilities.InitializeForUserProcess(caps.data(), caps.size(), vm_manager);
  86. if (capability_init_result.IsError()) {
  87. return capability_init_result;
  88. }
  89. return handle_table.SetSize(capabilities.GetHandleTableSize());
  90. }
  91. void Process::Run(VAddr entry_point, s32 main_thread_priority, u32 stack_size) {
  92. // Allocate and map the main thread stack
  93. // TODO(bunnei): This is heap area that should be allocated by the kernel and not mapped as part
  94. // of the user address space.
  95. vm_manager
  96. .MapMemoryBlock(vm_manager.GetTLSIORegionEndAddress() - stack_size,
  97. std::make_shared<std::vector<u8>>(stack_size, 0), 0, stack_size,
  98. MemoryState::Stack)
  99. .Unwrap();
  100. vm_manager.LogLayout();
  101. ChangeStatus(ProcessStatus::Running);
  102. SetupMainThread(*this, kernel, entry_point, main_thread_priority);
  103. }
  104. void Process::PrepareForTermination() {
  105. ChangeStatus(ProcessStatus::Exiting);
  106. const auto stop_threads = [this](const std::vector<SharedPtr<Thread>>& thread_list) {
  107. for (auto& thread : thread_list) {
  108. if (thread->GetOwnerProcess() != this)
  109. continue;
  110. if (thread == system.CurrentScheduler().GetCurrentThread())
  111. continue;
  112. // TODO(Subv): When are the other running/ready threads terminated?
  113. ASSERT_MSG(thread->GetStatus() == ThreadStatus::WaitSynchAny ||
  114. thread->GetStatus() == ThreadStatus::WaitSynchAll,
  115. "Exiting processes with non-waiting threads is currently unimplemented");
  116. thread->Stop();
  117. }
  118. };
  119. stop_threads(system.Scheduler(0).GetThreadList());
  120. stop_threads(system.Scheduler(1).GetThreadList());
  121. stop_threads(system.Scheduler(2).GetThreadList());
  122. stop_threads(system.Scheduler(3).GetThreadList());
  123. ChangeStatus(ProcessStatus::Exited);
  124. }
  125. /**
  126. * Finds a free location for the TLS section of a thread.
  127. * @param tls_slots The TLS page array of the thread's owner process.
  128. * Returns a tuple of (page, slot, alloc_needed) where:
  129. * page: The index of the first allocated TLS page that has free slots.
  130. * slot: The index of the first free slot in the indicated page.
  131. * alloc_needed: Whether there's a need to allocate a new TLS page (All pages are full).
  132. */
  133. static std::tuple<std::size_t, std::size_t, bool> FindFreeThreadLocalSlot(
  134. const std::vector<std::bitset<8>>& tls_slots) {
  135. // Iterate over all the allocated pages, and try to find one where not all slots are used.
  136. for (std::size_t page = 0; page < tls_slots.size(); ++page) {
  137. const auto& page_tls_slots = tls_slots[page];
  138. if (!page_tls_slots.all()) {
  139. // We found a page with at least one free slot, find which slot it is
  140. for (std::size_t slot = 0; slot < page_tls_slots.size(); ++slot) {
  141. if (!page_tls_slots.test(slot)) {
  142. return std::make_tuple(page, slot, false);
  143. }
  144. }
  145. }
  146. }
  147. return std::make_tuple(0, 0, true);
  148. }
  149. VAddr Process::MarkNextAvailableTLSSlotAsUsed(Thread& thread) {
  150. auto [available_page, available_slot, needs_allocation] = FindFreeThreadLocalSlot(tls_slots);
  151. const VAddr tls_begin = vm_manager.GetTLSIORegionBaseAddress();
  152. if (needs_allocation) {
  153. tls_slots.emplace_back(0); // The page is completely available at the start
  154. available_page = tls_slots.size() - 1;
  155. available_slot = 0; // Use the first slot in the new page
  156. // Allocate some memory from the end of the linear heap for this region.
  157. auto& tls_memory = thread.GetTLSMemory();
  158. tls_memory->insert(tls_memory->end(), Memory::PAGE_SIZE, 0);
  159. vm_manager.RefreshMemoryBlockMappings(tls_memory.get());
  160. vm_manager.MapMemoryBlock(tls_begin + available_page * Memory::PAGE_SIZE, tls_memory, 0,
  161. Memory::PAGE_SIZE, MemoryState::ThreadLocal);
  162. }
  163. tls_slots[available_page].set(available_slot);
  164. return tls_begin + available_page * Memory::PAGE_SIZE + available_slot * Memory::TLS_ENTRY_SIZE;
  165. }
  166. void Process::FreeTLSSlot(VAddr tls_address) {
  167. const VAddr tls_base = tls_address - vm_manager.GetTLSIORegionBaseAddress();
  168. const VAddr tls_page = tls_base / Memory::PAGE_SIZE;
  169. const VAddr tls_slot = (tls_base % Memory::PAGE_SIZE) / Memory::TLS_ENTRY_SIZE;
  170. tls_slots[tls_page].reset(tls_slot);
  171. }
  172. void Process::LoadModule(CodeSet module_, VAddr base_addr) {
  173. const auto MapSegment = [&](const CodeSet::Segment& segment, VMAPermission permissions,
  174. MemoryState memory_state) {
  175. const auto vma = vm_manager
  176. .MapMemoryBlock(segment.addr + base_addr, module_.memory,
  177. segment.offset, segment.size, memory_state)
  178. .Unwrap();
  179. vm_manager.Reprotect(vma, permissions);
  180. };
  181. // Map CodeSet segments
  182. MapSegment(module_.CodeSegment(), VMAPermission::ReadExecute, MemoryState::CodeStatic);
  183. MapSegment(module_.RODataSegment(), VMAPermission::Read, MemoryState::CodeMutable);
  184. MapSegment(module_.DataSegment(), VMAPermission::ReadWrite, MemoryState::CodeMutable);
  185. // Clear instruction cache in CPU JIT
  186. system.InvalidateCpuInstructionCaches();
  187. }
  188. Process::Process(Core::System& system)
  189. : WaitObject{system.Kernel()}, address_arbiter{system}, system{system} {}
  190. Process::~Process() = default;
  191. void Process::Acquire(Thread* thread) {
  192. ASSERT_MSG(!ShouldWait(thread), "Object unavailable!");
  193. }
  194. bool Process::ShouldWait(Thread* thread) const {
  195. return !is_signaled;
  196. }
  197. void Process::ChangeStatus(ProcessStatus new_status) {
  198. if (status == new_status) {
  199. return;
  200. }
  201. status = new_status;
  202. is_signaled = true;
  203. WakeupAllWaitingThreads();
  204. }
  205. } // namespace Kernel