AndroidO Treble架构下Hal进程启动及HIDL服务注册过程--不全

https://blog.csdn.net/yangwen123/article/details/79854267

通过前面对Treble架构的介绍,我们知道,Android Framework进程和Hal分离,每个Hal独立运行在自己的进程地址空间,那么这些Hal进程是如何启动的呢?本文以composer hal为例展开分析。

在以下路径有composer hal的rc启动脚本:

hardware/interfaces/graphics/composer/2.1/default/[email protected]


    
    
  1. service hwcomposer-2-1 /vendor/bin/hw/[email protected]
  2. class hal animation
  3. user system
  4. group graphics drmrpc
  5. capabilities SYS_NICE
  6. onrestart restart surfaceflinger

编译后,会将该脚本文件copy到vendor/etc/init目录,在开机时,init进程会读取并解析这个脚本,然后启动[email protected]进程:

system         661     1   32288   7832 0                   0 S [email protected]
    
    

该进程的可执行文件是:vendor/bin/hw/[email protected]

该可执行文件对应的源码为:hardware/interfaces/graphics/composer/2.1/default/service.cpp

composer Hal启动过程

hardware/interfaces/graphics/composer/2.1/default/service.cpp


    
    
  1. int main() {
  2. // the conventional HAL might start binder services
  3. android::ProcessState::initWithDriver("/dev/vndbinder");
  4. android::ProcessState::self()->setThreadPoolMaxThreadCount(4);
  5. android::ProcessState::self()->startThreadPool();
  6. // same as SF main thread
  7. struct sched_param param = {0};
  8. param.sched_priority = 2;
  9. if (sched_setscheduler(0, SCHED_FIFO | SCHED_RESET_ON_FORK,
  10. ¶m) != 0) {
  11. ALOGE("Couldn't set SCHED_FIFO: %d", errno);
  12. }
  13. return defaultPassthroughServiceImplementation <IComposer>(4);
  14. }
前面我们分析了Treble架构下的binder通信变化,在Treble架构下,存在了3个binder设备,分别是/dev/binder、/dev/vndbinder、/dev/hwbinder,上层需要通过binder库来访问这些binder设备,而/dev/binder和/dev/vndbinder都是由libbinder来访问,因此需要指定打开的binder设备。
android::ProcessState::initWithDriver("/dev/vndbinder");
    
    
这句说明composer hal通过vndbinder来通信的,接下来就是设置binder线程个数为4,并启动binder线程池,然后调用
defaultPassthroughServiceImplementation<IComposer>(4)
    
    

完成composer hal的启动。

system\libhidl\transport\include\hidl\LegacySupport.h


    
    
  1. template <class Interface>
  2. __attribute__((warn_unused_result))
  3. status_t defaultPassthroughServiceImplementation(std::string name,
  4. size_t maxThreads = 1) {
  5. configureRpcThreadpool(maxThreads, true); //配置binder线程个数
  6. status_t result = registerPassthroughServiceImplementation <Interface>(name);
  7. if (result != OK) {
  8. return result;
  9. }
  10. joinRpcThreadpool();
  11. return 0;
  12. }

    
    
  1. template< class Interface>
  2. __attribute__((warn_unused_result))
  3. status_t registerPassthroughServiceImplementation(
  4. std:: string name = "default") {
  5. sp<Interface> service = Interface::getService(name, true /* getStub */); //从当前进程空间中拿到IComposer接口类对象
  6. if (service == nullptr) {
  7. ALOGE( "Could not get passthrough implementation for %s/%s.",
  8. Interface::descriptor, name.c_str());
  9. return EXIT_FAILURE;
  10. }
  11. LOG_FATAL_IF(service->isRemote(), "Implementation of %s/%s is remote!",
  12. Interface::descriptor, name.c_str());
  13. status_t status = service->registerAsService(name); //将IComposer注册到hwservicemanager中
  14. if (status == OK) {
  15. ALOGI( "Registration complete for %s/%s.",
  16. Interface::descriptor, name.c_str());
  17. } else {
  18. ALOGE( "Could not register service %s/%s (%d).",
  19. Interface::descriptor, name.c_str(), status);
  20. }
  21. return status;
  22. }

Hal进程获取IComposer类对象

在composer hal进程启动时,首先调用IComposer 的getService(“default”,true)来获取IComposer的类对象。

composer\2.1\[email protected]_genc++\gen\android\hardware\graphics\composer\2.1\ComposerAll.cpp


    
    
  1. ::android::sp<IComposer> IComposer::getService( const std:: string &serviceName, const bool getStub) {
  2. using ::android::hardware::defaultServiceManager;
  3. using ::android::hardware::details::waitForHwService;
  4. using ::android::hardware::getPassthroughServiceManager;
  5. using ::android::hardware::Return;
  6. using ::android::sp;
  7. using Transport = ::android::hidl::manager::V1_0::IServiceManager::Transport;
  8. sp<IComposer> iface = nullptr;
  9. const sp<::android::hidl::manager::V1_0::IServiceManager> sm = defaultServiceManager(); //获取hwservicemanager的代理
  10. if (sm == nullptr) {
  11. ALOGE( "getService: defaultServiceManager() is null");
  12. return nullptr;
  13. }
  14. Return<Transport> transportRet = sm->getTransport(IComposer::descriptor, serviceName); //查询IComposer的Transport
  15. if (!transportRet.isOk()) {
  16. ALOGE( "getService: defaultServiceManager()->getTransport returns %s", transportRet.description().c_str());
  17. return nullptr;
  18. }
  19. Transport transport = transportRet;
  20. const bool vintfHwbinder = (transport == Transport::HWBINDER);
  21. const bool vintfPassthru = (transport == Transport::PASSTHROUGH); //Transport类型判断
  22. #ifdef __ANDROID_TREBLE__
  23. #ifdef __ANDROID_DEBUGGABLE__
  24. const char* env = std::getenv( "TREBLE_TESTING_OVERRIDE");
  25. const bool trebleTestingOverride = env && ! strcmp(env, "true");
  26. const bool vintfLegacy = (transport == Transport::EMPTY) && trebleTestingOverride;
  27. #else // __ANDROID_TREBLE__ but not __ANDROID_DEBUGGABLE__
  28. const bool trebleTestingOverride = false;
  29. const bool vintfLegacy = false;
  30. #endif // __ANDROID_DEBUGGABLE__
  31. #else // not __ANDROID_TREBLE__
  32. const char* env = std::getenv( "TREBLE_TESTING_OVERRIDE");
  33. const bool trebleTestingOverride = env && ! strcmp(env, "true");
  34. const bool vintfLegacy = (transport == Transport::EMPTY);
  35. #endif // __ANDROID_TREBLE__
  36.      //hwbinder方式下获取IComposer对象
  37. for ( int tries = 0; !getStub && (vintfHwbinder || (vintfLegacy && tries == 0)); tries++) {
  38. if (tries > 1) {
  39. ALOGI( "getService: Will do try %d for %s/%s in 1s...", tries, IComposer::descriptor, serviceName.c_str());
  40. sleep( 1);
  41. }
  42. if (vintfHwbinder && tries > 0) {
  43. waitForHwService(IComposer::descriptor, serviceName);
  44. }
  45. Return<sp<::android::hidl::base::V1_0::IBase>> ret =
  46. sm->get(IComposer::descriptor, serviceName);
  47. if (!ret.isOk()) {
  48. ALOGE( "IComposer: defaultServiceManager()->get returns %s", ret.description().c_str());
  49. break;
  50. }
  51. sp<::android::hidl::base::V1_0::IBase> base = ret;
  52. if (base == nullptr) {
  53. if (tries > 0) {
  54. ALOGW( "IComposer: found null hwbinder interface");
  55. } continue;
  56. }
  57. Return<sp<IComposer>> castRet = IComposer::castFrom(base, true /* emitError */);
  58. if (!castRet.isOk()) {
  59. if (castRet.isDeadObject()) {
  60. ALOGW( "IComposer: found dead hwbinder service");
  61. continue;
  62. } else {
  63. ALOGW( "IComposer: cannot call into hwbinder service: %s; No permission? Check for selinux denials.", castRet.description().c_str());
  64. break;
  65. }
  66. }
  67. iface = castRet;
  68. if (iface == nullptr) {
  69. ALOGW( "IComposer: received incompatible service; bug in hwservicemanager?");
  70. break;
  71. }
  72. return iface;
  73. }
  74. //passthrough方式下获取IComposer对象
  75.     if (getStub || vintfPassthru || vintfLegacy) {
  76.         const sp<::android::hidl::manager::V1_0::IServiceManager> pm = getPassthroughServiceManager();
  77.         if (pm != nullptr) {
  78.             Return<sp<::android::hidl::base::V1_0::IBase>> ret =
  79.                     pm->get(IComposer::descriptor, serviceName);
  80.             if (ret.isOk()) {
  81.                 sp<::android::hidl::base::V1_0::IBase> baseInterface = ret;
  82.                 if (baseInterface != nullptr) {
  83.                     iface = IComposer::castFrom(baseInterface);
  84.                     if (!getStub || trebleTestingOverride) {
  85.                         iface = new BsComposer(iface);
  86.                     }
  87.                 }
  88.             }
  89.         }
  90.     }
  91.     return iface;

这里通过hwservicemanager获取当前服务的Tranport类型,Treble中定义的Tranport包括passthrough和binderized,每个hidl服务都在/system/manifest.xml或者/vendor/manifest.xml中指定了对应的Tranport类型:


manifest.xml文件的读取和解析都是由hwservicemanager来完成的,此时[email protected]作为hwservicemanager的client端,通过hwservicemanager的binder代理对象来请求hwservicemanager进程查询IComposer的Transport类型,从上图可以看出IComposer的Transport被定义为hwbinder,因此:

vintfHwbinder=true
vintfPassthru=false
vintfLegacy=false

hidl服务对象获取方式包括2中:

1. 通过查询hwservicemanager来获取;

2.通过PassthroughServiceManager从本进程地址空间中获取;

那如何选择获取方式呢? 其实就是vintfHwbinder、vintfPassthru、vintfLegacy、getStub这4个变量值来决定hidl服务的获取方式。

1. 当getStub为true时,不管hal属于什么传输模式,都采用PassthroughServiceManager获取接口对象;

2.当getStub为false时,则根据hal传输模式来选择接口获取方式;

       《1》 当hal模式为Hwbinder时,则从hwservicemanager中查询;

       《2》当hal传输模式为Passthru或Legacy时,则采用PassthroughServiceManager来获取;

那什么是Hwbinder,什么是Passthru及Legacy呢?下图是google提供的hal的roadmap图:



    
    
  1. if (getStub || vintfPassthru || vintfLegacy) {
  2. const sp<::android::hidl::manager::V1_0::IServiceManager> pm = getPassthroughServiceManager();
  3. if (pm != nullptr) {
  4. Return<sp<::android::hidl::base::V1_0::IBase>> ret =
  5. pm->get(IComposer::descriptor, serviceName);
  6. if (ret.isOk()) {
  7. sp<::android::hidl::base::V1_0::IBase> baseInterface = ret;
  8. if (baseInterface != nullptr) {
  9. iface = IComposer::castFrom(baseInterface);
  10. if (!getStub || trebleTestingOverride) {
  11. iface = new BsComposer(iface);
  12. }
  13. }
  14. }
  15. }
  16. }
sp<Interface> service = Interface::getService(name, true /* getStub */)所以getStub=true. 这里通过PassthroughServiceManager来获取IComposer对象。其实所有的Hal 进程都是通过PassthroughServiceManager来得到hidl服务对象的,而作为Hal进程的Client端Framework进程在获取hidl服务对象时,需要通过hal的Transport类型来选择获取方式。
system\libhidl\transport\ServiceManagement.cpp

     
     
  1. sp<IServiceManager> getPassthroughServiceManager() {
  2. static sp<PassthroughServiceManager> manager( new PassthroughServiceManager());
  3. return manager;
  4. }
这里只是简单的创建了一个PassthroughServiceManager对象。PassthroughServiceManager也实现了IServiceManager接口。然后通过PassthroughServiceManager询服务:

     
     
  1. Return<sp<IBase>> get( const hidl_string& fqName,
  2. const hidl_string& name) override {
  3. std:: string stdFqName(fqName.c_str());
  4. //fqName looks like [email protected]::IFoo
  5. size_t idx = stdFqName.find( "::");
  6. if (idx == std:: string::npos ||
  7. idx + strlen( "::") + 1 >= stdFqName.size()) {
  8. LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
  9. return nullptr;
  10. }
  11. std:: string packageAndVersion = stdFqName.substr( 0, idx);
  12. std:: string ifaceName = stdFqName.substr(idx + strlen( "::"));
  13. const std:: string prefix = packageAndVersion + "-impl";
  14. const std:: string sym = "HIDL_FETCH_" + ifaceName;
  15. const android_namespace_t* sphal_namespace = android_get_exported_namespace( "sphal");
  16. const int dlMode = RTLD_LAZY;
  17. void *handle = nullptr;
  18. // TODO: lookup in VINTF instead
  19. // TODO(b/34135607): Remove HAL_LIBRARY_PATH_SYSTEM
  20. dlerror(); // clear
  21. for ( const std:: string &path : {
  22. HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, HAL_LIBRARY_PATH_SYSTEM
  23. }) {
  24. std:: vector< std:: string> libs = search(path, prefix, ".so");
  25. for ( const std:: string &lib : libs) {
  26. const std:: string fullPath = path + lib;
  27. // If sphal namespace is available, try to load from the
  28. // namespace first. If it fails, fall back to the original
  29. // dlopen, which loads from the current namespace.
  30. if (sphal_namespace != nullptr && path != HAL_LIBRARY_PATH_SYSTEM) {
  31. const android_dlextinfo dlextinfo = {
  32. .flags = ANDROID_DLEXT_USE_NAMESPACE,
  33. // const_cast is dirty but required because
  34. // library_namespace field is non-const.
  35. .library_namespace = const_cast< android_namespace_t*>(sphal_namespace),
  36. };
  37. handle = android_dlopen_ext(fullPath.c_str(), dlMode, &dlextinfo);
  38. if (handle == nullptr) {
  39. const char* error = dlerror();
  40. LOG(WARNING) << "Failed to dlopen " << lib << " from sphal namespace:"
  41. << (error == nullptr ? "unknown error" : error);
  42. } else {
  43. LOG(DEBUG) << lib << " loaded from sphal namespace.";
  44. }
  45. }
  46. if (handle == nullptr) {
  47. handle = dlopen(fullPath.c_str(), dlMode);
  48. }
  49. if (handle == nullptr) {
  50. const char* error = dlerror();
  51. LOG(ERROR) << "Failed to dlopen " << lib << ": "
  52. << (error == nullptr ? "unknown error" : error);
  53. continue;
  54. }
  55. IBase* (*generator)( const char* name);
  56. *( void **)(&generator) = dlsym(handle, sym.c_str());
  57. if(!generator) {
  58. const char* error = dlerror();
  59. LOG(ERROR) << "Passthrough lookup opened " << lib
  60. << " but could not find symbol " << sym << ": "
  61. << (error == nullptr ? "unknown error" : error);
  62. dlclose(handle);
  63. continue;
  64. }
  65. IBase *interface = (*generator)(name.c_str());
  66. if (interface == nullptr) {
  67. dlclose(handle);
  68. continue; // this module doesn't provide this instance name
  69. }
  70. registerReference(fqName, name);
  71. return interface;
  72. }
  73. }
  74. return nullptr;
  75. }

根据传入的fqName=([email protected]::IComposer")获取当前的接口名IComposer,拼接出后面需要查找的函数名HIDL_FETCH_IComposer和库名字[email protected],然后查找"/system/lib64/hw/"、"/vendor/lib64/hw/"、"/odm/lib64/hw/"下是否有对应的so库。接着通过dlopen载入/vendor/lib/hw/[email protected],然后通过dlsym查找并调用HIDL_FETCH_IComposer函数,最后调用registerReference(fqName, name)向hwservicemanager注册。

hardware/interfaces/graphics/composer/2.1/default/Android.bp


     
     
  1. cc_library_shared {
  2. defaults: ["hidl_defaults"],
  3. proprietary: true,
  4. relative_install_path: "hw",
  5. srcs: ["Hwc.cpp"],
  6. static_libs: ["libhwcomposer-client"],
  7. shared_libs: [
  8. "libbase",
  9. "libcutils",
  10. "libfmq",
  11. "libhardware",
  12. "libhidlbase",
  13. "libhidltransport",
  14. "liblog",
  15. "libsync",
  16. "libutils",
  17. "libhwc2on1adapter"
  18. ],
  19. }
从上面的编译脚本可知,[email protected]的源码文件为Hwc.cpp:
hardware/interfaces/graphics/composer/2.1/default/Hwc.cpp

     
     
  1. IComposer* HIDL_FETCH_IComposer(const char*)
  2. {
  3. const hw_module_t* module = nullptr;
  4. int err = hw_get_module(HWC_HARDWARE_MODULE_ID, & module);
  5. if (err) {
  6. ALOGE( "failed to get hwcomposer module");
  7. return nullptr;
  8. }
  9. return new HwcHal( module);
  10. }
hw_get_module就和AndroidO以前的Hal模式一致,这正是Passthrough复用原有hal的原理。加载hal库后,得到hw_module_t,然后使用HwcHal来包裹hw_module_t,而HwcHal实现了IComposer接口。

registerPassthroughClient

得到IComposer接口对象HwcHal后,需要注册相关信息到hwservicemanager中。


system\libhidl\transport\ServiceManagement.cpp


     
     
  1. static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
  2. sp<IServiceManager> binderizedManager = defaultServiceManager();
  3. if (binderizedManager == nullptr) {
  4. LOG(WARNING) << "Could not registerReference for "
  5. << interfaceName << "/" << instanceName
  6. << ": null binderized manager.";
  7. return;
  8. }
  9. auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName);
  10. if (!ret.isOk()) {
  11. LOG(WARNING) << "Could not registerReference for "
  12. << interfaceName << "/" << instanceName
  13. << ": " << ret.description();
  14. return;
  15. }
  16. LOG(VERBOSE) << "Successfully registerReference for "
  17. << interfaceName << "/" << instanceName;
  18. }
