k_process.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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(),
  44. std::addressof(owner_process))
  45. .IsSuccess());
  46. // Register 1 must be a handle to the main thread
  47. Handle thread_handle{};
  48. owner_process.GetHandleTable().Add(std::addressof(thread_handle), thread);
  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->m_resource_limit = res_limit;
  65. process->m_system_resource_address = 0;
  66. process->m_state = State::Created;
  67. process->m_program_id = 0;
  68. process->m_process_id = type == ProcessType::KernelInternal ? kernel.CreateNewKernelProcessID()
  69. : kernel.CreateNewUserProcessID();
  70. process->m_capabilities.InitializeForMetadatalessProcess();
  71. process->m_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->m_random_entropy.begin(), process->m_random_entropy.end(),
  75. [&] { return distribution(rng); });
  76. kernel.AppendNewProcess(process);
  77. // Clear remaining fields.
  78. process->m_num_running_threads = 0;
  79. process->m_is_signaled = false;
  80. process->m_exception_thread = nullptr;
  81. process->m_is_suspended = false;
  82. process->m_schedule_count = 0;
  83. process->m_is_handle_table_initialized = false;
  84. // Open a reference to the resource limit.
  85. process->m_resource_limit->Open();
  86. R_SUCCEED();
  87. }
  88. void KProcess::DoWorkerTaskImpl() {
  89. UNIMPLEMENTED();
  90. }
  91. KResourceLimit* KProcess::GetResourceLimit() const {
  92. return m_resource_limit;
  93. }
  94. void KProcess::IncrementRunningThreadCount() {
  95. ASSERT(m_num_running_threads.load() >= 0);
  96. ++m_num_running_threads;
  97. }
  98. void KProcess::DecrementRunningThreadCount() {
  99. ASSERT(m_num_running_threads.load() > 0);
  100. if (const auto prev = m_num_running_threads--; prev == 1) {
  101. // TODO(bunnei): Process termination to be implemented when multiprocess is supported.
  102. }
  103. }
  104. u64 KProcess::GetTotalPhysicalMemoryAvailable() {
  105. const u64 capacity{m_resource_limit->GetFreeValue(LimitableResource::PhysicalMemoryMax) +
  106. m_page_table.GetNormalMemorySize() + GetSystemResourceSize() + m_image_size +
  107. m_main_thread_stack_size};
  108. if (const auto pool_size = m_kernel.MemoryManager().GetSize(KMemoryManager::Pool::Application);
  109. capacity != pool_size) {
  110. LOG_WARNING(Kernel, "capacity {} != application pool size {}", capacity, pool_size);
  111. }
  112. if (capacity < m_memory_usage_capacity) {
  113. return capacity;
  114. }
  115. return m_memory_usage_capacity;
  116. }
  117. u64 KProcess::GetTotalPhysicalMemoryAvailableWithoutSystemResource() {
  118. return this->GetTotalPhysicalMemoryAvailable() - this->GetSystemResourceSize();
  119. }
  120. u64 KProcess::GetTotalPhysicalMemoryUsed() {
  121. return m_image_size + m_main_thread_stack_size + m_page_table.GetNormalMemorySize() +
  122. this->GetSystemResourceSize();
  123. }
  124. u64 KProcess::GetTotalPhysicalMemoryUsedWithoutSystemResource() {
  125. return this->GetTotalPhysicalMemoryUsed() - this->GetSystemResourceUsage();
  126. }
  127. bool KProcess::ReleaseUserException(KThread* thread) {
  128. KScopedSchedulerLock sl{m_kernel};
  129. if (m_exception_thread == thread) {
  130. m_exception_thread = nullptr;
  131. // Remove waiter thread.
  132. bool has_waiters{};
  133. if (KThread* next = thread->RemoveKernelWaiterByKey(
  134. std::addressof(has_waiters),
  135. reinterpret_cast<uintptr_t>(std::addressof(m_exception_thread)));
  136. next != nullptr) {
  137. next->EndWait(ResultSuccess);
  138. }
  139. KScheduler::SetSchedulerUpdateNeeded(m_kernel);
  140. return true;
  141. } else {
  142. return false;
  143. }
  144. }
  145. void KProcess::PinCurrentThread(s32 core_id) {
  146. ASSERT(KScheduler::IsSchedulerLockedByCurrentThread(m_kernel));
  147. // Get the current thread.
  148. KThread* cur_thread =
  149. m_kernel.Scheduler(static_cast<std::size_t>(core_id)).GetSchedulerCurrentThread();
  150. // If the thread isn't terminated, pin it.
  151. if (!cur_thread->IsTerminationRequested()) {
  152. // Pin it.
  153. this->PinThread(core_id, cur_thread);
  154. cur_thread->Pin(core_id);
  155. // An update is needed.
  156. KScheduler::SetSchedulerUpdateNeeded(m_kernel);
  157. }
  158. }
  159. void KProcess::UnpinCurrentThread(s32 core_id) {
  160. ASSERT(KScheduler::IsSchedulerLockedByCurrentThread(m_kernel));
  161. // Get the current thread.
  162. KThread* cur_thread =
  163. m_kernel.Scheduler(static_cast<std::size_t>(core_id)).GetSchedulerCurrentThread();
  164. // Unpin it.
  165. cur_thread->Unpin();
  166. this->UnpinThread(core_id, cur_thread);
  167. // An update is needed.
  168. KScheduler::SetSchedulerUpdateNeeded(m_kernel);
  169. }
  170. void KProcess::UnpinThread(KThread* thread) {
  171. ASSERT(KScheduler::IsSchedulerLockedByCurrentThread(m_kernel));
  172. // Get the thread's core id.
  173. const auto core_id = thread->GetActiveCore();
  174. // Unpin it.
  175. this->UnpinThread(core_id, thread);
  176. thread->Unpin();
  177. // An update is needed.
  178. KScheduler::SetSchedulerUpdateNeeded(m_kernel);
  179. }
  180. Result KProcess::AddSharedMemory(KSharedMemory* shmem, [[maybe_unused]] VAddr address,
  181. [[maybe_unused]] size_t size) {
  182. // Lock ourselves, to prevent concurrent access.
  183. KScopedLightLock lk(m_state_lock);
  184. // Try to find an existing info for the memory.
  185. KSharedMemoryInfo* shemen_info = nullptr;
  186. const auto iter = std::find_if(
  187. m_shared_memory_list.begin(), m_shared_memory_list.end(),
  188. [shmem](const KSharedMemoryInfo* info) { return info->GetSharedMemory() == shmem; });
  189. if (iter != m_shared_memory_list.end()) {
  190. shemen_info = *iter;
  191. }
  192. if (shemen_info == nullptr) {
  193. shemen_info = KSharedMemoryInfo::Allocate(m_kernel);
  194. R_UNLESS(shemen_info != nullptr, ResultOutOfMemory);
  195. shemen_info->Initialize(shmem);
  196. m_shared_memory_list.push_back(shemen_info);
  197. }
  198. // Open a reference to the shared memory and its info.
  199. shmem->Open();
  200. shemen_info->Open();
  201. R_SUCCEED();
  202. }
  203. void KProcess::RemoveSharedMemory(KSharedMemory* shmem, [[maybe_unused]] VAddr address,
  204. [[maybe_unused]] size_t size) {
  205. // Lock ourselves, to prevent concurrent access.
  206. KScopedLightLock lk(m_state_lock);
  207. KSharedMemoryInfo* shemen_info = nullptr;
  208. const auto iter = std::find_if(
  209. m_shared_memory_list.begin(), m_shared_memory_list.end(),
  210. [shmem](const KSharedMemoryInfo* info) { return info->GetSharedMemory() == shmem; });
  211. if (iter != m_shared_memory_list.end()) {
  212. shemen_info = *iter;
  213. }
  214. ASSERT(shemen_info != nullptr);
  215. if (shemen_info->Close()) {
  216. m_shared_memory_list.erase(iter);
  217. KSharedMemoryInfo::Free(m_kernel, shemen_info);
  218. }
  219. // Close a reference to the shared memory.
  220. shmem->Close();
  221. }
  222. void KProcess::RegisterThread(KThread* thread) {
  223. KScopedLightLock lk{m_list_lock};
  224. m_thread_list.push_back(thread);
  225. }
  226. void KProcess::UnregisterThread(KThread* thread) {
  227. KScopedLightLock lk{m_list_lock};
  228. m_thread_list.remove(thread);
  229. }
  230. u64 KProcess::GetFreeThreadCount() const {
  231. if (m_resource_limit != nullptr) {
  232. const auto current_value =
  233. m_resource_limit->GetCurrentValue(LimitableResource::ThreadCountMax);
  234. const auto limit_value = m_resource_limit->GetLimitValue(LimitableResource::ThreadCountMax);
  235. return limit_value - current_value;
  236. } else {
  237. return 0;
  238. }
  239. }
  240. Result KProcess::Reset() {
  241. // Lock the process and the scheduler.
  242. KScopedLightLock lk(m_state_lock);
  243. KScopedSchedulerLock sl{m_kernel};
  244. // Validate that we're in a state that we can reset.
  245. R_UNLESS(m_state != State::Terminated, ResultInvalidState);
  246. R_UNLESS(m_is_signaled, ResultInvalidState);
  247. // Clear signaled.
  248. m_is_signaled = false;
  249. R_SUCCEED();
  250. }
  251. Result KProcess::SetActivity(ProcessActivity activity) {
  252. // Lock ourselves and the scheduler.
  253. KScopedLightLock lk{m_state_lock};
  254. KScopedLightLock list_lk{m_list_lock};
  255. KScopedSchedulerLock sl{m_kernel};
  256. // Validate our state.
  257. R_UNLESS(m_state != State::Terminating, ResultInvalidState);
  258. R_UNLESS(m_state != State::Terminated, ResultInvalidState);
  259. // Either pause or resume.
  260. if (activity == ProcessActivity::Paused) {
  261. // Verify that we're not suspended.
  262. R_UNLESS(!m_is_suspended, ResultInvalidState);
  263. // Suspend all threads.
  264. for (auto* thread : this->GetThreadList()) {
  265. thread->RequestSuspend(SuspendType::Process);
  266. }
  267. // Set ourselves as suspended.
  268. this->SetSuspended(true);
  269. } else {
  270. ASSERT(activity == ProcessActivity::Runnable);
  271. // Verify that we're suspended.
  272. R_UNLESS(m_is_suspended, ResultInvalidState);
  273. // Resume all threads.
  274. for (auto* thread : this->GetThreadList()) {
  275. thread->Resume(SuspendType::Process);
  276. }
  277. // Set ourselves as resumed.
  278. this->SetSuspended(false);
  279. }
  280. R_SUCCEED();
  281. }
  282. Result KProcess::LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std::size_t code_size) {
  283. m_program_id = metadata.GetTitleID();
  284. m_ideal_core = metadata.GetMainThreadCore();
  285. m_is_64bit_process = metadata.Is64BitProgram();
  286. m_system_resource_size = metadata.GetSystemResourceSize();
  287. m_image_size = code_size;
  288. KScopedResourceReservation memory_reservation(
  289. m_resource_limit, LimitableResource::PhysicalMemoryMax, code_size + m_system_resource_size);
  290. if (!memory_reservation.Succeeded()) {
  291. LOG_ERROR(Kernel, "Could not reserve process memory requirements of size {:X} bytes",
  292. code_size + m_system_resource_size);
  293. R_RETURN(ResultLimitReached);
  294. }
  295. // Initialize process address space
  296. if (const Result result{m_page_table.InitializeForProcess(
  297. metadata.GetAddressSpaceType(), false, false, false, KMemoryManager::Pool::Application,
  298. 0x8000000, code_size, std::addressof(m_kernel.GetAppSystemResource()),
  299. m_resource_limit)};
  300. result.IsError()) {
  301. R_RETURN(result);
  302. }
  303. // Map process code region
  304. if (const Result result{m_page_table.MapProcessCode(m_page_table.GetCodeRegionStart(),
  305. code_size / PageSize, KMemoryState::Code,
  306. KMemoryPermission::None)};
  307. result.IsError()) {
  308. R_RETURN(result);
  309. }
  310. // Initialize process capabilities
  311. const auto& caps{metadata.GetKernelCapabilities()};
  312. if (const Result result{
  313. m_capabilities.InitializeForUserProcess(caps.data(), caps.size(), m_page_table)};
  314. result.IsError()) {
  315. R_RETURN(result);
  316. }
  317. // Set memory usage capacity
  318. switch (metadata.GetAddressSpaceType()) {
  319. case FileSys::ProgramAddressSpaceType::Is32Bit:
  320. case FileSys::ProgramAddressSpaceType::Is36Bit:
  321. case FileSys::ProgramAddressSpaceType::Is39Bit:
  322. m_memory_usage_capacity =
  323. m_page_table.GetHeapRegionEnd() - m_page_table.GetHeapRegionStart();
  324. break;
  325. case FileSys::ProgramAddressSpaceType::Is32BitNoMap:
  326. m_memory_usage_capacity =
  327. m_page_table.GetHeapRegionEnd() - m_page_table.GetHeapRegionStart() +
  328. m_page_table.GetAliasRegionEnd() - m_page_table.GetAliasRegionStart();
  329. break;
  330. default:
  331. ASSERT(false);
  332. break;
  333. }
  334. // Create TLS region
  335. R_TRY(this->CreateThreadLocalRegion(std::addressof(m_plr_address)));
  336. memory_reservation.Commit();
  337. R_RETURN(m_handle_table.Initialize(m_capabilities.GetHandleTableSize()));
  338. }
  339. void KProcess::Run(s32 main_thread_priority, u64 stack_size) {
  340. ASSERT(this->AllocateMainThreadStack(stack_size) == ResultSuccess);
  341. m_resource_limit->Reserve(LimitableResource::ThreadCountMax, 1);
  342. const std::size_t heap_capacity{m_memory_usage_capacity -
  343. (m_main_thread_stack_size + m_image_size)};
  344. ASSERT(!m_page_table.SetMaxHeapSize(heap_capacity).IsError());
  345. this->ChangeState(State::Running);
  346. SetupMainThread(m_kernel.System(), *this, main_thread_priority, m_main_thread_stack_top);
  347. }
  348. void KProcess::PrepareForTermination() {
  349. this->ChangeState(State::Terminating);
  350. const auto stop_threads = [this](const std::vector<KThread*>& in_thread_list) {
  351. for (auto* thread : in_thread_list) {
  352. if (thread->GetOwnerProcess() != this)
  353. continue;
  354. if (thread == GetCurrentThreadPointer(m_kernel))
  355. continue;
  356. // TODO(Subv): When are the other running/ready threads terminated?
  357. ASSERT_MSG(thread->GetState() == ThreadState::Waiting,
  358. "Exiting processes with non-waiting threads is currently unimplemented");
  359. thread->Exit();
  360. }
  361. };
  362. stop_threads(m_kernel.System().GlobalSchedulerContext().GetThreadList());
  363. this->DeleteThreadLocalRegion(m_plr_address);
  364. m_plr_address = 0;
  365. if (m_resource_limit) {
  366. m_resource_limit->Release(LimitableResource::PhysicalMemoryMax,
  367. m_main_thread_stack_size + m_image_size);
  368. }
  369. this->ChangeState(State::Terminated);
  370. }
  371. void KProcess::Finalize() {
  372. // Free all shared memory infos.
  373. {
  374. auto it = m_shared_memory_list.begin();
  375. while (it != m_shared_memory_list.end()) {
  376. KSharedMemoryInfo* info = *it;
  377. KSharedMemory* shmem = info->GetSharedMemory();
  378. while (!info->Close()) {
  379. shmem->Close();
  380. }
  381. shmem->Close();
  382. it = m_shared_memory_list.erase(it);
  383. KSharedMemoryInfo::Free(m_kernel, info);
  384. }
  385. }
  386. // Release memory to the resource limit.
  387. if (m_resource_limit != nullptr) {
  388. m_resource_limit->Close();
  389. m_resource_limit = nullptr;
  390. }
  391. // Finalize the page table.
  392. m_page_table.Finalize();
  393. // Perform inherited finalization.
  394. KSynchronizationObject::Finalize();
  395. }
  396. Result KProcess::CreateThreadLocalRegion(VAddr* out) {
  397. KThreadLocalPage* tlp = nullptr;
  398. VAddr tlr = 0;
  399. // See if we can get a region from a partially used TLP.
  400. {
  401. KScopedSchedulerLock sl{m_kernel};
  402. if (auto it = m_partially_used_tlp_tree.begin(); it != m_partially_used_tlp_tree.end()) {
  403. tlr = it->Reserve();
  404. ASSERT(tlr != 0);
  405. if (it->IsAllUsed()) {
  406. tlp = std::addressof(*it);
  407. m_partially_used_tlp_tree.erase(it);
  408. m_fully_used_tlp_tree.insert(*tlp);
  409. }
  410. *out = tlr;
  411. R_SUCCEED();
  412. }
  413. }
  414. // Allocate a new page.
  415. tlp = KThreadLocalPage::Allocate(m_kernel);
  416. R_UNLESS(tlp != nullptr, ResultOutOfMemory);
  417. auto tlp_guard = SCOPE_GUARD({ KThreadLocalPage::Free(m_kernel, tlp); });
  418. // Initialize the new page.
  419. R_TRY(tlp->Initialize(m_kernel, this));
  420. // Reserve a TLR.
  421. tlr = tlp->Reserve();
  422. ASSERT(tlr != 0);
  423. // Insert into our tree.
  424. {
  425. KScopedSchedulerLock sl{m_kernel};
  426. if (tlp->IsAllUsed()) {
  427. m_fully_used_tlp_tree.insert(*tlp);
  428. } else {
  429. m_partially_used_tlp_tree.insert(*tlp);
  430. }
  431. }
  432. // We succeeded!
  433. tlp_guard.Cancel();
  434. *out = tlr;
  435. R_SUCCEED();
  436. }
  437. Result KProcess::DeleteThreadLocalRegion(VAddr addr) {
  438. KThreadLocalPage* page_to_free = nullptr;
  439. // Release the region.
  440. {
  441. KScopedSchedulerLock sl{m_kernel};
  442. // Try to find the page in the partially used list.
  443. auto it = m_partially_used_tlp_tree.find_key(Common::AlignDown(addr, PageSize));
  444. if (it == m_partially_used_tlp_tree.end()) {
  445. // If we don't find it, it has to be in the fully used list.
  446. it = m_fully_used_tlp_tree.find_key(Common::AlignDown(addr, PageSize));
  447. R_UNLESS(it != m_fully_used_tlp_tree.end(), ResultInvalidAddress);
  448. // Release the region.
  449. it->Release(addr);
  450. // Move the page out of the fully used list.
  451. KThreadLocalPage* tlp = std::addressof(*it);
  452. m_fully_used_tlp_tree.erase(it);
  453. if (tlp->IsAllFree()) {
  454. page_to_free = tlp;
  455. } else {
  456. m_partially_used_tlp_tree.insert(*tlp);
  457. }
  458. } else {
  459. // Release the region.
  460. it->Release(addr);
  461. // Handle the all-free case.
  462. KThreadLocalPage* tlp = std::addressof(*it);
  463. if (tlp->IsAllFree()) {
  464. m_partially_used_tlp_tree.erase(it);
  465. page_to_free = tlp;
  466. }
  467. }
  468. }
  469. // If we should free the page it was in, do so.
  470. if (page_to_free != nullptr) {
  471. page_to_free->Finalize();
  472. KThreadLocalPage::Free(m_kernel, page_to_free);
  473. }
  474. R_SUCCEED();
  475. }
  476. bool KProcess::InsertWatchpoint(Core::System& system, VAddr addr, u64 size,
  477. DebugWatchpointType type) {
  478. const auto watch{std::find_if(m_watchpoints.begin(), m_watchpoints.end(), [&](const auto& wp) {
  479. return wp.type == DebugWatchpointType::None;
  480. })};
  481. if (watch == m_watchpoints.end()) {
  482. return false;
  483. }
  484. watch->start_address = addr;
  485. watch->end_address = addr + size;
  486. watch->type = type;
  487. for (VAddr page = Common::AlignDown(addr, PageSize); page < addr + size; page += PageSize) {
  488. m_debug_page_refcounts[page]++;
  489. system.Memory().MarkRegionDebug(page, PageSize, true);
  490. }
  491. return true;
  492. }
  493. bool KProcess::RemoveWatchpoint(Core::System& system, VAddr addr, u64 size,
  494. DebugWatchpointType type) {
  495. const auto watch{std::find_if(m_watchpoints.begin(), m_watchpoints.end(), [&](const auto& wp) {
  496. return wp.start_address == addr && wp.end_address == addr + size && wp.type == type;
  497. })};
  498. if (watch == m_watchpoints.end()) {
  499. return false;
  500. }
  501. watch->start_address = 0;
  502. watch->end_address = 0;
  503. watch->type = DebugWatchpointType::None;
  504. for (VAddr page = Common::AlignDown(addr, PageSize); page < addr + size; page += PageSize) {
  505. m_debug_page_refcounts[page]--;
  506. if (!m_debug_page_refcounts[page]) {
  507. system.Memory().MarkRegionDebug(page, PageSize, false);
  508. }
  509. }
  510. return true;
  511. }
  512. void KProcess::LoadModule(CodeSet code_set, VAddr base_addr) {
  513. const auto ReprotectSegment = [&](const CodeSet::Segment& segment,
  514. Svc::MemoryPermission permission) {
  515. m_page_table.SetProcessMemoryPermission(segment.addr + base_addr, segment.size, permission);
  516. };
  517. m_kernel.System().Memory().WriteBlock(*this, base_addr, code_set.memory.data(),
  518. code_set.memory.size());
  519. ReprotectSegment(code_set.CodeSegment(), Svc::MemoryPermission::ReadExecute);
  520. ReprotectSegment(code_set.RODataSegment(), Svc::MemoryPermission::Read);
  521. ReprotectSegment(code_set.DataSegment(), Svc::MemoryPermission::ReadWrite);
  522. }
  523. bool KProcess::IsSignaled() const {
  524. ASSERT(KScheduler::IsSchedulerLockedByCurrentThread(m_kernel));
  525. return m_is_signaled;
  526. }
  527. KProcess::KProcess(KernelCore& kernel)
  528. : KAutoObjectWithSlabHeapAndContainer{kernel}, m_page_table{m_kernel.System()},
  529. m_handle_table{m_kernel}, m_address_arbiter{m_kernel.System()},
  530. m_condition_var{m_kernel.System()}, m_state_lock{m_kernel}, m_list_lock{m_kernel} {}
  531. KProcess::~KProcess() = default;
  532. void KProcess::ChangeState(State new_state) {
  533. if (m_state == new_state) {
  534. return;
  535. }
  536. m_state = new_state;
  537. m_is_signaled = true;
  538. this->NotifyAvailable();
  539. }
  540. Result KProcess::AllocateMainThreadStack(std::size_t stack_size) {
  541. // Ensure that we haven't already allocated stack.
  542. ASSERT(m_main_thread_stack_size == 0);
  543. // Ensure that we're allocating a valid stack.
  544. stack_size = Common::AlignUp(stack_size, PageSize);
  545. // R_UNLESS(stack_size + image_size <= m_max_process_memory, ResultOutOfMemory);
  546. R_UNLESS(stack_size + m_image_size >= m_image_size, ResultOutOfMemory);
  547. // Place a tentative reservation of memory for our new stack.
  548. KScopedResourceReservation mem_reservation(this, Svc::LimitableResource::PhysicalMemoryMax,
  549. stack_size);
  550. R_UNLESS(mem_reservation.Succeeded(), ResultLimitReached);
  551. // Allocate and map our stack.
  552. if (stack_size) {
  553. KProcessAddress stack_bottom;
  554. R_TRY(m_page_table.MapPages(std::addressof(stack_bottom), stack_size / PageSize,
  555. KMemoryState::Stack, KMemoryPermission::UserReadWrite));
  556. m_main_thread_stack_top = stack_bottom + stack_size;
  557. m_main_thread_stack_size = stack_size;
  558. }
  559. // We succeeded! Commit our memory reservation.
  560. mem_reservation.Commit();
  561. R_SUCCEED();
  562. }
  563. } // namespace Kernel