From 62409f8139c03ac400c369be7507fced8ac15e7c Mon Sep 17 00:00:00 2001
From: GPUCode <47210458+GPUCode@users.noreply.github.com>
Date: Sat, 6 Jan 2024 02:12:00 +0200
Subject: [PATCH] kernel: Release thread resource limit in Thread::Stop (#7318)

* core: Config plg_ldr after its creation

* Also use service manager to retrieve the service

* thread: Release resource limit in Thread::Stop

* service: Undo plgldr change
---
 src/core/core.cpp                      | 6 ++++++
 src/core/hle/kernel/thread.cpp         | 8 ++------
 src/core/hle/service/plgldr/plgldr.cpp | 2 --
 3 files changed, 8 insertions(+), 8 deletions(-)

diff --git a/src/core/core.cpp b/src/core/core.cpp
index ad6f0ae56..e8c0c4178 100644
--- a/src/core/core.cpp
+++ b/src/core/core.cpp
@@ -449,6 +449,12 @@ System::ResultStatus System::Init(Frontend::EmuWindow& emu_window,
     gpu->SetInterruptHandler(
         [gsp](Service::GSP::InterruptId interrupt_id) { gsp->SignalInterrupt(interrupt_id); });
 
+    auto plg_ldr = Service::PLGLDR::GetService(*this);
+    if (plg_ldr) {
+        plg_ldr->SetEnabled(Settings::values.plugin_loader_enabled.GetValue());
+        plg_ldr->SetAllowGameChangeState(Settings::values.allow_plugin_loader.GetValue());
+    }
+
     LOG_DEBUG(Core, "Initialized OK");
 
     is_powered_on = true;
diff --git a/src/core/hle/kernel/thread.cpp b/src/core/hle/kernel/thread.cpp
index be18b2c39..7f6046a8f 100644
--- a/src/core/hle/kernel/thread.cpp
+++ b/src/core/hle/kernel/thread.cpp
@@ -60,12 +60,7 @@ void Thread::Acquire(Thread* thread) {
 Thread::Thread(KernelSystem& kernel, u32 core_id)
     : WaitObject(kernel), core_id(core_id), thread_manager(kernel.GetThreadManager(core_id)) {}
 
-Thread::~Thread() {
-    auto process = owner_process.lock();
-    if (process) {
-        process->resource_limit->Release(ResourceLimitType::Thread, 1);
-    }
-}
+Thread::~Thread() = default;
 
 Thread* ThreadManager::GetCurrentThread() const {
     return current_thread.get();
@@ -101,6 +96,7 @@ void Thread::Stop() {
         ((tls_address - Memory::TLS_AREA_VADDR) % Memory::CITRA_PAGE_SIZE) / Memory::TLS_ENTRY_SIZE;
     if (auto process = owner_process.lock()) {
         process->tls_slots[tls_page].reset(tls_slot);
+        process->resource_limit->Release(ResourceLimitType::Thread, 1);
     }
 }
 
diff --git a/src/core/hle/service/plgldr/plgldr.cpp b/src/core/hle/service/plgldr/plgldr.cpp
index 7fb929cc0..e46022815 100644
--- a/src/core/hle/service/plgldr/plgldr.cpp
+++ b/src/core/hle/service/plgldr/plgldr.cpp
@@ -26,12 +26,10 @@
 #include "common/settings.h"
 #include "core/core.h"
 #include "core/file_sys/plugin_3gx.h"
-#include "core/hle/ipc.h"
 #include "core/hle/ipc_helpers.h"
 #include "core/hle/kernel/event.h"
 #include "core/hle/kernel/handle_table.h"
 #include "core/hle/kernel/kernel.h"
-#include "core/hle/kernel/shared_memory.h"
 #include "core/hle/service/plgldr/plgldr.h"
 #include "core/loader/loader.h"