这里通过hwservicemanager的代理对象跨进程调用registerPassthroughClient。

[email protected]_genc++\gen\android\hidl\manager\1.0\ServiceManagerAll.cpp


     
     
  1. ::android::hardware::Return< void> BpHwServiceManager::registerPassthroughClient( const ::android::hardware::hidl_string& fqName, const ::android::hardware::hidl_string& name){
  2. ::android::hardware::Return< void> _hidl_out = ::android::hidl::manager::V1_0::BpHwServiceManager::_hidl_registerPassthroughClient( this, this, fqName, name);
  3. return _hidl_out;
  4. }

     
     
  1. ::android::hardware::Return< void> BpHwServiceManager::_hidl_registerPassthroughClient(::android::hardware::IInterface *_hidl_this, ::android::hardware::details::HidlInstrumentor *_hidl_this_instrumentor, const ::android::hardware::hidl_string& fqName, const ::android::hardware::hidl_string& name) {
  2. #ifdef __ANDROID_DEBUGGABLE__
  3. bool mEnableInstrumentation = _hidl_this_instrumentor->isInstrumentationEnabled();
  4. const auto &mInstrumentationCallbacks = _hidl_this_instrumentor->getInstrumentationCallbacks();
  5. #else
  6. ( void) _hidl_this_instrumentor;
  7. #endif // __ANDROID_DEBUGGABLE__
  8. atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::registerPassthroughClient::client");
  9. #ifdef __ANDROID_DEBUGGABLE__
  10. if (UNLIKELY(mEnableInstrumentation)) {
  11. std:: vector< void *> _hidl_args;
  12. _hidl_args.push_back(( void *)&fqName);
  13. _hidl_args.push_back(( void *)&name);
  14. for ( const auto &callback: mInstrumentationCallbacks) {
  15. callback(InstrumentationEvent::CLIENT_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args);
  16. }
  17. }
  18. #endif // __ANDROID_DEBUGGABLE__
  19. ::android::hardware::Parcel _hidl_data;
  20. ::android::hardware::Parcel _hidl_reply;
  21. ::android:: status_t _hidl_err;
  22. ::android::hardware::Status _hidl_status;
  23. _hidl_err = _hidl_data.writeInterfaceToken(BpHwServiceManager::descriptor);
  24. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  25. size_t _hidl_fqName_parent;
  26. _hidl_err = _hidl_data.writeBuffer(&fqName, sizeof(fqName), &_hidl_fqName_parent);
  27. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  28. _hidl_err = ::android::hardware::writeEmbeddedToParcel(
  29. fqName,
  30. &_hidl_data,
  31. _hidl_fqName_parent,
  32. 0 /* parentOffset */);
  33. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  34. size_t _hidl_name_parent;
  35. _hidl_err = _hidl_data.writeBuffer(&name, sizeof(name), &_hidl_name_parent);
  36. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  37. _hidl_err = ::android::hardware::writeEmbeddedToParcel(
  38. name,
  39. &_hidl_data,
  40. _hidl_name_parent,
  41. 0 /* parentOffset */);
  42. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  43. _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact( 8 /* registerPassthroughClient */, _hidl_data, &_hidl_reply);
  44. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  45. _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);
  46. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  47. if (!_hidl_status.isOk()) { return _hidl_status; }
  48. atrace_end(ATRACE_TAG_HAL);
  49. #ifdef __ANDROID_DEBUGGABLE__
  50. if (UNLIKELY(mEnableInstrumentation)) {
  51. std:: vector< void *> _hidl_args;
  52. for ( const auto &callback: mInstrumentationCallbacks) {
  53. callback(InstrumentationEvent::CLIENT_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args);
  54. }
  55. }
  56. #endif // __ANDROID_DEBUGGABLE__
  57. _hidl_status.setFromStatusT(_hidl_err);
  58. return ::android::hardware::Return< void>();
  59. _hidl_error:
  60. _hidl_status.setFromStatusT(_hidl_err);
  61. return ::android::hardware::Return< void>(_hidl_status);
  62. }
这里和普通binder通信相同,先就需要传输的函数参数打包到Parcel对象中,然后调用binder代理对象的transact函数将函数参数,函数调用码发送到Server端进程,这里的_hidl_this其实指向的是BpHwServiceManager,这个是与业务相关的代理对象,通过asBinder函数得到与传输相关的binder代理,那这个binder代理是什么类型呢? 其实就是BpHwBinder,关于hwservicemanager代理对象的获取,asBinder函数的实现,在后续的章节中进行分析。经过BpHwServiceManager的请求,最终位于hwservicemanager进程中的BnHwServiceManager将接收函数调用请求:
[email protected]_genc++\gen\android\hidl\manager\1.0\ServiceManagerAll.cpp

     
     
  1. ::android:: status_t BnHwServiceManager::onTransact(
  2. uint32_t _hidl_code,
  3. const ::android::hardware::Parcel &_hidl_data,
  4. ::android::hardware::Parcel *_hidl_reply,
  5. uint32_t _hidl_flags,
  6. TransactCallback _hidl_cb) {
  7. ::android:: status_t _hidl_err = ::android::OK;
  8. switch (_hidl_code) {
  9. case 8 /* registerPassthroughClient */:
  10. {
  11. _hidl_err = ::android::hidl::manager::V1_0::BnHwServiceManager::_hidl_registerPassthroughClient( this, _hidl_data, _hidl_reply, _hidl_cb);
  12. break;
  13. }
  14. default:
  15. {
  16. return ::android::hidl::base::V1_0::BnHwBase::onTransact(
  17. _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb);
  18. }
  19. }
BnHwServiceManager将调用_hidl_registerPassthroughClient来执行Client端的注册。

     
     
  1. ::android:: status_t BnHwServiceManager::_hidl_registerPassthroughClient(
  2. ::android::hidl::base::V1_0::BnHwBase* _hidl_this,
  3. const ::android::hardware::Parcel &_hidl_data,
  4. ::android::hardware::Parcel *_hidl_reply,
  5. TransactCallback _hidl_cb) {
  6. #ifdef __ANDROID_DEBUGGABLE__
  7. bool mEnableInstrumentation = _hidl_this->isInstrumentationEnabled();
  8. const auto &mInstrumentationCallbacks = _hidl_this->getInstrumentationCallbacks();
  9. #endif // __ANDROID_DEBUGGABLE__
  10. ::android:: status_t _hidl_err = ::android::OK;
  11. if (!_hidl_data.enforceInterface(BnHwServiceManager::Pure::descriptor)) {
  12. _hidl_err = ::android::BAD_TYPE;
  13. return _hidl_err;
  14. }
  15. const ::android::hardware::hidl_string* fqName;
  16. const ::android::hardware::hidl_string* name;
  17. size_t _hidl_fqName_parent;
  18. _hidl_err = _hidl_data.readBuffer( sizeof(*fqName), &_hidl_fqName_parent, reinterpret_cast< const void **>(&fqName));
  19. if (_hidl_err != ::android::OK) { return _hidl_err; }
  20. _hidl_err = ::android::hardware::readEmbeddedFromParcel(
  21. const_cast<::android::hardware::hidl_string &>(*fqName),
  22. _hidl_data,
  23. _hidl_fqName_parent,
  24. 0 /* parentOffset */);
  25. if (_hidl_err != ::android::OK) { return _hidl_err; }
  26. size_t _hidl_name_parent;
  27. _hidl_err = _hidl_data.readBuffer( sizeof(*name), &_hidl_name_parent, reinterpret_cast< const void **>(&name));
  28. if (_hidl_err != ::android::OK) { return _hidl_err; }
  29. _hidl_err = ::android::hardware::readEmbeddedFromParcel(
  30. const_cast<::android::hardware::hidl_string &>(*name),
  31. _hidl_data,
  32. _hidl_name_parent,
  33. 0 /* parentOffset */);
  34. if (_hidl_err != ::android::OK) { return _hidl_err; }
  35. atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::registerPassthroughClient::server");
  36. #ifdef __ANDROID_DEBUGGABLE__
  37. if (UNLIKELY(mEnableInstrumentation)) {
  38. std:: vector< void *> _hidl_args;
  39. _hidl_args.push_back(( void *)fqName);
  40. _hidl_args.push_back(( void *)name);
  41. for ( const auto &callback: mInstrumentationCallbacks) {
  42. callback(InstrumentationEvent::SERVER_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args);
  43. }
  44. }
  45. #endif // __ANDROID_DEBUGGABLE__
  46. static_cast<BnHwServiceManager*>(_hidl_this)->_hidl_mImpl->registerPassthroughClient(*fqName, *name);
  47. ( void) _hidl_cb;
  48. atrace_end(ATRACE_TAG_HAL);
  49. #ifdef __ANDROID_DEBUGGABLE__
  50. if (UNLIKELY(mEnableInstrumentation)) {
  51. std:: vector< void *> _hidl_args;
  52. for ( const auto &callback: mInstrumentationCallbacks) {
  53. callback(InstrumentationEvent::SERVER_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args);
  54. }
  55. }
  56. #endif // __ANDROID_DEBUGGABLE__
  57. ::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply);
  58. return _hidl_err;
  59. }
