blob: 97a5bba80d02e23075a97a84d3926a0d0bb1ad4e [file] [log] [blame]
Mikhail Naganovd8f24412024-03-20 18:15:42 -07001/*
2 * Copyright (C) 2024 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#pragma once
18
19#include <memory>
20#include <string>
21
22#include <android/binder_auto_utils.h>
Mikhail Naganov065985f2024-03-25 10:50:00 -070023#include <android/binder_ibinder.h>
Mikhail Naganovd8f24412024-03-20 18:15:42 -070024#include <android/binder_manager.h>
25
26namespace android {
27
Mikhail Naganov065985f2024-03-25 10:50:00 -070028class HalDeathHandler {
29 public:
30 static HalDeathHandler& getInstance();
31
32 bool registerHandler(AIBinder* binder);
33 private:
34 static void OnBinderDied(void*);
35
36 HalDeathHandler();
37
38 ::ndk::ScopedAIBinder_DeathRecipient mDeathRecipient;
39};
40
Mikhail Naganovd8f24412024-03-20 18:15:42 -070041template<class Intf>
42std::shared_ptr<Intf> getServiceInstance(const std::string& instanceName) {
43 const std::string serviceName =
44 std::string(Intf::descriptor).append("/").append(instanceName);
45 std::shared_ptr<Intf> service;
46 while (!service) {
47 AIBinder* serviceBinder = nullptr;
48 while (!serviceBinder) {
49 // 'waitForService' may return a nullptr, hopefully a transient error.
50 serviceBinder = AServiceManager_waitForService(serviceName.c_str());
51 }
52 // `fromBinder` may fail and return a nullptr if the service has died in the meantime.
53 service = Intf::fromBinder(ndk::SpAIBinder(serviceBinder));
Mikhail Naganov065985f2024-03-25 10:50:00 -070054 if (service != nullptr) {
55 HalDeathHandler::getInstance().registerHandler(serviceBinder);
56 }
Mikhail Naganovd8f24412024-03-20 18:15:42 -070057 }
58 return service;
59}
60
61} // namespace android