1 /* 2 * Copyright (C) 2021-2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef OHOS_IPC_IPC_THREAD_SKELETON_H 17 #define OHOS_IPC_IPC_THREAD_SKELETON_H 18 19 #include <mutex> 20 #include <pthread.h> 21 #include <unordered_map> 22 #include "iremote_invoker.h" 23 #include "binder_invoker.h" 24 25 namespace OHOS { 26 #ifdef CONFIG_IPC_SINGLE 27 namespace IPC_SINGLE { 28 #endif 29 30 enum class ThreadType { 31 NORMAL_THREAD = 0xB0B0B0B0, 32 IPC_THREAD = 0xB1B1B1B1, 33 }; 34 35 class IPCThreadSkeleton { 36 public: 37 IPCThreadSkeleton(); 38 39 ~IPCThreadSkeleton(); 40 41 static void TlsDestructor(void *args); 42 static void MakeTlsKey(); 43 44 static IPCThreadSkeleton *GetCurrent(); 45 46 static IRemoteInvoker *GetRemoteInvoker(int proto); 47 48 static IRemoteInvoker *GetDefaultInvoker(); 49 50 static IRemoteInvoker *GetActiveInvoker(); 51 52 static IRemoteInvoker *GetProxyInvoker(IRemoteObject *object); 53 54 static pthread_key_t GetTlsKey(); 55 56 static void GetVaildInstance(IPCThreadSkeleton *&instance); 57 58 static void SaveThreadName(const std::string &name); 59 60 static bool UpdateSendRequestCount(int delta); 61 62 static bool CheckInstanceIsExiting(std::atomic<uint32_t> &flag); 63 64 static bool SetThreadType(ThreadType type); 65 66 bool IsSendRequesting(); 67 68 // Joint Current thread into IPC Work Group 69 void JoinWorkThread(int proto); 70 // Quit current thread from IPC work group. 71 void StopWorkThread(int proto); 72 73 static constexpr uint32_t INVOKER_USE_MAGIC = 0x5A5A5A5A; 74 static constexpr uint32_t INVOKER_IDLE_MAGIC = 0xA5A5A5A5; 75 76 private: 77 static pthread_key_t TLSKey_; 78 static pthread_once_t TLSKeyOnce_; 79 std::atomic<uint32_t> exitFlag_ = INVOKER_USE_MAGIC; 80 std::atomic<uint32_t> usingFlag_ = INVOKER_IDLE_MAGIC; 81 static constexpr uint32_t INVOKER_MAX_COUNT = 2; 82 IRemoteInvoker *invokers_[INVOKER_MAX_COUNT] = {nullptr, nullptr}; 83 const pid_t tid_; 84 std::atomic<int32_t> sendRequestCount_ = 0; 85 std::string threadName_; 86 ThreadType threadType_ = ThreadType::NORMAL_THREAD; 87 }; 88 #ifdef CONFIG_IPC_SINGLE 89 } // namespace IPC_SINGLE 90 #endif 91 } // namespace OHOS 92 #endif // OHOS_IPC_IPC_THREAD_SKELETON_H 93