BnHwServiceManager首先读取BpHwServiceManager发送过来的函数参数,然后将registerPassthroughClient的执行转交个其成员变量的_hidl_mImpl对象,然后将执行结果返回给BpHwServiceManager,那么_hidl_mImpl保存的是什么对象呢? 其实_hidl_mImpl指向的是ServiceManager对象,这个是在构造BnHwServiceManager对象时传入的,在后续分析hwservicemanager启动过程时,会进行详细分析。
system\hwservicemanager\ServiceManager.cpp

     
     
  1. Return< void> ServiceManager::registerPassthroughClient( const hidl_string &fqName,
  2. const hidl_string &name) {
  3. pid_t pid = IPCThreadState::self()->getCallingPid();
  4. if (!mAcl.canGet(fqName, pid)) { //根据Client端的pid及注册接口的包名,判断是否有权限注册
  5. /* We guard this function with "get", because it's typically used in
  6. * the getService() path, albeit for a passthrough service in this
  7. * case
  8. */
  9. return Void();
  10. }
  11. LOG(INFO) << "registerPassthroughClient " << fgName.c_str() << " of "
  12. << name.c_str()
  13. PackageInterfaceMap &ifaceMap = mServiceMap[fqName];
  14. if (name.empty()) {
  15. LOG(WARNING) << "registerPassthroughClient encounters empty instance name for "
  16. << fqName.c_str();
  17. return Void();
  18. }
  19. HidlService *service = ifaceMap.lookup(name);
  20. if (service == nullptr) {
  21. auto adding = std::make_unique<HidlService>(fqName, name);
  22. adding->registerPassthroughClient(pid);
  23. ifaceMap.insertService( std::move(adding));
  24. } else {
  25. service->registerPassthroughClient(pid);
  26. }
  27. return Void();
  28. }
首先根据fqName从mServiceMap中查找对应的PackageInterfaceMap,然后根据name从PackageInterfaceMap中查找HidlService,如果找不到对应的HidlService对象,那么就调用std::make_unique<HidlService>(fqName,name)创建一个新的HidlService对象,并ifaceMap.insertService(std::move(adding))添加到PackageInterfaceMap中。如果查找到了HidlService对象,那么仅仅将Client进程的pid保存到HidlService的mPassthroughClients变量中。
system\hwservicemanager\HidlService.h

     
     
  1. HidlService( const std:: string &interfaceName,
  2. const std:: string &instanceName)
  3. : HidlService(
  4. interfaceName,
  5. instanceName,
  6. nullptr,
  7. static_cast< pid_t>(IServiceManager::PidConstant::NO_PID))
  8. {}
因此registerPassthroughClient在hwservicemanager中插入一个HidlService对象而已,并没有注册对应的IBase对象。getService最后将HwcHal对象返回给registerPassthroughServiceImplementation()函数,然后再次调用registerAsService注册该IBase对象。

registerAsService注册

registerAsService用于向hwservicemanager注册IBase对象,由于前面通过PassthroughServiceManager得到的HwcHal继承于IBase,因此可以调用registerAsService函数来注册。
composer\2.1\[email protected]_genc++\gen\android\hardware\graphics\composer\2.1\ComposerAll.cpp

     
     
  1. ::android:: status_t IComposer::registerAsService( const std:: string &serviceName) {
  2. ::android::hardware::details::onRegistration( "[email protected]", "IComposer", serviceName);
  3. const ::android::sp<::android::hidl::manager::V1_0::IServiceManager> sm
  4. = ::android::hardware::defaultServiceManager();
  5. if (sm == nullptr) {
  6. return ::android::INVALID_OPERATION;
  7. }
  8. ::android::hardware::Return< bool> ret = sm->add(serviceName.c_str(), this);
  9. return ret.isOk() && ret ? ::android::OK : ::android::UNKNOWN_ERROR;
  10. }
首先执行onRegistration函数,然后调用hwservicemanager的代理对象的add函数。
system\libhidl\transport\ServiceManagement.cpp

     
     
  1. void onRegistration(const std::string &packageName,
  2. const std:: string& /* interfaceName */,
  3. const std:: string& /* instanceName */) {
  4. tryShortenProcessName(packageName);
  5. }

     
     
  1. void tryShortenProcessName(const std::string &packageName) {
  2. std:: string processName = binaryName();
  3. if (!startsWith(processName, packageName)) {
  4. return;
  5. }
  6. size_t lastDot = packageName.rfind( '.');
  7. size_t secondDot = packageName.rfind( '.', lastDot - 1);
  8. if (secondDot == std:: string::npos) {
  9. return;
  10. }
  11. std:: string newName = processName.substr(secondDot + 1,
  12. 16 /* TASK_COMM_LEN */ - 1);
  13. ALOGI( "Removing namespace from process name %s to %s.",
  14. processName.c_str(), newName.c_str());
  15. int rc = pthread_setname_np(pthread_self(), newName.c_str());
  16. ALOGI_IF(rc != 0, "Removing namespace from process name %s failed.",
  17. processName.c_str());
  18. }
这里只是简单的修改了当前进程的名称。

[email protected]_genc++\gen\android\hidl\manager\1.0\ServiceManagerAll.cpp


     
     
  1. ::android::hardware::Return< bool> BpHwServiceManager::add( const ::android::hardware::hidl_string& name, const ::android::sp<::android::hidl::base::V1_0::IBase>& service){
  2. ::android::hardware::Return< bool> _hidl_out = ::android::hidl::manager::V1_0::BpHwServiceManager::_hidl_add( this, this, name, service);
  3. return _hidl_out;
  4. }

     
     
  1. ::android::hardware::Return< bool> BpHwServiceManager::_hidl_add(::android::hardware::IInterface *_hidl_this, ::android::hardware::details::HidlInstrumentor *_hidl_this_instrumentor, const ::android::hardware::hidl_string& name, const ::android::sp<::android::hidl::base::V1_0::IBase>& service) {
  2. #ifdef __ANDROID_DEBUGGABLE__
  3. bool mEnableInstrumentation = _hidl_this_instrumentor->isInstrumentationEnabled();
  4. const auto &mInstrumentationCallbacks = _hidl_this_instrumentor->getInstrumentationCallbacks();
  5. #else
  6. ( void) _hidl_this_instrumentor;
  7. #endif // __ANDROID_DEBUGGABLE__
  8. atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::add::client");
  9. #ifdef __ANDROID_DEBUGGABLE__
  10. if (UNLIKELY(mEnableInstrumentation)) {
  11. std:: vector< void *> _hidl_args;
  12. _hidl_args.push_back(( void *)&name);
  13. _hidl_args.push_back(( void *)&service);
  14. for ( const auto &callback: mInstrumentationCallbacks) {
  15. callback(InstrumentationEvent::CLIENT_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args);
  16. }
  17. }
  18. #endif // __ANDROID_DEBUGGABLE__
  19. ::android::hardware::Parcel _hidl_data;
  20. ::android::hardware::Parcel _hidl_reply;
  21. ::android:: status_t _hidl_err;
  22. ::android::hardware::Status _hidl_status;
  23. bool _hidl_out_success;
  24. _hidl_err = _hidl_data.writeInterfaceToken(BpHwServiceManager::descriptor);
  25. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  26. size_t _hidl_name_parent;
  27. _hidl_err = _hidl_data.writeBuffer(&name, sizeof(name), &_hidl_name_parent);
  28. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  29. _hidl_err = ::android::hardware::writeEmbeddedToParcel(
  30. name,
  31. &_hidl_data,
  32. _hidl_name_parent,
  33. 0 /* parentOffset */);
  34. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  35. if (service == nullptr) {
  36. _hidl_err = _hidl_data.writeStrongBinder( nullptr);
  37. } else {
  38. ::android::sp<::android::hardware::IBinder> _hidl_binder = ::android::hardware::toBinder<
  39. ::android::hidl::base::V1_0::IBase>(service);
  40. if (_hidl_binder.get() != nullptr) {
  41. _hidl_err = _hidl_data.writeStrongBinder(_hidl_binder);
  42. } else {
  43. _hidl_err = ::android::UNKNOWN_ERROR;
  44. }
  45. }
  46. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  47. ::android::hardware::ProcessState::self()->startThreadPool();
  48. _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact( 2 /* add */, _hidl_data, &_hidl_reply);
  49. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  50. _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);
  51. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  52. if (!_hidl_status.isOk()) { return _hidl_status; }
  53. _hidl_err = _hidl_reply.readBool(&_hidl_out_success);
  54. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  55. atrace_end(ATRACE_TAG_HAL);
  56. #ifdef __ANDROID_DEBUGGABLE__
  57. if (UNLIKELY(mEnableInstrumentation)) {
  58. std:: vector< void *> _hidl_args;
  59. _hidl_args.push_back(( void *)&_hidl_out_success);
  60. for ( const auto &callback: mInstrumentationCallbacks) {
  61. callback(InstrumentationEvent::CLIENT_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args);
  62. }
  63. }
  64. #endif // __ANDROID_DEBUGGABLE__
  65. _hidl_status.setFromStatusT(_hidl_err);
  66. return ::android::hardware::Return< bool>(_hidl_out_success);
  67. _hidl_error:
  68. _hidl_status.setFromStatusT(_hidl_err);
  69. return ::android::hardware::Return< bool>(_hidl_status);
  70. }
这里的步骤和前面的registerPassthroughClient基本一致,唯一不同的是,此时需要向Server端hwservicemanager传输一个IBase对象。

     
     
  1. ::android::sp<::android::hardware::IBinder> _hidl_binder = ::android::hardware::toBinder<
  2. ::android::hidl::base::V1_0::IBase>(service);
  3. if (_hidl_binder.get() != nullptr) {
  4. _hidl_err = _hidl_data.writeStrongBinder(_hidl_binder);
  5. }
