1 /* 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> 23 #include <android/binder_ibinder.h> 24 #include <android/binder_manager.h> 25 26 namespace android { 27 28 class 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 41 template<class Intf> getServiceInstance(const std::string & instanceName)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)); 54 if (service != nullptr) { 55 HalDeathHandler::getInstance().registerHandler(serviceBinder); 56 } 57 } 58 return service; 59 } 60 61 } // namespace android 62