k_process.cpp 23 KB

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