这里首先通过toBinder函数将IBase对象,其实就是HwcHal对象转换为IBinder对象,然后通过writeStrongBinder将IBinder对象序列化到Parcel中,toBinder函数在后续进行分析,我们这里只需要知道经过toBinder函数后,在Hal进程端会创建一个BnHwComposer本地binder对象,然后通过IPC调用发送给hwservicemanager。
[email protected]_genc++\gen\android\hidl\manager\1.0\ServiceManagerAll.cpp

     
     
  1. ::android:: status_t BnHwServiceManager::onTransact(
  2. uint32_t _hidl_code,
  3. const ::android::hardware::Parcel &_hidl_data,
  4. ::android::hardware::Parcel *_hidl_reply,
  5. uint32_t _hidl_flags,
  6. TransactCallback _hidl_cb) {
  7. ::android:: status_t _hidl_err = ::android::OK;
  8. switch (_hidl_code) {
  9. case 2 /* add */:
  10. {
  11. _hidl_err = ::android::hidl::manager::V1_0::BnHwServiceManager::_hidl_add( this, _hidl_data, _hidl_reply, _hidl_cb);
  12. break;
  13. }
  14. default:
  15. {
  16. return ::android::hidl::base::V1_0::BnHwBase::onTransact(
  17. _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb);
  18. }
  19. }
  20. if (_hidl_err == ::android::UNEXPECTED_NULL) {
  21. _hidl_err = ::android::hardware::writeToParcel(
  22. ::android::hardware::Status::fromExceptionCode(::android::hardware::Status::EX_NULL_POINTER),
  23. _hidl_reply);
  24. } return _hidl_err;
  25. }

     
     
  1. ::android:: status_t BnHwServiceManager::_hidl_add(
  2. ::android::hidl::base::V1_0::BnHwBase* _hidl_this,
  3. const ::android::hardware::Parcel &_hidl_data,
  4. ::android::hardware::Parcel *_hidl_reply,
  5. TransactCallback _hidl_cb) {
  6. #ifdef __ANDROID_DEBUGGABLE__
  7. bool mEnableInstrumentation = _hidl_this->isInstrumentationEnabled();
  8. const auto &mInstrumentationCallbacks = _hidl_this->getInstrumentationCallbacks();
  9. #endif // __ANDROID_DEBUGGABLE__
  10. ::android:: status_t _hidl_err = ::android::OK;
  11. if (!_hidl_data.enforceInterface(BnHwServiceManager::Pure::descriptor)) {
  12. _hidl_err = ::android::BAD_TYPE;
  13. return _hidl_err;
  14. }
  15. const ::android::hardware::hidl_string* name;
  16. ::android::sp<::android::hidl::base::V1_0::IBase> service;
  17. size_t _hidl_name_parent;
  18. _hidl_err = _hidl_data.readBuffer(sizeof(*name), &_hidl_name_parent, reinterpret_cast<const void **>(&name));
  19. if (_hidl_err != ::android::OK) { return _hidl_err; }
  20. _hidl_err = ::android::hardware::readEmbeddedFromParcel(
  21. const_cast<::android::hardware::hidl_string &>(*name),
  22. _hidl_data,
  23. _hidl_name_parent,
  24. 0 /* parentOffset */);
  25. if (_hidl_err != ::android::OK) { return _hidl_err; }
  26. {
  27. ::android::sp<::android::hardware::IBinder> _hidl_service_binder;
  28. _hidl_err = _hidl_data.readNullableStrongBinder(&_hidl_service_binder);
  29. if (_hidl_err != ::android::OK) { return _hidl_err; }
  30. service = ::android::hardware::fromBinder<::android::hidl::base::V1_0::IBase,::android::hidl::base::V1_0::BpHwBase,::android::hidl::base::V1_0::BnHwBase>(_hidl_service_binder);
  31. }
  32. atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::add::server");
  33. #ifdef __ANDROID_DEBUGGABLE__
  34. if (UNLIKELY(mEnableInstrumentation)) {
  35. std:: vector< void *> _hidl_args;
  36. _hidl_args.push_back(( void *)name);
  37. _hidl_args.push_back(( void *)&service);
  38. for ( const auto &callback: mInstrumentationCallbacks) {
  39. callback(InstrumentationEvent::SERVER_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args);
  40. }
  41. }
  42. #endif // __ANDROID_DEBUGGABLE__
  43. bool _hidl_out_success = static_cast<BnHwServiceManager*>(_hidl_this)->_hidl_mImpl->add(*name, service);
  44. ::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply);
  45. _hidl_err = _hidl_reply->writeBool(_hidl_out_success);
  46. /* _hidl_err ignored! */
  47. atrace_end(ATRACE_TAG_HAL);
  48. #ifdef __ANDROID_DEBUGGABLE__
  49. if (UNLIKELY(mEnableInstrumentation)) {
  50. std:: vector< void *> _hidl_args;
  51. _hidl_args.push_back(( void *)&_hidl_out_success);
  52. for ( const auto &callback: mInstrumentationCallbacks) {
  53. callback(InstrumentationEvent::SERVER_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args);
  54. }
  55. }
  56. #endif // __ANDROID_DEBUGGABLE__
  57. _hidl_cb(*_hidl_reply);
  58. return _hidl_err;
  59. }
hwservicemanager进程通过_hidl_err = _hidl_data.readNullableStrongBinder(&_hidl_service_binder);拿到client进程发送过来的BnHwComposer对象,binder实体到达目的端进程将变为binder代理对象,然后通过fromBinder函数将binder代理对象转换为业务代理对象BpHwBase,这个过程在后续进行详细分析,接下来继续调用_hidl_mImpl的add函数,而我们知道_hidl_mImpl其实就是ServiceManager:

system\hwservicemanager\ServiceManager.cpp

     
     
  1. Return< bool> ServiceManager::add( const hidl_string& name, const sp<IBase>& service) {
  2. bool isValidService = false;
  3. if (service == nullptr) {
  4. return false;
  5. }
  6. LOG(INFO) << "register service " << name;
  7. // TODO(b/34235311): use HIDL way to determine this
  8. // also, this assumes that the PID that is registering is the pid that is the service
  9. pid_t pid = IPCThreadState::self()->getCallingPid();
  10. auto ret = service->interfaceChain([&]( const auto &interfaceChain) {
  11. if (interfaceChain.size() == 0) {
  12. return;
  13. }
  14.         ...
  15. });
  16. if (!ret.isOk()) {
  17. LOG(ERROR) << "Failed to retrieve interface chain.";
  18. return false;
  19. }
  20. return isValidService;
  21. }
接着调用interfaceChain函数并传入一个函数回调,由于此时service是BpHwBase对象,BpHwBase的interfaceChain函数实现如下:
[email protected]_genc++\gen\android\hidl\base\1.0\BaseAll.cpp

     
     
  1. ::android::hardware::Return< void> BpHwBase::interfaceChain(interfaceChain_cb _hidl_cb){
  2. ::android::hardware::Return< void> _hidl_out = ::android::hidl::base::V1_0::BpHwBase::_hidl_interfaceChain( this, this, _hidl_cb);
  3. return _hidl_out;
  4. }

     
     
  1. ::android::hardware::Return< void> BpHwBase::_hidl_interfaceChain(::android::hardware::IInterface *_hidl_this, ::android::hardware::details::HidlInstrumentor *_hidl_this_instrumentor, interfaceChain_cb _hidl_cb) {
  2. #ifdef __ANDROID_DEBUGGABLE__
  3. bool mEnableInstrumentation = _hidl_this_instrumentor->isInstrumentationEnabled();
  4. const auto &mInstrumentationCallbacks = _hidl_this_instrumentor->getInstrumentationCallbacks();
  5. #else
  6. ( void) _hidl_this_instrumentor;
  7. #endif // __ANDROID_DEBUGGABLE__
  8. if (_hidl_cb == nullptr) {
  9. return ::android::hardware::Status::fromExceptionCode(
  10. ::android::hardware::Status::EX_ILLEGAL_ARGUMENT,
  11. "Null synchronous callback passed.");
  12. }
  13. atrace_begin(ATRACE_TAG_HAL, "HIDL::IBase::interfaceChain::client");
  14. #ifdef __ANDROID_DEBUGGABLE__
  15. if (UNLIKELY(mEnableInstrumentation)) {
  16. std:: vector< void *> _hidl_args;
  17. for ( const auto &callback: mInstrumentationCallbacks) {
  18. callback(InstrumentationEvent::CLIENT_API_ENTRY, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args);
  19. }
  20. }
  21. #endif // __ANDROID_DEBUGGABLE__
  22. ::android::hardware::Parcel _hidl_data;
  23. ::android::hardware::Parcel _hidl_reply;
  24. ::android:: status_t _hidl_err;
  25. ::android::hardware::Status _hidl_status;
  26. const ::android::hardware::hidl_vec<::android::hardware::hidl_string>* _hidl_out_descriptors;
  27. _hidl_err = _hidl_data.writeInterfaceToken(BpHwBase::descriptor);
  28. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  29. _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact( 256067662 /* interfaceChain */, _hidl_data, &_hidl_reply);
  30. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  31. _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);
  32. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  33. if (!_hidl_status.isOk()) { return _hidl_status; }
  34. size_t _hidl__hidl_out_descriptors_parent;
  35. _hidl_err = _hidl_reply.readBuffer( sizeof(*_hidl_out_descriptors), &_hidl__hidl_out_descriptors_parent, reinterpret_cast< const void **>(&_hidl_out_descriptors));
  36. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  37. size_t _hidl__hidl_out_descriptors_child;
  38. _hidl_err = ::android::hardware::readEmbeddedFromParcel(
  39. const_cast<::android::hardware::hidl_vec<::android::hardware::hidl_string> &>(*_hidl_out_descriptors),
  40. _hidl_reply,
  41. _hidl__hidl_out_descriptors_parent,
  42. 0 /* parentOffset */, &_hidl__hidl_out_descriptors_child);
  43. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  44. for ( size_t _hidl_index_0 = 0; _hidl_index_0 < _hidl_out_descriptors->size(); ++_hidl_index_0) {
  45. _hidl_err = ::android::hardware::readEmbeddedFromParcel(
  46. const_cast<::android::hardware::hidl_string &>((*_hidl_out_descriptors)[_hidl_index_0]),
  47. _hidl_reply,
  48. _hidl__hidl_out_descriptors_child,
  49. _hidl_index_0 * sizeof(::android::hardware::hidl_string));
  50. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  51. }
  52. _hidl_cb(*_hidl_out_descriptors);
  53. atrace_end(ATRACE_TAG_HAL);
  54. #ifdef __ANDROID_DEBUGGABLE__
  55. if (UNLIKELY(mEnableInstrumentation)) {
  56. std:: vector< void *> _hidl_args;
  57. _hidl_args.push_back(( void *)_hidl_out_descriptors);
  58. for ( const auto &callback: mInstrumentationCallbacks) {
  59. callback(InstrumentationEvent::CLIENT_API_EXIT, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args);
  60. }
  61. }
  62. #endif // __ANDROID_DEBUGGABLE__
  63. _hidl_status.setFromStatusT(_hidl_err);
  64. return ::android::hardware::Return< void>();
  65. _hidl_error:
  66. _hidl_status.setFromStatusT(_hidl_err);
  67. return ::android::hardware::Return< void>(_hidl_status);
  68. }
这里再次回到Hal进程空间,调用BnHwComposer的interfaceChain函数查询_hidl_out_descriptors,

然后调用传递进来的回调函数_hidl_cb。因此BnHwComposer的onTransact将接收请求:
composer\2.1\[email protected]_genc++\gen\android\hardware\graphics\composer\2.1\ComposerAll.cpp

     
     
  1. ::android:: status_t BnHwComposer::onTransact(
  2. uint32_t _hidl_code,
  3. const ::android::hardware::Parcel &_hidl_data,
  4. ::android::hardware::Parcel *_hidl_reply,
  5. uint32_t _hidl_flags,
  6. TransactCallback _hidl_cb) {
  7. ::android:: status_t _hidl_err = ::android::OK;
  8. switch (_hidl_code) {
  9. case 256067662 /* interfaceChain */:
  10. {
  11. _hidl_err = ::android::hidl::base::V1_0::BnHwBase::_hidl_interfaceChain( this, _hidl_data, _hidl_reply, _hidl_cb);
  12. break;
  13. }
  14. default:
  15. {
  16. return ::android::hidl::base::V1_0::BnHwBase::onTransact(
  17. _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb);
  18. }
  19. }
  20. if (_hidl_err == ::android::UNEXPECTED_NULL) {
  21. _hidl_err = ::android::hardware::writeToParcel(
  22. ::android::hardware::Status::fromExceptionCode(::android::hardware::Status::EX_NULL_POINTER),
  23. _hidl_reply);
  24. } return _hidl_err;
  25. }
