1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include <sys/types.h> // pid_t 18 #include <mutex> 19 20 #include "berberis/base/checks.h" 21 #include "berberis/base/forever_alloc.h" 22 #include "berberis/guest_os_primitives/guest_thread.h" 23 24 #include "guest_thread_map.h" 25 26 namespace berberis { 27 GetInstance()28GuestThreadMap* GuestThreadMap::GetInstance() { 29 static auto* g_guest_thread_map = NewForever<GuestThreadMap>(); 30 return g_guest_thread_map; 31 } 32 ResetThreadTable(pid_t tid,GuestThread * thread)33void GuestThreadMap::ResetThreadTable(pid_t tid, GuestThread* thread) { 34 std::lock_guard<std::mutex> lock(mutex_); 35 map_.clear(); 36 map_[tid] = thread; 37 } 38 InsertThread(pid_t tid,GuestThread * thread)39void GuestThreadMap::InsertThread(pid_t tid, GuestThread* thread) { 40 std::lock_guard<std::mutex> lock(mutex_); 41 auto result = map_.insert({tid, thread}); 42 CHECK(result.second); 43 } 44 RemoveThread(pid_t tid)45GuestThread* GuestThreadMap::RemoveThread(pid_t tid) { 46 std::lock_guard<std::mutex> lock(mutex_); 47 auto it = map_.find(tid); 48 CHECK(it != map_.end()); 49 GuestThread* thread = it->second; 50 map_.erase(it); 51 return thread; 52 } 53 FindThread(pid_t tid)54GuestThread* GuestThreadMap::FindThread(pid_t tid) { 55 std::lock_guard<std::mutex> lock(mutex_); 56 auto it = map_.find(tid); 57 if (it == map_.end()) { 58 return nullptr; 59 } 60 return it->second; 61 } 62 63 } // namespace berberis 64