1 /*
2  * Copyright (c) 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 CLIENT_DEATH_HANDLER_H
17 #define CLIENT_DEATH_HANDLER_H
18 
19 #include <functional>
20 #include <map>
21 #include <mutex>
22 #include <vector>
23 
24 #include "iremote_object.h"
25 #include "refbase.h"
26 #include "nocopyable.h"
27 
28 #include "input_binder_client_death_recipient.h"
29 
30 namespace OHOS {
31 namespace MMI {
32 enum class CallBackType : int32_t {
33     CALLBACK_TYPE_AUTHORIZE_HELPER,
34 };
35 using ClientDeathCallback = std::function<void(int32_t)>;
36 class ClientDeathHandler final : RefBase {
37 public:
38     ClientDeathHandler();
39     ~ClientDeathHandler();
40     DISALLOW_COPY_AND_MOVE(ClientDeathHandler);
41     bool RegisterClientDeathRecipient(const sptr<IRemoteObject> &binderClientSrv, int32_t pid);
42     bool AddClientDeathCallback(CallBackType type, ClientDeathCallback callback);
43     bool UnregisterClientDeathRecipient(const wptr<IRemoteObject> &remoteObj);
44     void RemoveClientDeathCallback(CallBackType type);
45 
46 protected:
47     bool RegisterClientDeathRecipient(const sptr<IRemoteObject> &binderClientSrv);
48     bool AddClientPid(const sptr<IRemoteObject> &binderClientSrv, int32_t pid);
49     void RemoveClientPid(int32_t pid);
50     int32_t FindClientPid(const sptr<IRemoteObject> &binderClientSrv);
51     void NotifyDeath(int32_t pid);
52 
53 private:
54     void OnDeath(const wptr<IRemoteObject> &remoteObj);
55     std::mutex mutexPidMap_;
56     std::map<int32_t, sptr<IRemoteObject>> clientPidMap_;
57     std::mutex mutexDeathRecipient_;
58     sptr<InputBinderClientDeathRecipient> deathRecipient_ = nullptr;
59     std::mutex mutexCallbacks_;
60     std::map<CallBackType, ClientDeathCallback> deathCallbacks_;
61 };
62 } // namespace MMI
63 } // namespace OHOS
64 #endif // CLIENT_DEATH_HANDLER_H
65