注意,onTransact的最后一个参数是一个回调函数,是由IPCThreadState传递进来的,该回调函数将传入BnHwBase的interfaceChain中执行。这个实现由其父类BnHwBase来完成:
[email protected]_genc++\gen\android\hidl\base\1.0\BaseAll.cpp

     
     
  1. ::android:: status_t BnHwBase::_hidl_interfaceChain(
  2. BnHwBase* _hidl_this,
  3. const ::android::hardware::Parcel &_hidl_data,
  4. ::android::hardware::Parcel *_hidl_reply,
  5. TransactCallback _hidl_cb) {
  6. #ifdef __ANDROID_DEBUGGABLE__
  7. bool mEnableInstrumentation = _hidl_this->isInstrumentationEnabled();
  8. const auto &mInstrumentationCallbacks = _hidl_this->getInstrumentationCallbacks();
  9. #endif // __ANDROID_DEBUGGABLE__
  10. ::android:: status_t _hidl_err = ::android::OK;
  11. if (!_hidl_data.enforceInterface(BnHwBase::Pure::descriptor)) {
  12. _hidl_err = ::android::BAD_TYPE;
  13. return _hidl_err;
  14. }
  15. atrace_begin(ATRACE_TAG_HAL, "HIDL::IBase::interfaceChain::server");
  16. #ifdef __ANDROID_DEBUGGABLE__
  17. if (UNLIKELY(mEnableInstrumentation)) {
  18. std:: vector< void *> _hidl_args;
  19. for ( const auto &callback: mInstrumentationCallbacks) {
  20. callback(InstrumentationEvent::SERVER_API_ENTRY, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args);
  21. }
  22. }
  23. #endif // __ANDROID_DEBUGGABLE__

通过前面对Treble架构的介绍,我们知道,Android Framework进程和Hal分离,每个Hal独立运行在自己的进程地址空间,那么这些Hal进程是如何启动的呢?本文以composer hal为例展开分析。

在以下路径有composer hal的rc启动脚本:

hardware/interfaces/graphics/composer/2.1/default/[email protected]


  
  
  1. service hwcomposer-2-1 /vendor/bin/hw/[email protected]
  2. class hal animation
  3. user system
  4. group graphics drmrpc
  5. capabilities SYS_NICE
  6. onrestart restart surfaceflinger

编译后,会将该脚本文件copy到vendor/etc/init目录,在开机时,init进程会读取并解析这个脚本,然后启动[email protected]进程:

system         661     1   32288   7832 0                   0 S [email protected]
  
  

该进程的可执行文件是:vendor/bin/hw/[email protected]

该可执行文件对应的源码为:hardware/interfaces/graphics/composer/2.1/default/service.cpp

composer Hal启动过程

hardware/interfaces/graphics/composer/2.1/default/service.cpp


  
  
  1. int main() {
  2. // the conventional HAL might start binder services
  3. android::ProcessState::initWithDriver("/dev/vndbinder");
  4. android::ProcessState::self()->setThreadPoolMaxThreadCount(4);
  5. android::ProcessState::self()->startThreadPool();
  6. // same as SF main thread
  7. struct sched_param param = {0};
  8. param.sched_priority = 2;
  9. if (sched_setscheduler(0, SCHED_FIFO | SCHED_RESET_ON_FORK,
  10. ¶m) != 0) {
  11. ALOGE("Couldn't set SCHED_FIFO: %d", errno);
  12. }
  13. return defaultPassthroughServiceImplementation <IComposer>(4);
  14. }
前面我们分析了Treble架构下的binder通信变化,在Treble架构下,存在了3个binder设备,分别是/dev/binder、/dev/vndbinder、/dev/hwbinder,上层需要通过binder库来访问这些binder设备,而/dev/binder和/dev/vndbinder都是由libbinder来访问,因此需要指定打开的binder设备。
android::ProcessState::initWithDriver("/dev/vndbinder");
  
  
这句说明composer hal通过vndbinder来通信的,接下来就是设置binder线程个数为4,并启动binder线程池,然后调用
defaultPassthroughServiceImplementation<IComposer>(4)
  
  

完成composer hal的启动。

system\libhidl\transport\include\hidl\LegacySupport.h


  
  
  1. template <class Interface>
  2. __attribute__((warn_unused_result))
  3. status_t defaultPassthroughServiceImplementation(std::string name,
  4. size_t maxThreads = 1) {
  5. configureRpcThreadpool(maxThreads, true); //配置binder线程个数
  6. status_t result = registerPassthroughServiceImplementation <Interface>(name);
  7. if (result != OK) {
  8. return result;
  9. }
  10. joinRpcThreadpool();
  11. return 0;
  12. }

  
  
  1. template< class Interface>
  2. __attribute__((warn_unused_result))
  3. status_t registerPassthroughServiceImplementation(
  4. std:: string name = "default") {
  5. sp<Interface> service = Interface::getService(name, true /* getStub */); //从当前进程空间中拿到IComposer接口类对象
  6. if (service == nullptr) {
  7. ALOGE( "Could not get passthrough implementation for %s/%s.",
  8. Interface::descriptor, name.c_str());
  9. return EXIT_FAILURE;
  10. }
  11. LOG_FATAL_IF(service->isRemote(), "Implementation of %s/%s is remote!",
  12. Interface::descriptor, name.c_str());
  13. status_t status = service->registerAsService(name); //将IComposer注册到hwservicemanager中
  14. if (status == OK) {
  15. ALOGI( "Registration complete for %s/%s.",
  16. Interface::descriptor, name.c_str());
  17. } else {
  18. ALOGE( "Could not register service %s/%s (%d).",
  19. Interface::descriptor, name.c_str(), status);
  20. }
  21. return status;
  22. }

Hal进程获取IComposer类对象

在composer hal进程启动时,首先调用IComposer 的getService(“default”,true)来获取IComposer的类对象。

composer\2.1\[email protected]_genc++\gen\android\hardware\graphics\composer\2.1\ComposerAll.cpp


  
  
  1. ::android::sp<IComposer> IComposer::getService( const std:: string &serviceName, const bool getStub) {
  2. using ::android::hardware::defaultServiceManager;
  3. using ::android::hardware::details::waitForHwService;
  4. using ::android::hardware::getPassthroughServiceManager;
  5. using ::android::hardware::Return;
  6. using ::android::sp;
  7. using Transport = ::android::hidl::manager::V1_0::IServiceManager::Transport;
  8. sp<IComposer> iface = nullptr;
  9. const sp<::android::hidl::manager::V1_0::IServiceManager> sm = defaultServiceManager(); //获取hwservicemanager的代理
  10. if (sm == nullptr) {
  11. ALOGE( "getService: defaultServiceManager() is null");
  12. return nullptr;
  13. }
  14. Return<Transport> transportRet = sm->getTransport(IComposer::descriptor, serviceName); //查询IComposer的Transport
  15. if (!transportRet.isOk()) {
  16. ALOGE( "getService: defaultServiceManager()->getTransport returns %s", transportRet.description().c_str());
  17. return nullptr;
  18. }
  19. Transport transport = transportRet;
  20. const bool vintfHwbinder = (transport == Transport::HWBINDER);
  21. const bool vintfPassthru = (transport == Transport::PASSTHROUGH); //Transport类型判断
  22. #ifdef __ANDROID_TREBLE__
  23. #ifdef __ANDROID_DEBUGGABLE__
  24. const char* env = std::getenv( "TREBLE_TESTING_OVERRIDE");
  25. const bool trebleTestingOverride = env && ! strcmp(env, "true");
  26. const bool vintfLegacy = (transport == Transport::EMPTY) && trebleTestingOverride;
  27. #else // __ANDROID_TREBLE__ but not __ANDROID_DEBUGGABLE__
  28. const bool trebleTestingOverride = false;
  29. const bool vintfLegacy = false;
  30. #endif // __ANDROID_DEBUGGABLE__
  31. #else // not __ANDROID_TREBLE__
  32. const char* env = std::getenv( "TREBLE_TESTING_OVERRIDE");
  33. const bool trebleTestingOverride = env && ! strcmp(env, "true");
  34. const bool vintfLegacy = (transport == Transport::EMPTY);
  35. #endif // __ANDROID_TREBLE__
  36.      //hwbinder方式下获取IComposer对象
  37. for ( int tries = 0; !getStub && (vintfHwbinder || (vintfLegacy && tries == 0)); tries++) {
  38. if (tries > 1) {
  39. ALOGI( "getService: Will do try %d for %s/%s in 1s...", tries, IComposer::descriptor, serviceName.c_str());
  40. sleep( 1);
  41. }
  42. if (vintfHwbinder && tries > 0) {
  43. waitForHwService(IComposer::descriptor, serviceName);
  44. }
  45. Return<sp<::android::hidl::base::V1_0::IBase>> ret =
  46. sm->get(IComposer::descriptor, serviceName);
  47. if (!ret.isOk()) {
  48. ALOGE( "IComposer: defaultServiceManager()->get returns %s", ret.description().c_str());
  49. break;
  50. }
  51. sp<::android::hidl::base::V1_0::IBase> base = ret;
  52. if (base == nullptr) {
  53. if (tries > 0) {
  54. ALOGW( "IComposer: found null hwbinder interface");
  55. } continue;
  56. }
  57. Return<sp<IComposer>> castRet = IComposer::castFrom(base, true /* emitError */);
  58. if (!castRet.isOk()) {
  59. if (castRet.isDeadObject()) {
  60. ALOGW( "IComposer: found dead hwbinder service");
  61. continue;
  62. } else {
  63. ALOGW( "IComposer: cannot call into hwbinder service: %s; No permission? Check for selinux denials.", castRet.description().c_str());
  64. break;
  65. }
  66. }
  67. iface = castRet;
  68. if (iface == nullptr) {
  69. ALOGW( "IComposer: received incompatible service; bug in hwservicemanager?");
  70. break;
  71. }
  72. return iface;
  73. }
  74. //passthrough方式下获取IComposer对象
  75.     if (getStub || vintfPassthru || vintfLegacy) {
  76.         const sp<::android::hidl::manager::V1_0::IServiceManager> pm = getPassthroughServiceManager();
  77.         if (pm != nullptr) {
  78.             Return<sp<::android::hidl::base::V1_0::IBase>> ret =
  79.                     pm->get(IComposer::descriptor, serviceName);
  80.             if (ret.isOk()) {
  81.                 sp<::android::hidl::base::V1_0::IBase> baseInterface = ret;
  82.                 if (baseInterface != nullptr) {
  83.                     iface = IComposer::castFrom(baseInterface);
  84.                     if (!getStub || trebleTestingOverride) {
  85.                         iface = new BsComposer(iface);
  86.                     }
  87.                 }
  88.             }
  89.         }
  90.     }
  91.     return iface;

这里通过hwservicemanager获取当前服务的Tranport类型,Treble中定义的Tranport包括passthrough和binderized,每个hidl服务都在/system/manifest.xml或者/vendor/manifest.xml中指定了对应的Tranport类型:


manifest.xml文件的读取和解析都是由hwservicemanager来完成的,此时[email protected]作为hwservicemanager的client端,通过hwservicemanager的binder代理对象来请求hwservicemanager进程查询IComposer的Transport类型,从上图可以看出IComposer的Transport被定义为hwbinder,因此:

vintfHwbinder=true
vintfPassthru=false
vintfLegacy=false

hidl服务对象获取方式包括2中:

1. 通过查询hwservicemanager来获取;

2.通过PassthroughServiceManager从本进程地址空间中获取;

那如何选择获取方式呢? 其实就是vintfHwbinder、vintfPassthru、vintfLegacy、getStub这4个变量值来决定hidl服务的获取方式。

1. 当getStub为true时,不管hal属于什么传输模式,都采用PassthroughServiceManager获取接口对象;

2.当getStub为false时,则根据hal传输模式来选择接口获取方式;

       《1》 当hal模式为Hwbinder时,则从hwservicemanager中查询;

       《2》当hal传输模式为Passthru或Legacy时,则采用PassthroughServiceManager来获取;

那什么是Hwbinder,什么是Passthru及Legacy呢?下图是google提供的hal的roadmap图:



  
  
  1. if (getStub || vintfPassthru || vintfLegacy) {
  2. const sp<::android::hidl::manager::V1_0::IServiceManager> pm = getPassthroughServiceManager();
  3. if (pm != nullptr) {
  4. Return<sp<::android::hidl::base::V1_0::IBase>> ret =
  5. pm->get(IComposer::descriptor, serviceName);
  6. if (ret.isOk()) {
  7. sp<::android::hidl::base::V1_0::IBase> baseInterface = ret;
  8. if (baseInterface != nullptr) {
  9. iface = IComposer::castFrom(baseInterface);
  10. if (!getStub || trebleTestingOverride) {
  11. iface = new BsComposer(iface);
  12. }
  13. }
  14. }
  15. }
  16. }
sp<Interface> service = Interface::getService(name, true /* getStub */)所以getStub=true. 这里通过PassthroughServiceManager来获取IComposer对象。其实所有的Hal 进程都是通过PassthroughServiceManager来得到hidl服务对象的,而作为Hal进程的Client端Framework进程在获取hidl服务对象时,需要通过hal的Transport类型来选择获取方式。
system\libhidl\transport\ServiceManagement.cpp

   
   
  1. sp<IServiceManager> getPassthroughServiceManager() {
  2. static sp<PassthroughServiceManager> manager( new PassthroughServiceManager());
  3. return manager;
  4. }
这里只是简单的创建了一个PassthroughServiceManager对象。PassthroughServiceManager也实现了IServiceManager接口。然后通过PassthroughServiceManager询服务:

   
   
  1. Return<sp<IBase>> get( const hidl_string& fqName,
  2. const hidl_string& name) override {
  3. std:: string stdFqName(fqName.c_str());
  4. //fqName looks like [email protected]::IFoo
  5. size_t idx = stdFqName.find( "::");
  6. if (idx == std:: string::npos ||
  7. idx + strlen( "::") + 1 >= stdFqName.size()) {
  8. LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
  9. return nullptr;
  10. }
  11. std:: string packageAndVersion = stdFqName.substr( 0, idx);
  12. std:: string ifaceName = stdFqName.substr(idx + strlen( "::"));
  13. const std:: string prefix = packageAndVersion + "-impl";
  14. const std:: string sym = "HIDL_FETCH_" + ifaceName;
  15. const android_namespace_t* sphal_namespace = android_get_exported_namespace( "sphal");
  16. const int dlMode = RTLD_LAZY;
  17. void *handle = nullptr;
  18. // TODO: lookup in VINTF instead
  19. // TODO(b/34135607): Remove HAL_LIBRARY_PATH_SYSTEM
  20. dlerror(); // clear
  21. for ( const std:: string &path : {
  22. HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, HAL_LIBRARY_PATH_SYSTEM
  23. }) {
  24. std:: vector< std:: string> libs = search(path, prefix, ".so");
  25. for ( const std:: string &lib : libs) {
  26. const std:: string fullPath = path + lib;
  27. // If sphal namespace is available, try to load from the
  28. // namespace first. If it fails, fall back to the original
  29. // dlopen, which loads from the current namespace.
  30. if (sphal_namespace != nullptr && path != HAL_LIBRARY_PATH_SYSTEM) {
  31. const android_dlextinfo dlextinfo = {
  32. .flags = ANDROID_DLEXT_USE_NAMESPACE,
  33. // const_cast is dirty but required because
  34. // library_namespace field is non-const.
  35. .library_namespace = const_cast< android_namespace_t*>(sphal_namespace),
  36. };
  37. handle = android_dlopen_ext(fullPath.c_str(), dlMode, &dlextinfo);
  38. if (handle == nullptr) {
  39. const char* error = dlerror();
  40. LOG(WARNING) << "Failed to dlopen " << lib << " from sphal namespace:"
  41. << (error == nullptr ? "unknown error" : error);
  42. } else {
  43. LOG(DEBUG) << lib << " loaded from sphal namespace.";
  44. }
  45. }
  46. if (handle == nullptr) {
  47. handle = dlopen(fullPath.c_str(), dlMode);
  48. }
  49. if (handle == nullptr) {
  50. const char* error = dlerror();
  51. LOG(ERROR) << "Failed to dlopen " << lib << ": "
  52. << (error == nullptr ? "unknown error" : error);
  53. continue;
  54. }
  55. IBase* (*generator)( const char* name);
  56. *( void **)(&generator) = dlsym(handle, sym.c_str());
  57. if(!generator) {
  58. const char* error = dlerror();
  59. LOG(ERROR) << "Passthrough lookup opened " << lib
  60. << " but could not find symbol " << sym << ": "
  61. << (error == nullptr ? "unknown error" : error);
  62. dlclose(handle);
  63. continue;
  64. }
  65. IBase *interface = (*generator)(name.c_str());
  66. if (interface == nullptr) {
  67. dlclose(handle);
  68. continue; // this module doesn't provide this instance name
  69. }
  70. registerReference(fqName, name);
  71. return interface;
  72. }
  73. }
  74. return nullptr;
  75. }

根据传入的fqName=([email protected]::IComposer")获取当前的接口名IComposer,拼接出后面需要查找的函数名HIDL_FETCH_IComposer和库名字[email protected],然后查找"/system/lib64/hw/"、"/vendor/lib64/hw/"、"/odm/lib64/hw/"下是否有对应的so库。接着通过dlopen载入/vendor/lib/hw/[email protected],然后通过dlsym查找并调用HIDL_FETCH_IComposer函数,最后调用registerReference(fqName, name)向hwservicemanager注册。

hardware/interfaces/graphics/composer/2.1/default/Android.bp


   
   
  1. cc_library_shared {
  2. defaults: ["hidl_defaults"],
  3. proprietary: true,
  4. relative_install_path: "hw",
  5. srcs: ["Hwc.cpp"],
  6. static_libs: ["libhwcomposer-client"],
  7. shared_libs: [
  8. "libbase",
  9. "libcutils",
  10. "libfmq",
  11. "libhardware",
  12. "libhidlbase",
  13. "libhidltransport",
  14. "liblog",
  15. "libsync",
  16. "libutils",
  17. "libhwc2on1adapter"
  18. ],
  19. }
从上面的编译脚本可知,[email protected]的源码文件为Hwc.cpp:
hardware/interfaces/graphics/composer/2.1/default/Hwc.cpp

   
   
  1. IComposer* HIDL_FETCH_IComposer(const char*)
  2. {
  3. const hw_module_t* module = nullptr;
  4. int err = hw_get_module(HWC_HARDWARE_MODULE_ID, & module);
  5. if (err) {
  6. ALOGE( "failed to get hwcomposer module");
  7. return nullptr;
  8. }
  9. return new HwcHal( module);
  10. }
hw_get_module就和AndroidO以前的Hal模式一致,这正是Passthrough复用原有hal的原理。加载hal库后,得到hw_module_t,然后使用HwcHal来包裹hw_module_t,而HwcHal实现了IComposer接口。

registerPassthroughClient

得到IComposer接口对象HwcHal后,需要注册相关信息到hwservicemanager中。


system\libhidl\transport\ServiceManagement.cpp


   
   
  1. static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
  2. sp<IServiceManager> binderizedManager = defaultServiceManager();
  3. if (binderizedManager == nullptr) {
  4. LOG(WARNING) << "Could not registerReference for "
  5. << interfaceName << "/" << instanceName
  6. << ": null binderized manager.";
  7. return;
  8. }
  9. auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName);
  10. if (!ret.isOk()) {
  11. LOG(WARNING) << "Could not registerReference for "
  12. << interfaceName << "/" << instanceName
  13. << ": " << ret.description();
  14. return;
  15. }
  16. LOG(VERBOSE) << "Successfully registerReference for "
  17. << interfaceName << "/" << instanceName;
  18. }
这里通过hwservicemanager的代理对象跨进程调用registerPassthroughClient。

[email protected]_genc++\gen\android\hidl\manager\1.0\ServiceManagerAll.cpp


   
   
  1. ::android::hardware::Return< void> BpHwServiceManager::registerPassthroughClient( const ::android::hardware::hidl_string& fqName, const ::android::hardware::hidl_string& name){
  2. ::android::hardware::Return< void> _hidl_out = ::android::hidl::manager::V1_0::BpHwServiceManager::_hidl_registerPassthroughClient( this, this, fqName, name);
  3. return _hidl_out;
  4. }

   
   
  1. ::android::hardware::Return< void> BpHwServiceManager::_hidl_registerPassthroughClient(::android::hardware::IInterface *_hidl_this, ::android::hardware::details::HidlInstrumentor *_hidl_this_instrumentor, const ::android::hardware::hidl_string& fqName, const ::android::hardware::hidl_string& name) {
  2. #ifdef __ANDROID_DEBUGGABLE__
  3. bool mEnableInstrumentation = _hidl_this_instrumentor->isInstrumentationEnabled();
  4. const auto &mInstrumentationCallbacks = _hidl_this_instrumentor->getInstrumentationCallbacks();
  5. #else
  6. ( void) _hidl_this_instrumentor;
  7. #endif // __ANDROID_DEBUGGABLE__
  8. atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::registerPassthroughClient::client");
  9. #ifdef __ANDROID_DEBUGGABLE__
  10. if (UNLIKELY(mEnableInstrumentation)) {
  11. std:: vector< void *> _hidl_args;
  12. _hidl_args.push_back(( void *)&fqName);
  13. _hidl_args.push_back(( void *)&name);
  14. for ( const auto &callback: mInstrumentationCallbacks) {
  15. callback(InstrumentationEvent::CLIENT_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args);
  16. }
  17. }
  18. #endif // __ANDROID_DEBUGGABLE__
  19. ::android::hardware::Parcel _hidl_data;
  20. ::android::hardware::Parcel _hidl_reply;
  21. ::android:: status_t _hidl_err;
  22. ::android::hardware::Status _hidl_status;
  23. _hidl_err = _hidl_data.writeInterfaceToken(BpHwServiceManager::descriptor);
  24. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  25. size_t _hidl_fqName_parent;
  26. _hidl_err = _hidl_data.writeBuffer(&fqName, sizeof(fqName), &_hidl_fqName_parent);
  27. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  28. _hidl_err = ::android::hardware::writeEmbeddedToParcel(
  29. fqName,
  30. &_hidl_data,
  31. _hidl_fqName_parent,
  32. 0 /* parentOffset */);
  33. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  34. size_t _hidl_name_parent;
  35. _hidl_err = _hidl_data.writeBuffer(&name, sizeof(name), &_hidl_name_parent);
  36. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  37. _hidl_err = ::android::hardware::writeEmbeddedToParcel(
  38. name,
  39. &_hidl_data,
  40. _hidl_name_parent,
  41. 0 /* parentOffset */);
  42. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  43. _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact( 8 /* registerPassthroughClient */, _hidl_data, &_hidl_reply);
  44. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  45. _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);
  46. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  47. if (!_hidl_status.isOk()) { return _hidl_status; }
  48. atrace_end(ATRACE_TAG_HAL);
  49. #ifdef __ANDROID_DEBUGGABLE__
  50. if (UNLIKELY(mEnableInstrumentation)) {
  51. std:: vector< void *> _hidl_args;
  52. for ( const auto &callback: mInstrumentationCallbacks) {
  53. callback(InstrumentationEvent::CLIENT_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args);
  54. }
  55. }
  56. #endif // __ANDROID_DEBUGGABLE__
  57. _hidl_status.setFromStatusT(_hidl_err);
  58. return ::android::hardware::Return< void>();
  59. _hidl_error:
  60. _hidl_status.setFromStatusT(_hidl_err);
  61. return ::android::hardware::Return< void>(_hidl_status);
  62. }
