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(), &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. u64 KProcess::GetFreeThreadCount() const {
  232. if (resource_limit != nullptr) {
  233. const auto current_value =
  234. resource_limit->GetCurrentValue(LimitableResource::ThreadCountMax);
  235. const auto limit_value = 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(state_lock);
  244. KScopedSchedulerLock sl{kernel};
  245. // Validate that we're in a state that we can reset.
  246. R_UNLESS(state != State::Terminated, ResultInvalidState);
  247. R_UNLESS(is_signaled, ResultInvalidState);
  248. // Clear signaled.
  249. is_signaled = false;
  250. R_SUCCEED();
  251. }
  252. Result KProcess::SetActivity(ProcessActivity activity) {
  253. // Lock ourselves and the scheduler.
  254. KScopedLightLock lk{state_lock};
  255. KScopedLightLock list_lk{list_lock};
  256. KScopedSchedulerLock sl{kernel};
  257. // Validate our state.
  258. R_UNLESS(state != State::Terminating, ResultInvalidState);
  259. R_UNLESS(state != State::Terminated, ResultInvalidState);
  260. // Either pause or resume.
  261. if (activity == ProcessActivity::Paused) {
  262. // Verify that we're not suspended.
  263. R_UNLESS(!is_suspended, ResultInvalidState);
  264. // Suspend all threads.
  265. for (auto* thread : GetThreadList()) {
  266. thread->RequestSuspend(SuspendType::Process);
  267. }
  268. // Set ourselves as suspended.
  269. SetSuspended(true);
  270. } else {
  271. ASSERT(activity == ProcessActivity::Runnable);
  272. // Verify that we're suspended.
  273. R_UNLESS(is_suspended, ResultInvalidState);
  274. // Resume all threads.
  275. for (auto* thread : GetThreadList()) {
  276. thread->Resume(SuspendType::Process);
  277. }
  278. // Set ourselves as resumed.
  279. SetSuspended(false);
  280. }
  281. R_SUCCEED();
  282. }
  283. Result KProcess::LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std::size_t code_size) {
  284. program_id = metadata.GetTitleID();
  285. ideal_core = metadata.GetMainThreadCore();
  286. is_64bit_process = metadata.Is64BitProgram();
  287. system_resource_size = metadata.GetSystemResourceSize();
  288. image_size = code_size;
  289. // We currently do not support process-specific system resource
  290. UNIMPLEMENTED_IF(system_resource_size != 0);
  291. KScopedResourceReservation memory_reservation(
  292. resource_limit, LimitableResource::PhysicalMemoryMax, code_size + system_resource_size);
  293. if (!memory_reservation.Succeeded()) {
  294. LOG_ERROR(Kernel, "Could not reserve process memory requirements of size {:X} bytes",
  295. code_size + system_resource_size);
  296. R_RETURN(ResultLimitReached);
  297. }
  298. // Initialize proces address space
  299. if (const Result result{page_table.InitializeForProcess(
  300. metadata.GetAddressSpaceType(), false, false, false, KMemoryManager::Pool::Application,
  301. 0x8000000, code_size, &kernel.GetAppSystemResource(), resource_limit)};
  302. result.IsError()) {
  303. R_RETURN(result);
  304. }
  305. // Map process code region
  306. if (const Result result{page_table.MapProcessCode(page_table.GetCodeRegionStart(),
  307. code_size / PageSize, KMemoryState::Code,
  308. KMemoryPermission::None)};
  309. result.IsError()) {
  310. R_RETURN(result);
  311. }
  312. // Initialize process capabilities
  313. const auto& caps{metadata.GetKernelCapabilities()};
  314. if (const Result result{
  315. capabilities.InitializeForUserProcess(caps.data(), caps.size(), page_table)};
  316. result.IsError()) {
  317. R_RETURN(result);
  318. }
  319. // Set memory usage capacity
  320. switch (metadata.GetAddressSpaceType()) {
  321. case FileSys::ProgramAddressSpaceType::Is32Bit:
  322. case FileSys::ProgramAddressSpaceType::Is36Bit:
  323. case FileSys::ProgramAddressSpaceType::Is39Bit:
  324. memory_usage_capacity = page_table.GetHeapRegionEnd() - page_table.GetHeapRegionStart();
  325. break;
  326. case FileSys::ProgramAddressSpaceType::Is32BitNoMap:
  327. memory_usage_capacity = page_table.GetHeapRegionEnd() - page_table.GetHeapRegionStart() +
  328. page_table.GetAliasRegionEnd() - page_table.GetAliasRegionStart();
  329. break;
  330. default:
  331. ASSERT(false);
  332. break;
  333. }
  334. // Create TLS region
  335. R_TRY(this->CreateThreadLocalRegion(std::addressof(plr_address)));
  336. memory_reservation.Commit();
  337. R_RETURN(handle_table.Initialize(capabilities.GetHandleTableSize()));
  338. }
  339. void KProcess::Run(s32 main_thread_priority, u64 stack_size) {
  340. ASSERT(AllocateMainThreadStack(stack_size) == ResultSuccess);
  341. resource_limit->Reserve(LimitableResource::ThreadCountMax, 1);
  342. const std::size_t heap_capacity{memory_usage_capacity - (main_thread_stack_size + image_size)};
  343. ASSERT(!page_table.SetMaxHeapSize(heap_capacity).IsError());
  344. ChangeState(State::Running);
  345. SetupMainThread(kernel.System(), *this, main_thread_priority, main_thread_stack_top);
  346. }
  347. void KProcess::PrepareForTermination() {
  348. ChangeState(State::Terminating);
  349. const auto stop_threads = [this](const std::vector<KThread*>& in_thread_list) {
  350. for (auto* thread : in_thread_list) {
  351. if (thread->GetOwnerProcess() != this)
  352. continue;
  353. if (thread == GetCurrentThreadPointer(kernel))
  354. continue;
  355. // TODO(Subv): When are the other running/ready threads terminated?
  356. ASSERT_MSG(thread->GetState() == ThreadState::Waiting,
  357. "Exiting processes with non-waiting threads is currently unimplemented");
  358. thread->Exit();
  359. }
  360. };
  361. stop_threads(kernel.System().GlobalSchedulerContext().GetThreadList());
  362. this->DeleteThreadLocalRegion(plr_address);
  363. plr_address = 0;
  364. if (resource_limit) {
  365. resource_limit->Release(LimitableResource::PhysicalMemoryMax,
  366. main_thread_stack_size + image_size);
  367. }
  368. ChangeState(State::Terminated);
  369. }
  370. void KProcess::Finalize() {
  371. // Free all shared memory infos.
  372. {
  373. auto it = shared_memory_list.begin();
  374. while (it != shared_memory_list.end()) {
  375. KSharedMemoryInfo* info = *it;
  376. KSharedMemory* shmem = info->GetSharedMemory();
  377. while (!info->Close()) {
  378. shmem->Close();
  379. }
  380. shmem->Close();
  381. it = shared_memory_list.erase(it);
  382. KSharedMemoryInfo::Free(kernel, info);
  383. }
  384. }
  385. // Release memory to the resource limit.
  386. if (resource_limit != nullptr) {
  387. resource_limit->Close();
  388. resource_limit = nullptr;
  389. }
  390. // Finalize the page table.
  391. page_table.Finalize();
  392. // Perform inherited finalization.
  393. KAutoObjectWithSlabHeapAndContainer<KProcess, KWorkerTask>::Finalize();
  394. }
  395. Result KProcess::CreateThreadLocalRegion(VAddr* out) {
  396. KThreadLocalPage* tlp = nullptr;
  397. VAddr tlr = 0;
  398. // See if we can get a region from a partially used TLP.
  399. {
  400. KScopedSchedulerLock sl{kernel};
  401. if (auto it = partially_used_tlp_tree.begin(); it != partially_used_tlp_tree.end()) {
  402. tlr = it->Reserve();
  403. ASSERT(tlr != 0);
  404. if (it->IsAllUsed()) {
  405. tlp = std::addressof(*it);
  406. partially_used_tlp_tree.erase(it);
  407. fully_used_tlp_tree.insert(*tlp);
  408. }
  409. *out = tlr;
  410. R_SUCCEED();
  411. }
  412. }
  413. // Allocate a new page.
  414. tlp = KThreadLocalPage::Allocate(kernel);
  415. R_UNLESS(tlp != nullptr, ResultOutOfMemory);
  416. auto tlp_guard = SCOPE_GUARD({ KThreadLocalPage::Free(kernel, tlp); });
  417. // Initialize the new page.
  418. R_TRY(tlp->Initialize(kernel, this));
  419. // Reserve a TLR.
  420. tlr = tlp->Reserve();
  421. ASSERT(tlr != 0);
  422. // Insert into our tree.
  423. {
  424. KScopedSchedulerLock sl{kernel};
  425. if (tlp->IsAllUsed()) {
  426. fully_used_tlp_tree.insert(*tlp);
  427. } else {
  428. partially_used_tlp_tree.insert(*tlp);
  429. }
  430. }
  431. // We succeeded!
  432. tlp_guard.Cancel();
  433. *out = tlr;
  434. R_SUCCEED();
  435. }
  436. Result KProcess::DeleteThreadLocalRegion(VAddr addr) {
  437. KThreadLocalPage* page_to_free = nullptr;
  438. // Release the region.
  439. {
  440. KScopedSchedulerLock sl{kernel};
  441. // Try to find the page in the partially used list.
  442. auto it = partially_used_tlp_tree.find_key(Common::AlignDown(addr, PageSize));
  443. if (it == partially_used_tlp_tree.end()) {
  444. // If we don't find it, it has to be in the fully used list.
  445. it = fully_used_tlp_tree.find_key(Common::AlignDown(addr, PageSize));
  446. R_UNLESS(it != fully_used_tlp_tree.end(), ResultInvalidAddress);
  447. // Release the region.
  448. it->Release(addr);
  449. // Move the page out of the fully used list.
  450. KThreadLocalPage* tlp = std::addressof(*it);
  451. fully_used_tlp_tree.erase(it);
  452. if (tlp->IsAllFree()) {
  453. page_to_free = tlp;
  454. } else {
  455. partially_used_tlp_tree.insert(*tlp);
  456. }
  457. } else {
  458. // Release the region.
  459. it->Release(addr);
  460. // Handle the all-free case.
  461. KThreadLocalPage* tlp = std::addressof(*it);
  462. if (tlp->IsAllFree()) {
  463. partially_used_tlp_tree.erase(it);
  464. page_to_free = tlp;
  465. }
  466. }
  467. }
  468. // If we should free the page it was in, do so.
  469. if (page_to_free != nullptr) {
  470. page_to_free->Finalize();
  471. KThreadLocalPage::Free(kernel, page_to_free);
  472. }
  473. R_SUCCEED();
  474. }
  475. bool KProcess::InsertWatchpoint(Core::System& system, VAddr addr, u64 size,
  476. DebugWatchpointType type) {
  477. const auto watch{std::find_if(watchpoints.begin(), watchpoints.end(), [&](const auto& wp) {
  478. return wp.type == DebugWatchpointType::None;
  479. })};
  480. if (watch == watchpoints.end()) {
  481. return false;
  482. }
  483. watch->start_address = addr;
  484. watch->end_address = addr + size;
  485. watch->type = type;
  486. for (VAddr page = Common::AlignDown(addr, PageSize); page < addr + size; page += PageSize) {
  487. debug_page_refcounts[page]++;
  488. system.Memory().MarkRegionDebug(page, PageSize, true);
  489. }
  490. return true;
  491. }
  492. bool KProcess::RemoveWatchpoint(Core::System& system, VAddr addr, u64 size,
  493. DebugWatchpointType type) {
  494. const auto watch{std::find_if(watchpoints.begin(), watchpoints.end(), [&](const auto& wp) {
  495. return wp.start_address == addr && wp.end_address == addr + size && wp.type == type;
  496. })};
  497. if (watch == watchpoints.end()) {
  498. return false;
  499. }
  500. watch->start_address = 0;
  501. watch->end_address = 0;
  502. watch->type = DebugWatchpointType::None;
  503. for (VAddr page = Common::AlignDown(addr, PageSize); page < addr + size; page += PageSize) {
  504. debug_page_refcounts[page]--;
  505. if (!debug_page_refcounts[page]) {
  506. system.Memory().MarkRegionDebug(page, PageSize, false);
  507. }
  508. }
  509. return true;
  510. }
  511. void KProcess::LoadModule(CodeSet code_set, VAddr base_addr) {
  512. const auto ReprotectSegment = [&](const CodeSet::Segment& segment,
  513. Svc::MemoryPermission permission) {
  514. page_table.SetProcessMemoryPermission(segment.addr + base_addr, segment.size, permission);
  515. };
  516. kernel.System().Memory().WriteBlock(*this, base_addr, code_set.memory.data(),
  517. code_set.memory.size());
  518. ReprotectSegment(code_set.CodeSegment(), Svc::MemoryPermission::ReadExecute);
  519. ReprotectSegment(code_set.RODataSegment(), Svc::MemoryPermission::Read);
  520. ReprotectSegment(code_set.DataSegment(), Svc::MemoryPermission::ReadWrite);
  521. }
  522. bool KProcess::IsSignaled() const {
  523. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  524. return is_signaled;
  525. }
  526. KProcess::KProcess(KernelCore& kernel_)
  527. : KAutoObjectWithSlabHeapAndContainer{kernel_}, page_table{kernel_.System()},
  528. handle_table{kernel_}, address_arbiter{kernel_.System()}, condition_var{kernel_.System()},
  529. state_lock{kernel_}, list_lock{kernel_} {}
  530. KProcess::~KProcess() = default;
  531. void KProcess::ChangeState(State new_state) {
  532. if (state == new_state) {
  533. return;
  534. }
  535. state = new_state;
  536. is_signaled = true;
  537. NotifyAvailable();
  538. }
  539. Result KProcess::AllocateMainThreadStack(std::size_t stack_size) {
  540. // Ensure that we haven't already allocated stack.
  541. ASSERT(main_thread_stack_size == 0);
  542. // Ensure that we're allocating a valid stack.
  543. stack_size = Common::AlignUp(stack_size, PageSize);
  544. // R_UNLESS(stack_size + image_size <= m_max_process_memory, ResultOutOfMemory);
  545. R_UNLESS(stack_size + image_size >= image_size, ResultOutOfMemory);
  546. // Place a tentative reservation of memory for our new stack.
  547. KScopedResourceReservation mem_reservation(this, Svc::LimitableResource::PhysicalMemoryMax,
  548. stack_size);
  549. R_UNLESS(mem_reservation.Succeeded(), ResultLimitReached);
  550. // Allocate and map our stack.
  551. if (stack_size) {
  552. KProcessAddress stack_bottom;
  553. R_TRY(page_table.MapPages(std::addressof(stack_bottom), stack_size / PageSize,
  554. KMemoryState::Stack, KMemoryPermission::UserReadWrite));
  555. main_thread_stack_top = stack_bottom + stack_size;
  556. main_thread_stack_size = stack_size;
  557. }
  558. // We succeeded! Commit our memory reservation.
  559. mem_reservation.Commit();
  560. R_SUCCEED();
  561. }
  562. } // namespace Kernel