diff --git a/src/windows-emulator/emulator_thread.hpp b/src/windows-emulator/emulator_thread.hpp index e9907d08..c0b5b891 100644 --- a/src/windows-emulator/emulator_thread.hpp +++ b/src/windows-emulator/emulator_thread.hpp @@ -210,6 +210,11 @@ class emulator_thread : public ref_counted_object this->marker.mark_as_moved(); } + static bool deleter(emulator_thread& t) + { + return ref_counted_object::deleter(t) && t.is_terminated(); + } + private: void setup_registers(x86_64_emulator& emu, const process_context& context) const; diff --git a/src/windows-emulator/handles.hpp b/src/windows-emulator/handles.hpp index a5430973..d105fbc4 100644 --- a/src/windows-emulator/handles.hpp +++ b/src/windows-emulator/handles.hpp @@ -136,6 +136,11 @@ class ref_counted_object static bool deleter(ref_counted_object& e) { + if (e.ref_count == 0) + { + return true; + } + return --e.ref_count == 0; } diff --git a/src/windows-emulator/syscalls/object.cpp b/src/windows-emulator/syscalls/object.cpp index 024a04b9..ae7c134c 100644 --- a/src/windows-emulator/syscalls/object.cpp +++ b/src/windows-emulator/syscalls/object.cpp @@ -15,7 +15,7 @@ namespace syscalls if (h.value.type == handle_types::thread) { const auto* t = c.proc.threads.get(h); - if (t == c.proc.active_thread && t->ref_count == 1) + if (t && t->ref_count == 1) { // TODO: Better handle ref counting return STATUS_SUCCESS; diff --git a/src/windows-emulator/windows_emulator.cpp b/src/windows-emulator/windows_emulator.cpp index 8911a48b..76cf20ba 100644 --- a/src/windows-emulator/windows_emulator.cpp +++ b/src/windows-emulator/windows_emulator.cpp @@ -50,6 +50,27 @@ namespace void perform_context_switch_work(windows_emulator& win_emu) { + auto& threads = win_emu.process.threads; + + for (auto it = threads.begin(); it != threads.end();) + { + if (!it->second.is_terminated() || it->second.ref_count > 0) + { + ++it; + continue; + } + + const auto [new_it, deleted] = threads.erase(it); + if (!deleted) + { + ++it; + } + else + { + it = new_it; + } + } + auto& devices = win_emu.process.devices; // Crappy mechanism to prevent mutation while iterating.