这里和普通binder通信相同,先就需要传输的函数参数打包到Parcel对象中,然后调用binder代理对象的transact函数将函数参数,函数调用码发送到Server端进程,这里的_hidl_this其实指向的是BpHwServiceManager,这个是与业务相关的代理对象,通过asBinder函数得到与传输相关的binder代理,那这个binder代理是什么类型呢? 其实就是BpHwBinder,关于hwservicemanager代理对象的获取,asBinder函数的实现,在后续的章节中进行分析。经过BpHwServiceManager的请求,最终位于hwservicemanager进程中的BnHwServiceManager将接收函数调用请求:
[email protected]_genc++\gen\android\hidl\manager\1.0\ServiceManagerAll.cpp

   
   
  1. ::android:: status_t BnHwServiceManager::onTransact(
  2. uint32_t _hidl_code,
  3. const ::android::hardware::Parcel &_hidl_data,
  4. ::android::hardware::Parcel *_hidl_reply,
  5. uint32_t _hidl_flags,
  6. TransactCallback _hidl_cb) {
  7. ::android:: status_t _hidl_err = ::android::OK;
  8. switch (_hidl_code) {
  9. case 8 /* registerPassthroughClient */:
  10. {
  11. _hidl_err = ::android::hidl::manager::V1_0::BnHwServiceManager::_hidl_registerPassthroughClient( this, _hidl_data, _hidl_reply, _hidl_cb);
  12. break;
  13. }
  14. default:
  15. {
  16. return ::android::hidl::base::V1_0::BnHwBase::onTransact(
  17. _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb);
  18. }
  19. }
BnHwServiceManager将调用_hidl_registerPassthroughClient来执行Client端的注册。

   
   
  1. ::android:: status_t BnHwServiceManager::_hidl_registerPassthroughClient(
  2. ::android::hidl::base::V1_0::BnHwBase* _hidl_this,
  3. const ::android::hardware::Parcel &_hidl_data,
  4. ::android::hardware::Parcel *_hidl_reply,
  5. TransactCallback _hidl_cb) {
  6. #ifdef __ANDROID_DEBUGGABLE__
  7. bool mEnableInstrumentation = _hidl_this->isInstrumentationEnabled();
  8. const auto &mInstrumentationCallbacks = _hidl_this->getInstrumentationCallbacks();
  9. #endif // __ANDROID_DEBUGGABLE__
  10. ::android:: status_t _hidl_err = ::android::OK;
  11. if (!_hidl_data.enforceInterface(BnHwServiceManager::Pure::descriptor)) {
  12. _hidl_err = ::android::BAD_TYPE;
  13. return _hidl_err;
  14. }
  15. const ::android::hardware::hidl_string* fqName;
  16. const ::android::hardware::hidl_string* name;
  17. size_t _hidl_fqName_parent;
  18. _hidl_err = _hidl_data.readBuffer( sizeof(*fqName), &_hidl_fqName_parent, reinterpret_cast< const void **>(&fqName));
  19. if (_hidl_err != ::android::OK) { return _hidl_err; }
  20. _hidl_err = ::android::hardware::readEmbeddedFromParcel(
  21. const_cast<::android::hardware::hidl_string &>(*fqName),
  22. _hidl_data,
  23. _hidl_fqName_parent,
  24. 0 /* parentOffset */);
  25. if (_hidl_err != ::android::OK) { return _hidl_err; }
  26. size_t _hidl_name_parent;
  27. _hidl_err = _hidl_data.readBuffer( sizeof(*name), &_hidl_name_parent, reinterpret_cast< const void **>(&name));
  28. if (_hidl_err != ::android::OK) { return _hidl_err; }
  29. _hidl_err = ::android::hardware::readEmbeddedFromParcel(
  30. const_cast<::android::hardware::hidl_string &>(*name),
  31. _hidl_data,
  32. _hidl_name_parent,
  33. 0 /* parentOffset */);
  34. if (_hidl_err != ::android::OK) { return _hidl_err; }
  35. atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::registerPassthroughClient::server");
  36. #ifdef __ANDROID_DEBUGGABLE__
  37. if (UNLIKELY(mEnableInstrumentation)) {
  38. std:: vector< void *> _hidl_args;
  39. _hidl_args.push_back(( void *)fqName);
  40. _hidl_args.push_back(( void *)name);
  41. for ( const auto &callback: mInstrumentationCallbacks) {
  42. callback(InstrumentationEvent::SERVER_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args);
  43. }
  44. }
  45. #endif // __ANDROID_DEBUGGABLE__
  46. static_cast<BnHwServiceManager*>(_hidl_this)->_hidl_mImpl->registerPassthroughClient(*fqName, *name);
  47. ( void) _hidl_cb;
  48. atrace_end(ATRACE_TAG_HAL);
  49. #ifdef __ANDROID_DEBUGGABLE__
  50. if (UNLIKELY(mEnableInstrumentation)) {
  51. std:: vector< void *> _hidl_args;
  52. for ( const auto &callback: mInstrumentationCallbacks) {
  53. callback(InstrumentationEvent::SERVER_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args);
  54. }
  55. }
  56. #endif // __ANDROID_DEBUGGABLE__
  57. ::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply);
  58. return _hidl_err;
  59. }
