process.cpp 9.3 KB

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