k_process.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. // SPDX-FileCopyrightText: 2015 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <bitset>
  5. #include <ctime>
  6. #include <memory>
  7. #include <random>
  8. #include "common/alignment.h"
  9. #include "common/assert.h"
  10. #include "common/logging/log.h"
  11. #include "common/scope_exit.h"
  12. #include "common/settings.h"
  13. #include "core/core.h"
  14. #include "core/file_sys/program_metadata.h"
  15. #include "core/hle/kernel/code_set.h"
  16. #include "core/hle/kernel/k_memory_block_manager.h"
  17. #include "core/hle/kernel/k_page_table.h"
  18. #include "core/hle/kernel/k_process.h"
  19. #include "core/hle/kernel/k_resource_limit.h"
  20. #include "core/hle/kernel/k_scheduler.h"
  21. #include "core/hle/kernel/k_scoped_resource_reservation.h"
  22. #include "core/hle/kernel/k_shared_memory.h"
  23. #include "core/hle/kernel/k_shared_memory_info.h"
  24. #include "core/hle/kernel/k_thread.h"
  25. #include "core/hle/kernel/kernel.h"
  26. #include "core/hle/kernel/svc_results.h"
  27. #include "core/memory.h"
  28. namespace Kernel {
  29. namespace {
  30. /**
  31. * Sets up the primary application thread
  32. *
  33. * @param system The system instance to create the main thread under.
  34. * @param owner_process The parent process for the main thread
  35. * @param priority The priority to give the main thread
  36. */
  37. void SetupMainThread(Core::System& system, KProcess& owner_process, u32 priority, VAddr stack_top) {
  38. const VAddr entry_point = owner_process.PageTable().GetCodeRegionStart();
  39. ASSERT(owner_process.GetResourceLimit()->Reserve(LimitableResource::ThreadCountMax, 1));
  40. KThread* thread = KThread::Create(system.Kernel());
  41. SCOPE_EXIT({ thread->Close(); });
  42. ASSERT(KThread::InitializeUserThread(system, thread, entry_point, 0, stack_top, priority,
  43. owner_process.GetIdealCoreId(), &owner_process)
  44. .IsSuccess());
  45. // Register 1 must be a handle to the main thread
  46. Handle thread_handle{};
  47. owner_process.GetHandleTable().Add(&thread_handle, thread);
  48. thread->SetName("main");
  49. thread->GetContext32().cpu_registers[0] = 0;
  50. thread->GetContext64().cpu_registers[0] = 0;
  51. thread->GetContext32().cpu_registers[1] = thread_handle;
  52. thread->GetContext64().cpu_registers[1] = thread_handle;
  53. if (system.DebuggerEnabled()) {
  54. thread->RequestSuspend(SuspendType::Debug);
  55. }
  56. // Run our thread.
  57. void(thread->Run());
  58. }
  59. } // Anonymous namespace
  60. Result KProcess::Initialize(KProcess* process, Core::System& system, std::string process_name,
  61. ProcessType type, KResourceLimit* res_limit) {
  62. auto& kernel = system.Kernel();
  63. process->name = std::move(process_name);
  64. process->resource_limit = res_limit;
  65. process->system_resource_address = 0;
  66. process->state = State::Created;
  67. process->program_id = 0;
  68. process->process_id = type == ProcessType::KernelInternal ? kernel.CreateNewKernelProcessID()
  69. : kernel.CreateNewUserProcessID();
  70. process->capabilities.InitializeForMetadatalessProcess();
  71. process->is_initialized = true;
  72. std::mt19937 rng(Settings::values.rng_seed.GetValue().value_or(std::time(nullptr)));
  73. std::uniform_int_distribution<u64> distribution;
  74. std::generate(process->random_entropy.begin(), process->random_entropy.end(),
  75. [&] { return distribution(rng); });
  76. kernel.AppendNewProcess(process);
  77. // Clear remaining fields.
  78. process->num_running_threads = 0;
  79. process->is_signaled = false;
  80. process->exception_thread = nullptr;
  81. process->is_suspended = false;
  82. process->schedule_count = 0;
  83. process->is_handle_table_initialized = false;
  84. // Open a reference to the resource limit.
  85. process->resource_limit->Open();
  86. R_SUCCEED();
  87. }
  88. void KProcess::DoWorkerTaskImpl() {
  89. UNIMPLEMENTED();
  90. }
  91. KResourceLimit* KProcess::GetResourceLimit() const {
  92. return resource_limit;
  93. }
  94. void KProcess::IncrementRunningThreadCount() {
  95. ASSERT(num_running_threads.load() >= 0);
  96. ++num_running_threads;
  97. }
  98. void KProcess::DecrementRunningThreadCount() {
  99. ASSERT(num_running_threads.load() > 0);
  100. if (const auto prev = num_running_threads--; prev == 1) {
  101. // TODO(bunnei): Process termination to be implemented when multiprocess is supported.
  102. UNIMPLEMENTED_MSG("KProcess termination is not implemennted!");
  103. }
  104. }
  105. u64 KProcess::GetTotalPhysicalMemoryAvailable() {
  106. const u64 capacity{resource_limit->GetFreeValue(LimitableResource::PhysicalMemoryMax) +
  107. page_table.GetNormalMemorySize() + GetSystemResourceSize() + image_size +
  108. main_thread_stack_size};
  109. if (const auto pool_size = kernel.MemoryManager().GetSize(KMemoryManager::Pool::Application);
  110. capacity != pool_size) {
  111. LOG_WARNING(Kernel, "capacity {} != application pool size {}", capacity, pool_size);
  112. }
  113. if (capacity < memory_usage_capacity) {
  114. return capacity;
  115. }
  116. return memory_usage_capacity;
  117. }
  118. u64 KProcess::GetTotalPhysicalMemoryAvailableWithoutSystemResource() {
  119. return GetTotalPhysicalMemoryAvailable() - GetSystemResourceSize();
  120. }
  121. u64 KProcess::GetTotalPhysicalMemoryUsed() {
  122. return image_size + main_thread_stack_size + page_table.GetNormalMemorySize() +
  123. GetSystemResourceSize();
  124. }
  125. u64 KProcess::GetTotalPhysicalMemoryUsedWithoutSystemResource() {
  126. return GetTotalPhysicalMemoryUsed() - GetSystemResourceUsage();
  127. }
  128. bool KProcess::ReleaseUserException(KThread* thread) {
  129. KScopedSchedulerLock sl{kernel};
  130. if (exception_thread == thread) {
  131. exception_thread = nullptr;
  132. // Remove waiter thread.
  133. s32 num_waiters{};
  134. if (KThread* next = thread->RemoveWaiterByKey(
  135. std::addressof(num_waiters),
  136. reinterpret_cast<uintptr_t>(std::addressof(exception_thread)));
  137. next != nullptr) {
  138. next->EndWait(ResultSuccess);
  139. }
  140. KScheduler::SetSchedulerUpdateNeeded(kernel);
  141. return true;
  142. } else {
  143. return false;
  144. }
  145. }
  146. void KProcess::PinCurrentThread(s32 core_id) {
  147. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  148. // Get the current thread.
  149. KThread* cur_thread =
  150. kernel.Scheduler(static_cast<std::size_t>(core_id)).GetSchedulerCurrentThread();
  151. // If the thread isn't terminated, pin it.
  152. if (!cur_thread->IsTerminationRequested()) {
  153. // Pin it.
  154. PinThread(core_id, cur_thread);
  155. cur_thread->Pin(core_id);
  156. // An update is needed.
  157. KScheduler::SetSchedulerUpdateNeeded(kernel);
  158. }
  159. }
  160. void KProcess::UnpinCurrentThread(s32 core_id) {
  161. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  162. // Get the current thread.
  163. KThread* cur_thread =
  164. kernel.Scheduler(static_cast<std::size_t>(core_id)).GetSchedulerCurrentThread();
  165. // Unpin it.
  166. cur_thread->Unpin();
  167. UnpinThread(core_id, cur_thread);
  168. // An update is needed.
  169. KScheduler::SetSchedulerUpdateNeeded(kernel);
  170. }
  171. void KProcess::UnpinThread(KThread* thread) {
  172. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  173. // Get the thread's core id.
  174. const auto core_id = thread->GetActiveCore();
  175. // Unpin it.
  176. UnpinThread(core_id, thread);
  177. thread->Unpin();
  178. // An update is needed.
  179. KScheduler::SetSchedulerUpdateNeeded(kernel);
  180. }
  181. Result KProcess::AddSharedMemory(KSharedMemory* shmem, [[maybe_unused]] VAddr address,
  182. [[maybe_unused]] size_t size) {
  183. // Lock ourselves, to prevent concurrent access.
  184. KScopedLightLock lk(state_lock);
  185. // Try to find an existing info for the memory.
  186. KSharedMemoryInfo* shemen_info = nullptr;
  187. const auto iter = std::find_if(
  188. shared_memory_list.begin(), shared_memory_list.end(),
  189. [shmem](const KSharedMemoryInfo* info) { return info->GetSharedMemory() == shmem; });
  190. if (iter != shared_memory_list.end()) {
  191. shemen_info = *iter;
  192. }
  193. if (shemen_info == nullptr) {
  194. shemen_info = KSharedMemoryInfo::Allocate(kernel);
  195. R_UNLESS(shemen_info != nullptr, ResultOutOfMemory);
  196. shemen_info->Initialize(shmem);
  197. shared_memory_list.push_back(shemen_info);
  198. }
  199. // Open a reference to the shared memory and its info.
  200. shmem->Open();
  201. shemen_info->Open();
  202. R_SUCCEED();
  203. }
  204. void KProcess::RemoveSharedMemory(KSharedMemory* shmem, [[maybe_unused]] VAddr address,
  205. [[maybe_unused]] size_t size) {
  206. // Lock ourselves, to prevent concurrent access.
  207. KScopedLightLock lk(state_lock);
  208. KSharedMemoryInfo* shemen_info = nullptr;
  209. const auto iter = std::find_if(
  210. shared_memory_list.begin(), shared_memory_list.end(),
  211. [shmem](const KSharedMemoryInfo* info) { return info->GetSharedMemory() == shmem; });
  212. if (iter != shared_memory_list.end()) {
  213. shemen_info = *iter;
  214. }
  215. ASSERT(shemen_info != nullptr);
  216. if (shemen_info->Close()) {
  217. shared_memory_list.erase(iter);
  218. KSharedMemoryInfo::Free(kernel, shemen_info);
  219. }
  220. // Close a reference to the shared memory.
  221. shmem->Close();
  222. }
  223. void KProcess::RegisterThread(KThread* thread) {
  224. KScopedLightLock lk{list_lock};
  225. thread_list.push_back(thread);
  226. }
  227. void KProcess::UnregisterThread(KThread* thread) {
  228. KScopedLightLock lk{list_lock};
  229. thread_list.remove(thread);
  230. }
  231. Result KProcess::Reset() {
  232. // Lock the process and the scheduler.
  233. KScopedLightLock lk(state_lock);
  234. KScopedSchedulerLock sl{kernel};
  235. // Validate that we're in a state that we can reset.
  236. R_UNLESS(state != State::Terminated, ResultInvalidState);
  237. R_UNLESS(is_signaled, ResultInvalidState);
  238. // Clear signaled.
  239. is_signaled = false;
  240. R_SUCCEED();
  241. }
  242. Result KProcess::SetActivity(ProcessActivity activity) {
  243. // Lock ourselves and the scheduler.
  244. KScopedLightLock lk{state_lock};
  245. KScopedLightLock list_lk{list_lock};
  246. KScopedSchedulerLock sl{kernel};
  247. // Validate our state.
  248. R_UNLESS(state != State::Terminating, ResultInvalidState);
  249. R_UNLESS(state != State::Terminated, ResultInvalidState);
  250. // Either pause or resume.
  251. if (activity == ProcessActivity::Paused) {
  252. // Verify that we're not suspended.
  253. R_UNLESS(!is_suspended, ResultInvalidState);
  254. // Suspend all threads.
  255. for (auto* thread : GetThreadList()) {
  256. thread->RequestSuspend(SuspendType::Process);
  257. }
  258. // Set ourselves as suspended.
  259. SetSuspended(true);
  260. } else {
  261. ASSERT(activity == ProcessActivity::Runnable);
  262. // Verify that we're suspended.
  263. R_UNLESS(is_suspended, ResultInvalidState);
  264. // Resume all threads.
  265. for (auto* thread : GetThreadList()) {
  266. thread->Resume(SuspendType::Process);
  267. }
  268. // Set ourselves as resumed.
  269. SetSuspended(false);
  270. }
  271. R_SUCCEED();
  272. }
  273. Result KProcess::LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std::size_t code_size) {
  274. program_id = metadata.GetTitleID();
  275. ideal_core = metadata.GetMainThreadCore();
  276. is_64bit_process = metadata.Is64BitProgram();
  277. system_resource_size = metadata.GetSystemResourceSize();
  278. image_size = code_size;
  279. // We currently do not support process-specific system resource
  280. UNIMPLEMENTED_IF(system_resource_size != 0);
  281. KScopedResourceReservation memory_reservation(
  282. resource_limit, LimitableResource::PhysicalMemoryMax, code_size + system_resource_size);
  283. if (!memory_reservation.Succeeded()) {
  284. LOG_ERROR(Kernel, "Could not reserve process memory requirements of size {:X} bytes",
  285. code_size + system_resource_size);
  286. R_RETURN(ResultLimitReached);
  287. }
  288. // Initialize proces address space
  289. if (const Result result{page_table.InitializeForProcess(
  290. metadata.GetAddressSpaceType(), false, false, false, KMemoryManager::Pool::Application,
  291. 0x8000000, code_size, &kernel.GetSystemSystemResource(), resource_limit)};
  292. result.IsError()) {
  293. R_RETURN(result);
  294. }
  295. // Map process code region
  296. if (const Result result{page_table.MapProcessCode(page_table.GetCodeRegionStart(),
  297. code_size / PageSize, KMemoryState::Code,
  298. KMemoryPermission::None)};
  299. result.IsError()) {
  300. R_RETURN(result);
  301. }
  302. // Initialize process capabilities
  303. const auto& caps{metadata.GetKernelCapabilities()};
  304. if (const Result result{
  305. capabilities.InitializeForUserProcess(caps.data(), caps.size(), page_table)};
  306. result.IsError()) {
  307. R_RETURN(result);
  308. }
  309. // Set memory usage capacity
  310. switch (metadata.GetAddressSpaceType()) {
  311. case FileSys::ProgramAddressSpaceType::Is32Bit:
  312. case FileSys::ProgramAddressSpaceType::Is36Bit:
  313. case FileSys::ProgramAddressSpaceType::Is39Bit:
  314. memory_usage_capacity = page_table.GetHeapRegionEnd() - page_table.GetHeapRegionStart();
  315. break;
  316. case FileSys::ProgramAddressSpaceType::Is32BitNoMap:
  317. memory_usage_capacity = page_table.GetHeapRegionEnd() - page_table.GetHeapRegionStart() +
  318. page_table.GetAliasRegionEnd() - page_table.GetAliasRegionStart();
  319. break;
  320. default:
  321. ASSERT(false);
  322. }
  323. // Create TLS region
  324. R_TRY(this->CreateThreadLocalRegion(std::addressof(plr_address)));
  325. memory_reservation.Commit();
  326. R_RETURN(handle_table.Initialize(capabilities.GetHandleTableSize()));
  327. }
  328. void KProcess::Run(s32 main_thread_priority, u64 stack_size) {
  329. AllocateMainThreadStack(stack_size);
  330. resource_limit->Reserve(LimitableResource::ThreadCountMax, 1);
  331. resource_limit->Reserve(LimitableResource::PhysicalMemoryMax, main_thread_stack_size);
  332. const std::size_t heap_capacity{memory_usage_capacity - (main_thread_stack_size + image_size)};
  333. ASSERT(!page_table.SetMaxHeapSize(heap_capacity).IsError());
  334. ChangeState(State::Running);
  335. SetupMainThread(kernel.System(), *this, main_thread_priority, main_thread_stack_top);
  336. }
  337. void KProcess::PrepareForTermination() {
  338. ChangeState(State::Terminating);
  339. const auto stop_threads = [this](const std::vector<KThread*>& in_thread_list) {
  340. for (auto* thread : in_thread_list) {
  341. if (thread->GetOwnerProcess() != this)
  342. continue;
  343. if (thread == GetCurrentThreadPointer(kernel))
  344. continue;
  345. // TODO(Subv): When are the other running/ready threads terminated?
  346. ASSERT_MSG(thread->GetState() == ThreadState::Waiting,
  347. "Exiting processes with non-waiting threads is currently unimplemented");
  348. thread->Exit();
  349. }
  350. };
  351. stop_threads(kernel.System().GlobalSchedulerContext().GetThreadList());
  352. this->DeleteThreadLocalRegion(plr_address);
  353. plr_address = 0;
  354. if (resource_limit) {
  355. resource_limit->Release(LimitableResource::PhysicalMemoryMax,
  356. main_thread_stack_size + image_size);
  357. }
  358. ChangeState(State::Terminated);
  359. }
  360. void KProcess::Finalize() {
  361. // Free all shared memory infos.
  362. {
  363. auto it = shared_memory_list.begin();
  364. while (it != shared_memory_list.end()) {
  365. KSharedMemoryInfo* info = *it;
  366. KSharedMemory* shmem = info->GetSharedMemory();
  367. while (!info->Close()) {
  368. shmem->Close();
  369. }
  370. shmem->Close();
  371. it = shared_memory_list.erase(it);
  372. KSharedMemoryInfo::Free(kernel, info);
  373. }
  374. }
  375. // Release memory to the resource limit.
  376. if (resource_limit != nullptr) {
  377. resource_limit->Close();
  378. resource_limit = nullptr;
  379. }
  380. // Finalize the page table.
  381. page_table.Finalize();
  382. // Perform inherited finalization.
  383. KAutoObjectWithSlabHeapAndContainer<KProcess, KWorkerTask>::Finalize();
  384. }
  385. Result KProcess::CreateThreadLocalRegion(VAddr* out) {
  386. KThreadLocalPage* tlp = nullptr;
  387. VAddr tlr = 0;
  388. // See if we can get a region from a partially used TLP.
  389. {
  390. KScopedSchedulerLock sl{kernel};
  391. if (auto it = partially_used_tlp_tree.begin(); it != partially_used_tlp_tree.end()) {
  392. tlr = it->Reserve();
  393. ASSERT(tlr != 0);
  394. if (it->IsAllUsed()) {
  395. tlp = std::addressof(*it);
  396. partially_used_tlp_tree.erase(it);
  397. fully_used_tlp_tree.insert(*tlp);
  398. }
  399. *out = tlr;
  400. R_SUCCEED();
  401. }
  402. }
  403. // Allocate a new page.
  404. tlp = KThreadLocalPage::Allocate(kernel);
  405. R_UNLESS(tlp != nullptr, ResultOutOfMemory);
  406. auto tlp_guard = SCOPE_GUARD({ KThreadLocalPage::Free(kernel, tlp); });
  407. // Initialize the new page.
  408. R_TRY(tlp->Initialize(kernel, this));
  409. // Reserve a TLR.
  410. tlr = tlp->Reserve();
  411. ASSERT(tlr != 0);
  412. // Insert into our tree.
  413. {
  414. KScopedSchedulerLock sl{kernel};
  415. if (tlp->IsAllUsed()) {
  416. fully_used_tlp_tree.insert(*tlp);
  417. } else {
  418. partially_used_tlp_tree.insert(*tlp);
  419. }
  420. }
  421. // We succeeded!
  422. tlp_guard.Cancel();
  423. *out = tlr;
  424. R_SUCCEED();
  425. }
  426. Result KProcess::DeleteThreadLocalRegion(VAddr addr) {
  427. KThreadLocalPage* page_to_free = nullptr;
  428. // Release the region.
  429. {
  430. KScopedSchedulerLock sl{kernel};
  431. // Try to find the page in the partially used list.
  432. auto it = partially_used_tlp_tree.find_key(Common::AlignDown(addr, PageSize));
  433. if (it == partially_used_tlp_tree.end()) {
  434. // If we don't find it, it has to be in the fully used list.
  435. it = fully_used_tlp_tree.find_key(Common::AlignDown(addr, PageSize));
  436. R_UNLESS(it != fully_used_tlp_tree.end(), ResultInvalidAddress);
  437. // Release the region.
  438. it->Release(addr);
  439. // Move the page out of the fully used list.
  440. KThreadLocalPage* tlp = std::addressof(*it);
  441. fully_used_tlp_tree.erase(it);
  442. if (tlp->IsAllFree()) {
  443. page_to_free = tlp;
  444. } else {
  445. partially_used_tlp_tree.insert(*tlp);
  446. }
  447. } else {
  448. // Release the region.
  449. it->Release(addr);
  450. // Handle the all-free case.
  451. KThreadLocalPage* tlp = std::addressof(*it);
  452. if (tlp->IsAllFree()) {
  453. partially_used_tlp_tree.erase(it);
  454. page_to_free = tlp;
  455. }
  456. }
  457. }
  458. // If we should free the page it was in, do so.
  459. if (page_to_free != nullptr) {
  460. page_to_free->Finalize();
  461. KThreadLocalPage::Free(kernel, page_to_free);
  462. }
  463. R_SUCCEED();
  464. }
  465. bool KProcess::InsertWatchpoint(Core::System& system, VAddr addr, u64 size,
  466. DebugWatchpointType type) {
  467. const auto watch{std::find_if(watchpoints.begin(), watchpoints.end(), [&](const auto& wp) {
  468. return wp.type == DebugWatchpointType::None;
  469. })};
  470. if (watch == watchpoints.end()) {
  471. return false;
  472. }
  473. watch->start_address = addr;
  474. watch->end_address = addr + size;
  475. watch->type = type;
  476. for (VAddr page = Common::AlignDown(addr, PageSize); page < addr + size; page += PageSize) {
  477. debug_page_refcounts[page]++;
  478. system.Memory().MarkRegionDebug(page, PageSize, true);
  479. }
  480. return true;
  481. }
  482. bool KProcess::RemoveWatchpoint(Core::System& system, VAddr addr, u64 size,
  483. DebugWatchpointType type) {
  484. const auto watch{std::find_if(watchpoints.begin(), watchpoints.end(), [&](const auto& wp) {
  485. return wp.start_address == addr && wp.end_address == addr + size && wp.type == type;
  486. })};
  487. if (watch == watchpoints.end()) {
  488. return false;
  489. }
  490. watch->start_address = 0;
  491. watch->end_address = 0;
  492. watch->type = DebugWatchpointType::None;
  493. for (VAddr page = Common::AlignDown(addr, PageSize); page < addr + size; page += PageSize) {
  494. debug_page_refcounts[page]--;
  495. if (!debug_page_refcounts[page]) {
  496. system.Memory().MarkRegionDebug(page, PageSize, false);
  497. }
  498. }
  499. return true;
  500. }
  501. void KProcess::LoadModule(CodeSet code_set, VAddr base_addr) {
  502. const auto ReprotectSegment = [&](const CodeSet::Segment& segment,
  503. Svc::MemoryPermission permission) {
  504. page_table.SetProcessMemoryPermission(segment.addr + base_addr, segment.size, permission);
  505. };
  506. kernel.System().Memory().WriteBlock(*this, base_addr, code_set.memory.data(),
  507. code_set.memory.size());
  508. ReprotectSegment(code_set.CodeSegment(), Svc::MemoryPermission::ReadExecute);
  509. ReprotectSegment(code_set.RODataSegment(), Svc::MemoryPermission::Read);
  510. ReprotectSegment(code_set.DataSegment(), Svc::MemoryPermission::ReadWrite);
  511. }
  512. bool KProcess::IsSignaled() const {
  513. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  514. return is_signaled;
  515. }
  516. KProcess::KProcess(KernelCore& kernel_)
  517. : KAutoObjectWithSlabHeapAndContainer{kernel_}, page_table{kernel_.System()},
  518. handle_table{kernel_}, address_arbiter{kernel_.System()}, condition_var{kernel_.System()},
  519. state_lock{kernel_}, list_lock{kernel_} {}
  520. KProcess::~KProcess() = default;
  521. void KProcess::ChangeState(State new_state) {
  522. if (state == new_state) {
  523. return;
  524. }
  525. state = new_state;
  526. is_signaled = true;
  527. NotifyAvailable();
  528. }
  529. Result KProcess::AllocateMainThreadStack(std::size_t stack_size) {
  530. ASSERT(stack_size);
  531. // The kernel always ensures that the given stack size is page aligned.
  532. main_thread_stack_size = Common::AlignUp(stack_size, PageSize);
  533. const VAddr start{page_table.GetStackRegionStart()};
  534. const std::size_t size{page_table.GetStackRegionEnd() - start};
  535. CASCADE_RESULT(main_thread_stack_top,
  536. page_table.AllocateAndMapMemory(
  537. main_thread_stack_size / PageSize, PageSize, false, start, size / PageSize,
  538. KMemoryState::Stack, KMemoryPermission::UserReadWrite));
  539. main_thread_stack_top += main_thread_stack_size;
  540. R_SUCCEED();
  541. }
  542. } // namespace Kernel