BnHwServiceManager首先读取BpHwServiceManager发送过来的函数参数,然后将registerPassthroughClient的执行转交个其成员变量的_hidl_mImpl对象,然后将执行结果返回给BpHwServiceManager,那么_hidl_mImpl保存的是什么对象呢? 其实_hidl_mImpl指向的是ServiceManager对象,这个是在构造BnHwServiceManager对象时传入的,在后续分析hwservicemanager启动过程时,会进行详细分析。
system\hwservicemanager\ServiceManager.cpp

   
   
  1. Return< void> ServiceManager::registerPassthroughClient( const hidl_string &fqName,
  2. const hidl_string &name) {
  3. pid_t pid = IPCThreadState::self()->getCallingPid();
  4. if (!mAcl.canGet(fqName, pid)) { //根据Client端的pid及注册接口的包名,判断是否有权限注册
  5. /* We guard this function with "get", because it's typically used in
  6. * the getService() path, albeit for a passthrough service in this
  7. * case
  8. */
  9. return Void();
  10. }
  11. LOG(INFO) << "registerPassthroughClient " << fgName.c_str() << " of "
  12. << name.c_str()
  13. PackageInterfaceMap &ifaceMap = mServiceMap[fqName];
  14. if (name.empty()) {
  15. LOG(WARNING) << "registerPassthroughClient encounters empty instance name for "
  16. << fqName.c_str();
  17. return Void();
  18. }
  19. HidlService *service = ifaceMap.lookup(name);
  20. if (service == nullptr) {
  21. auto adding = std::make_unique<HidlService>(fqName, name);
  22. adding->registerPassthroughClient(pid);
  23. ifaceMap.insertService( std::move(adding));
  24. } else {
  25. service->registerPassthroughClient(pid);
  26. }
  27. return Void();
  28. }
首先根据fqName从mServiceMap中查找对应的PackageInterfaceMap,然后根据name从PackageInterfaceMap中查找HidlService,如果找不到对应的HidlService对象,那么就调用std::make_unique<HidlService>(fqName,name)创建一个新的HidlService对象,并ifaceMap.insertService(std::move(adding))添加到PackageInterfaceMap中。如果查找到了HidlService对象,那么仅仅将Client进程的pid保存到HidlService的mPassthroughClients变量中。
system\hwservicemanager\HidlService.h

   
   
  1. HidlService( const std:: string &interfaceName,
  2. const std:: string &instanceName)
  3. : HidlService(
  4. interfaceName,
  5. instanceName,
  6. nullptr,
  7. static_cast< pid_t>(IServiceManager::PidConstant::NO_PID))
  8. {}
因此registerPassthroughClient在hwservicemanager中插入一个HidlService对象而已,并没有注册对应的IBase对象。getService最后将HwcHal对象返回给registerPassthroughServiceImplementation()函数,然后再次调用registerAsService注册该IBase对象。

registerAsService注册

registerAsService用于向hwservicemanager注册IBase对象,由于前面通过PassthroughServiceManager得到的HwcHal继承于IBase,因此可以调用registerAsService函数来注册。
composer\2.1\[email protected]_genc++\gen\android\hardware\graphics\composer\2.1\ComposerAll.cpp

   
   
  1. ::android:: status_t IComposer::registerAsService( const std:: string &serviceName) {
  2. ::android::hardware::details::onRegistration( "[email protected]", "IComposer", serviceName);
  3. const ::android::sp<::android::hidl::manager::V1_0::IServiceManager> sm
  4. = ::android::hardware::defaultServiceManager();
  5. if (sm == nullptr) {
  6. return ::android::INVALID_OPERATION;
  7. }
  8. ::android::hardware::Return< bool> ret = sm->add(serviceName.c_str(), this);
  9. return ret.isOk() && ret ? ::android::OK : ::android::UNKNOWN_ERROR;
  10. }
首先执行onRegistration函数,然后调用hwservicemanager的代理对象的add函数。
system\libhidl\transport\ServiceManagement.cpp

   
   
  1. void onRegistration(const std::string &packageName,
  2. const std:: string& /* interfaceName */,
  3. const std:: string& /* instanceName */) {
  4. tryShortenProcessName(packageName);
  5. }

   
   
  1. void tryShortenProcessName(const std::string &packageName) {
  2. std:: string processName = binaryName();
  3. if (!startsWith(processName, packageName)) {
  4. return;
  5. }
  6. size_t lastDot = packageName.rfind( '.');
  7. size_t secondDot = packageName.rfind( '.', lastDot - 1);
  8. if (secondDot == std:: string::npos) {
  9. return;
  10. }
  11. std:: string newName = processName.substr(secondDot + 1,
  12. 16 /* TASK_COMM_LEN */ - 1);
  13. ALOGI( "Removing namespace from process name %s to %s.",
  14. processName.c_str(), newName.c_str());
  15. int rc = pthread_setname_np(pthread_self(), newName.c_str());
  16. ALOGI_IF(rc != 0, "Removing namespace from process name %s failed.",
  17. processName.c_str());
  18. }
这里只是简单的修改了当前进程的名称。

[email protected]_genc++\gen\android\hidl\manager\1.0\ServiceManagerAll.cpp


   
   
  1. ::android::hardware::Return< bool> BpHwServiceManager::add( const ::android::hardware::hidl_string& name, const ::android::sp<::android::hidl::base::V1_0::IBase>& service){
  2. ::android::hardware::Return< bool> _hidl_out = ::android::hidl::manager::V1_0::BpHwServiceManager::_hidl_add( this, this, name, service);
  3. return _hidl_out;
  4. }

   
   
  1. ::android::hardware::Return< bool> BpHwServiceManager::_hidl_add(::android::hardware::IInterface *_hidl_this, ::android::hardware::details::HidlInstrumentor *_hidl_this_instrumentor, const ::android::hardware::hidl_string& name, const ::android::sp<::android::hidl::base::V1_0::IBase>& service) {
  2. #ifdef __ANDROID_DEBUGGABLE__
  3. bool mEnableInstrumentation = _hidl_this_instrumentor->isInstrumentationEnabled();
  4. const auto &mInstrumentationCallbacks = _hidl_this_instrumentor->getInstrumentationCallbacks();
  5. #else
  6. ( void) _hidl_this_instrumentor;
  7. #endif // __ANDROID_DEBUGGABLE__
  8. atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::add::client");
  9. #ifdef __ANDROID_DEBUGGABLE__
  10. if (UNLIKELY(mEnableInstrumentation)) {
  11. std:: vector< void *> _hidl_args;
  12. _hidl_args.push_back(( void *)&name);
  13. _hidl_args.push_back(( void *)&service);
  14. for ( const auto &callback: mInstrumentationCallbacks) {
  15. callback(InstrumentationEvent::CLIENT_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args);
  16. }
  17. }
  18. #endif // __ANDROID_DEBUGGABLE__
  19. ::android::hardware::Parcel _hidl_data;
  20. ::android::hardware::Parcel _hidl_reply;
  21. ::android:: status_t _hidl_err;
  22. ::android::hardware::Status _hidl_status;
  23. bool _hidl_out_success;
  24. _hidl_err = _hidl_data.writeInterfaceToken(BpHwServiceManager::descriptor);
  25. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  26. size_t _hidl_name_parent;
  27. _hidl_err = _hidl_data.writeBuffer(&name, sizeof(name), &_hidl_name_parent);
  28. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  29. _hidl_err = ::android::hardware::writeEmbeddedToParcel(
  30. name,
  31. &_hidl_data,
  32. _hidl_name_parent,
  33. 0 /* parentOffset */);
  34. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  35. if (service == nullptr) {
  36. _hidl_err = _hidl_data.writeStrongBinder( nullptr);
  37. } else {
  38. ::android::sp<::android::hardware::IBinder> _hidl_binder = ::android::hardware::toBinder<
  39. ::android::hidl::base::V1_0::IBase>(service);
  40. if (_hidl_binder.get() != nullptr) {
  41. _hidl_err = _hidl_data.writeStrongBinder(_hidl_binder);
  42. } else {
  43. _hidl_err = ::android::UNKNOWN_ERROR;
  44. }
  45. }
  46. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  47. ::android::hardware::ProcessState::self()->startThreadPool();
  48. _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact( 2 /* add */, _hidl_data, &_hidl_reply);
  49. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  50. _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);
  51. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  52. if (!_hidl_status.isOk()) { return _hidl_status; }
  53. _hidl_err = _hidl_reply.readBool(&_hidl_out_success);
  54. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  55. atrace_end(ATRACE_TAG_HAL);
  56. #ifdef __ANDROID_DEBUGGABLE__
  57. if (UNLIKELY(mEnableInstrumentation)) {
  58. std:: vector< void *> _hidl_args;
  59. _hidl_args.push_back(( void *)&_hidl_out_success);
  60. for ( const auto &callback: mInstrumentationCallbacks) {
  61. callback(InstrumentationEvent::CLIENT_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args);
  62. }
  63. }
  64. #endif // __ANDROID_DEBUGGABLE__
  65. _hidl_status.setFromStatusT(_hidl_err);
  66. return ::android::hardware::Return< bool>(_hidl_out_success);
  67. _hidl_error:
  68. _hidl_status.setFromStatusT(_hidl_err);
  69. return ::android::hardware::Return< bool>(_hidl_status);
  70. }
这里的步骤和前面的registerPassthroughClient基本一致,唯一不同的是,此时需要向Server端hwservicemanager传输一个IBase对象。

   
   
  1. ::android::sp<::android::hardware::IBinder> _hidl_binder = ::android::hardware::toBinder<
  2. ::android::hidl::base::V1_0::IBase>(service);
  3. if (_hidl_binder.get() != nullptr) {
  4. _hidl_err = _hidl_data.writeStrongBinder(_hidl_binder);
  5. }
