Fix unregister issue

This commit is contained in:
2026-04-19 14:47:29 +10:00
parent 2de11c4b0c
commit 51fe507dfd
8 changed files with 191 additions and 122 deletions

View File

@@ -20,8 +20,12 @@
// Handle registry with refcount — prevents use-after-free when
// ReleaseANSTREHandle is called while an operation is still running.
static std::unordered_map<ANSCENTER::ANSTRE*, int>& TREHandleRegistry() {
static std::unordered_map<ANSCENTER::ANSTRE*, int> s;
// destructionStarted: set by the first Unregister caller; blocks new Acquires
// and makes subsequent Unregister calls return false without deleting.
// Prevents double-free when Release is raced on the same handle.
struct TREEntry { int refcount; bool destructionStarted; };
static std::unordered_map<ANSCENTER::ANSTRE*, TREEntry>& TREHandleRegistry() {
static std::unordered_map<ANSCENTER::ANSTRE*, TREEntry> s;
return s;
}
static std::mutex& TREHandleRegistryMutex() {
@@ -35,14 +39,15 @@ static std::condition_variable& TREHandleRegistryCV() {
static void RegisterTREHandle(ANSCENTER::ANSTRE* h) {
std::lock_guard<std::mutex> lk(TREHandleRegistryMutex());
TREHandleRegistry()[h] = 1;
TREHandleRegistry()[h] = { 1, false };
}
static ANSCENTER::ANSTRE* AcquireTREHandle(ANSCENTER::ANSTRE* h) {
std::lock_guard<std::mutex> lk(TREHandleRegistryMutex());
auto it = TREHandleRegistry().find(h);
if (it == TREHandleRegistry().end()) return nullptr;
it->second++;
if (it->second.destructionStarted) return nullptr;
it->second.refcount++;
return h;
}
@@ -50,23 +55,25 @@ static bool ReleaseTREHandleRef(ANSCENTER::ANSTRE* h) {
std::lock_guard<std::mutex> lk(TREHandleRegistryMutex());
auto it = TREHandleRegistry().find(h);
if (it == TREHandleRegistry().end()) return false;
it->second--;
if (it->second <= 0) {
TREHandleRegistry().erase(it);
it->second.refcount--;
if (it->second.refcount <= 0) {
TREHandleRegistryCV().notify_all();
return true;
}
return false;
return false; // Only Unregister deletes.
}
static bool UnregisterTREHandle(ANSCENTER::ANSTRE* h) {
std::unique_lock<std::mutex> lk(TREHandleRegistryMutex());
auto it = TREHandleRegistry().find(h);
if (it == TREHandleRegistry().end()) return false;
it->second--;
if (it->second.destructionStarted) {
return false; // Another thread already owns the delete.
}
it->second.destructionStarted = true;
it->second.refcount--;
bool ok = TREHandleRegistryCV().wait_for(lk, std::chrono::seconds(30), [&]() {
auto it2 = TREHandleRegistry().find(h);
return it2 == TREHandleRegistry().end() || it2->second <= 0;
return it2 == TREHandleRegistry().end() || it2->second.refcount <= 0;
});
if (!ok) {
OutputDebugStringA("WARNING: UnregisterTREHandle timed out waiting for in-flight operations\n");