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 23 #include "ipc_types.h" 24 #include "binder_invoker.h" 25 #include "iremote_invoker.h" 26 27 namespace OHOS { 28 #ifdef CONFIG_IPC_SINGLE 29 namespace IPC_SINGLE { 30 #endif 31 32 enum class ThreadType { 33 NORMAL_THREAD = 0xB0B0B0B0, 34 IPC_THREAD = 0xB1B1B1B1, 35 }; 36 37 class IPCThreadSkeleton { 38 public: 39 IPCThreadSkeleton(); 40 41 ~IPCThreadSkeleton(); 42 43 static void TlsDestructor(void *args); 44 static void MakeTlsKey(); 45 46 static IPCThreadSkeleton *GetCurrent(); 47 48 static IRemoteInvoker *GetRemoteInvoker(int proto); 49 50 static IRemoteInvoker *GetDefaultInvoker(); 51 52 static IRemoteInvoker *GetActiveInvoker(); 53 54 static IRemoteInvoker *GetProxyInvoker(IRemoteObject *object); 55 56 static pthread_key_t GetTlsKey(); 57 58 static void GetVaildInstance(IPCThreadSkeleton *&instance); 59 60 static void SaveThreadName(const std::string &name); 61 62 static bool UpdateSendRequestCount(int delta); 63 64 static bool IsInstanceException(std::atomic<uint32_t> &flag); 65 66 static bool SetThreadType(ThreadType type); 67 68 static ThreadType GetThreadType(); 69 70 static int32_t GetThreadInvocationState(); 71 72 bool IsSendRequesting(); 73 74 // Joint Current thread into IPC Work Group 75 void JoinWorkThread(int proto); 76 // Quit current thread from IPC work group. 77 void StopWorkThread(int proto); 78 79 static constexpr uint32_t INVOKER_USE_MAGIC = 0x5A5A5A5A; 80 static constexpr uint32_t INVOKER_IDLE_MAGIC = 0xA5A5A5A5; 81 82 private: 83 static pthread_key_t TLSKey_; 84 static pthread_once_t TLSKeyOnce_; 85 std::atomic<uint32_t> exitFlag_ = INVOKER_USE_MAGIC; 86 std::atomic<uint32_t> usingFlag_ = INVOKER_IDLE_MAGIC; 87 static constexpr uint32_t INVOKER_MAX_COUNT = 2; 88 IRemoteInvoker *invokers_[INVOKER_MAX_COUNT] = { nullptr, nullptr }; 89 const pid_t tid_; 90 std::atomic<int32_t> sendRequestCount_ = 0; 91 std::string threadName_; 92 ThreadType threadType_ = ThreadType::NORMAL_THREAD; 93 uint64_t ffrtTaskId_ = 0; 94 }; 95 #ifdef CONFIG_IPC_SINGLE 96 } // namespace IPC_SINGLE 97 #endif 98 } // namespace OHOS 99 #endif // OHOS_IPC_IPC_THREAD_SKELETON_H 100