这里首先通过toBinder函数将IBase对象,其实就是HwcHal对象转换为IBinder对象,然后通过writeStrongBinder将IBinder对象序列化到Parcel中,toBinder函数在后续进行分析,我们这里只需要知道经过toBinder函数后,在Hal进程端会创建一个BnHwComposer本地binder对象,然后通过IPC调用发送给hwservicemanager。
[email protected]_genc++\gen\android\hidl\manager\1.0\ServiceManagerAll.cpp

   
   
  1. ::android:: status_t BnHwServiceManager::onTransact(
  2. uint32_t _hidl_code,
  3. const ::android::hardware::Parcel &_hidl_data,
  4. ::android::hardware::Parcel *_hidl_reply,
  5. uint32_t _hidl_flags,
  6. TransactCallback _hidl_cb) {
  7. ::android:: status_t _hidl_err = ::android::OK;
  8. switch (_hidl_code) {
  9. case 2 /* add */:
  10. {
  11. _hidl_err = ::android::hidl::manager::V1_0::BnHwServiceManager::_hidl_add( this, _hidl_data, _hidl_reply, _hidl_cb);
  12. break;
  13. }
  14. default:
  15. {
  16. return ::android::hidl::base::V1_0::BnHwBase::onTransact(
  17. _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb);
  18. }
  19. }
  20. if (_hidl_err == ::android::UNEXPECTED_NULL) {
  21. _hidl_err = ::android::hardware::writeToParcel(
  22. ::android::hardware::Status::fromExceptionCode(::android::hardware::Status::EX_NULL_POINTER),
  23. _hidl_reply);
  24. } return _hidl_err;
  25. }

   
   
  1. ::android:: status_t BnHwServiceManager::_hidl_add(
  2. ::android::hidl::base::V1_0::BnHwBase* _hidl_this,
  3. const ::android::hardware::Parcel &_hidl_data,
  4. ::android::hardware::Parcel *_hidl_reply,
  5. TransactCallback _hidl_cb) {
  6. #ifdef __ANDROID_DEBUGGABLE__
  7. bool mEnableInstrumentation = _hidl_this->isInstrumentationEnabled();
  8. const auto &mInstrumentationCallbacks = _hidl_this->getInstrumentationCallbacks();
  9. #endif // __ANDROID_DEBUGGABLE__
  10. ::android:: status_t _hidl_err = ::android::OK;
  11. if (!_hidl_data.enforceInterface(BnHwServiceManager::Pure::descriptor)) {
  12. _hidl_err = ::android::BAD_TYPE;
  13. return _hidl_err;
  14. }
  15. const ::android::hardware::hidl_string* name;
  16. ::android::sp<::android::hidl::base::V1_0::IBase> service;
  17. size_t _hidl_name_parent;
  18. _hidl_err = _hidl_data.readBuffer(sizeof(*name), &_hidl_name_parent, reinterpret_cast<const void **>(&name));
  19. if (_hidl_err != ::android::OK) { return _hidl_err; }
  20. _hidl_err = ::android::hardware::readEmbeddedFromParcel(
  21. const_cast<::android::hardware::hidl_string &>(*name),
  22. _hidl_data,
  23. _hidl_name_parent,
  24. 0 /* parentOffset */);
  25. if (_hidl_err != ::android::OK) { return _hidl_err; }
  26. {
  27. ::android::sp<::android::hardware::IBinder> _hidl_service_binder;
  28. _hidl_err = _hidl_data.readNullableStrongBinder(&_hidl_service_binder);
  29. if (_hidl_err != ::android::OK) { return _hidl_err; }
  30. service = ::android::hardware::fromBinder<::android::hidl::base::V1_0::IBase,::android::hidl::base::V1_0::BpHwBase,::android::hidl::base::V1_0::BnHwBase>(_hidl_service_binder);
  31. }
  32. atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::add::server");
  33. #ifdef __ANDROID_DEBUGGABLE__
  34. if (UNLIKELY(mEnableInstrumentation)) {
  35. std:: vector< void *> _hidl_args;
  36. _hidl_args.push_back(( void *)name);
  37. _hidl_args.push_back(( void *)&service);
  38. for ( const auto &callback: mInstrumentationCallbacks) {
  39. callback(InstrumentationEvent::SERVER_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args);
  40. }
  41. }
  42. #endif // __ANDROID_DEBUGGABLE__
  43. bool _hidl_out_success = static_cast<BnHwServiceManager*>(_hidl_this)->_hidl_mImpl->add(*name, service);
  44. ::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply);
  45. _hidl_err = _hidl_reply->writeBool(_hidl_out_success);
  46. /* _hidl_err ignored! */
  47. atrace_end(ATRACE_TAG_HAL);
  48. #ifdef __ANDROID_DEBUGGABLE__
  49. if (UNLIKELY(mEnableInstrumentation)) {
  50. std:: vector< void *> _hidl_args;
  51. _hidl_args.push_back(( void *)&_hidl_out_success);
  52. for ( const auto &callback: mInstrumentationCallbacks) {
  53. callback(InstrumentationEvent::SERVER_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args);
  54. }
  55. }
  56. #endif // __ANDROID_DEBUGGABLE__
  57. _hidl_cb(*_hidl_reply);
  58. return _hidl_err;
  59. }
hwservicemanager进程通过_hidl_err = _hidl_data.readNullableStrongBinder(&_hidl_service_binder);拿到client进程发送过来的BnHwComposer对象,binder实体到达目的端进程将变为binder代理对象,然后通过fromBinder函数将binder代理对象转换为业务代理对象BpHwBase,这个过程在后续进行详细分析,接下来继续调用_hidl_mImpl的add函数,而我们知道_hidl_mImpl其实就是ServiceManager:

system\hwservicemanager\ServiceManager.cpp

   
   
  1. Return< bool> ServiceManager::add( const hidl_string& name, const sp<IBase>& service) {
  2. bool isValidService = false;
  3. if (service == nullptr) {
  4. return false;
  5. }
  6. LOG(INFO) << "register service " << name;
  7. // TODO(b/34235311): use HIDL way to determine this
  8. // also, this assumes that the PID that is registering is the pid that is the service
  9. pid_t pid = IPCThreadState::self()->getCallingPid();
  10. auto ret = service->interfaceChain([&]( const auto &interfaceChain) {
  11. if (interfaceChain.size() == 0) {
  12. return;
  13. }
  14.         ...
  15. });
  16. if (!ret.isOk()) {
  17. LOG(ERROR) << "Failed to retrieve interface chain.";
  18. return false;
  19. }
  20. return isValidService;
  21. }
接着调用interfaceChain函数并传入一个函数回调,由于此时service是BpHwBase对象,BpHwBase的interfaceChain函数实现如下:
[email protected]_genc++\gen\android\hidl\base\1.0\BaseAll.cpp

   
   
  1. ::android::hardware::Return< void> BpHwBase::interfaceChain(interfaceChain_cb _hidl_cb){
  2. ::android::hardware::Return< void> _hidl_out = ::android::hidl::base::V1_0::BpHwBase::_hidl_interfaceChain( this, this, _hidl_cb);
  3. return _hidl_out;
  4. }

   
   
  1. ::android::hardware::Return< void> BpHwBase::_hidl_interfaceChain(::android::hardware::IInterface *_hidl_this, ::android::hardware::details::HidlInstrumentor *_hidl_this_instrumentor, interfaceChain_cb _hidl_cb) {
  2. #ifdef __ANDROID_DEBUGGABLE__
  3. bool mEnableInstrumentation = _hidl_this_instrumentor->isInstrumentationEnabled();
  4. const auto &mInstrumentationCallbacks = _hidl_this_instrumentor->getInstrumentationCallbacks();
  5. #else
  6. ( void) _hidl_this_instrumentor;
  7. #endif // __ANDROID_DEBUGGABLE__
  8. if (_hidl_cb == nullptr) {
  9. return ::android::hardware::Status::fromExceptionCode(
  10. ::android::hardware::Status::EX_ILLEGAL_ARGUMENT,
  11. "Null synchronous callback passed.");
  12. }
  13. atrace_begin(ATRACE_TAG_HAL, "HIDL::IBase::interfaceChain::client");
  14. #ifdef __ANDROID_DEBUGGABLE__
  15. if (UNLIKELY(mEnableInstrumentation)) {
  16. std:: vector< void *> _hidl_args;
  17. for ( const auto &callback: mInstrumentationCallbacks) {
  18. callback(InstrumentationEvent::CLIENT_API_ENTRY, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args);
  19. }
  20. }
  21. #endif // __ANDROID_DEBUGGABLE__
  22. ::android::hardware::Parcel _hidl_data;
  23. ::android::hardware::Parcel _hidl_reply;
  24. ::android:: status_t _hidl_err;
  25. ::android::hardware::Status _hidl_status;
  26. const ::android::hardware::hidl_vec<::android::hardware::hidl_string>* _hidl_out_descriptors;
  27. _hidl_err = _hidl_data.writeInterfaceToken(BpHwBase::descriptor);
  28. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  29. _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact( 256067662 /* interfaceChain */, _hidl_data, &_hidl_reply);
  30. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  31. _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);
  32. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  33. if (!_hidl_status.isOk()) { return _hidl_status; }
  34. size_t _hidl__hidl_out_descriptors_parent;
  35. _hidl_err = _hidl_reply.readBuffer( sizeof(*_hidl_out_descriptors), &_hidl__hidl_out_descriptors_parent, reinterpret_cast< const void **>(&_hidl_out_descriptors));
  36. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  37. size_t _hidl__hidl_out_descriptors_child;
  38. _hidl_err = ::android::hardware::readEmbeddedFromParcel(
  39. const_cast<::android::hardware::hidl_vec<::android::hardware::hidl_string> &>(*_hidl_out_descriptors),
  40. _hidl_reply,
  41. _hidl__hidl_out_descriptors_parent,
  42. 0 /* parentOffset */, &_hidl__hidl_out_descriptors_child);
  43. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  44. for ( size_t _hidl_index_0 = 0; _hidl_index_0 < _hidl_out_descriptors->size(); ++_hidl_index_0) {
  45. _hidl_err = ::android::hardware::readEmbeddedFromParcel(
  46. const_cast<::android::hardware::hidl_string &>((*_hidl_out_descriptors)[_hidl_index_0]),
  47. _hidl_reply,
  48. _hidl__hidl_out_descriptors_child,
  49. _hidl_index_0 * sizeof(::android::hardware::hidl_string));
  50. if (_hidl_err != ::android::OK) { goto _hidl_error; }
  51. }
  52. _hidl_cb(*_hidl_out_descriptors);
  53. atrace_end(ATRACE_TAG_HAL);
  54. #ifdef __ANDROID_DEBUGGABLE__
  55. if (UNLIKELY(mEnableInstrumentation)) {
  56. std:: vector< void *> _hidl_args;
  57. _hidl_args.push_back(( void *)_hidl_out_descriptors);
  58. for ( const auto &callback: mInstrumentationCallbacks) {
  59. callback(InstrumentationEvent::CLIENT_API_EXIT, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args);
  60. }
  61. }
  62. #endif // __ANDROID_DEBUGGABLE__
  63. _hidl_status.setFromStatusT(_hidl_err);
  64. return ::android::hardware::Return< void>();
  65. _hidl_error:
  66. _hidl_status.setFromStatusT(_hidl_err);
  67. return ::android::hardware::Return< void>(_hidl_status);
  68. }
这里再次回到Hal进程空间,调用BnHwComposer的interfaceChain函数查询_hidl_out_descriptors,

然后调用传递进来的回调函数_hidl_cb。因此BnHwComposer的onTransact将接收请求:
composer\2.1\[email protected]_genc++\gen\android\hardware\graphics\composer\2.1\ComposerAll.cpp

   
   
  1. ::android:: status_t BnHwComposer::onTransact(
  2. uint32_t _hidl_code,
  3. const ::android::hardware::Parcel &_hidl_data,
  4. ::android::hardware::Parcel *_hidl_reply,
  5. uint32_t _hidl_flags,
  6. TransactCallback _hidl_cb) {
  7. ::android:: status_t _hidl_err = ::android::OK;
  8. switch (_hidl_code) {
  9. case 256067662 /* interfaceChain */:
  10. {
  11. _hidl_err = ::android::hidl::base::V1_0::BnHwBase::_hidl_interfaceChain( this, _hidl_data, _hidl_reply, _hidl_cb);
  12. break;
  13. }
  14. default:
  15. {
  16. return ::android::hidl::base::V1_0::BnHwBase::onTransact(
  17. _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb);
  18. }
  19. }
  20. if (_hidl_err == ::android::UNEXPECTED_NULL) {
  21. _hidl_err = ::android::hardware::writeToParcel(
  22. ::android::hardware::Status::fromExceptionCode(::android::hardware::Status::EX_NULL_POINTER),
  23. _hidl_reply);
  24. } return _hidl_err;
  25. }
注意,onTransact的最后一个参数是一个回调函数,是由IPCThreadState传递进来的,该回调函数将传入BnHwBase的interfaceChain中执行。这个实现由其父类BnHwBase来完成:
[email protected]_genc++\gen\android\hidl\base\1.0\BaseAll.cpp

   
   
  1. ::android:: status_t BnHwBase::_hidl_interfaceChain(
  2. BnHwBase* _hidl_this,
  3. const ::android::hardware::Parcel &_hidl_data,
  4. ::android::hardware::Parcel *_hidl_reply,
  5. TransactCallback _hidl_cb) {
  6. #ifdef __ANDROID_DEBUGGABLE__
  7. bool mEnableInstrumentation = _hidl_this->isInstrumentationEnabled();
  8. const auto &mInstrumentationCallbacks = _hidl_this->getInstrumentationCallbacks();
  9. #endif // __ANDROID_DEBUGGABLE__
  10. ::android:: status_t _hidl_err = ::android::OK;
  11. if (!_hidl_data.enforceInterface(BnHwBase::Pure::descriptor)) {
  12. _hidl_err = ::android::BAD_TYPE;
  13. return _hidl_err;
  14. }
  15. atrace_begin(ATRACE_TAG_HAL, "HIDL::IBase::interfaceChain::server");
  16. #ifdef __ANDROID_DEBUGGABLE__
  17. if (UNLIKELY(mEnableInstrumentation)) {
  18. std:: vector< void *> _hidl_args;
  19. for ( const auto &callback: mInstrumentationCallbacks) {
  20. callback(InstrumentationEvent::SERVER_API_ENTRY, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args);
  21. }
  22. }
  23. #endif // __ANDROID_DEBUGGABLE__

猜你喜欢

转载自blog.csdn.net/vzvzvxz/article/details/83214462