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

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

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

hardware/interfaces/graphics/composer/2.1/default/android.hardware.graphics.composer@2.1-service.rc

 
  1. service hwcomposer-2-1 /vendor/bin/hw/android.hardware.graphics.composer@2.1-service

  2. class hal animation

  3. user system

  4. group graphics drmrpc

  5. capabilities SYS_NICE

  6. onrestart restart surfaceflinger

编译后,会将该脚本文件copy到vendor/etc/init目录,在开机时,init进程会读取并解析这个脚本,然后启动android.hardware.graphics.composer@2.1-service进程:

system         661     1   32288   7832 0                   0 S android.hardware.graphics.composer@2.1-service

该进程的可执行文件是:vendor/bin/hw/android.hardware.graphics.composer@2.1-service,

该可执行文件对应的源码为: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.  
  7. // same as SF main thread

  8. struct sched_param param = {0};

  9. param.sched_priority = 2;

  10. if (sched_setscheduler(0, SCHED_FIFO | SCHED_RESET_ON_FORK,

  11. ¶m) != 0) {

  12. ALOGE("Couldn't set SCHED_FIFO: %d", errno);

  13. }

  14.  
  15. return defaultPassthroughServiceImplementation<IComposer>(4);

  16. }

前面我们分析了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.  
  8. if (result != OK) {

  9. return result;

  10. }

  11.  
  12. joinRpcThreadpool();

  13. return 0;

  14. }

 
  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.  
  7. if (service == nullptr) {

  8. ALOGE("Could not get passthrough implementation for %s/%s.",

  9. Interface::descriptor, name.c_str());

  10. return EXIT_FAILURE;

  11. }

  12.  
  13. LOG_FATAL_IF(service->isRemote(), "Implementation of %s/%s is remote!",

  14. Interface::descriptor, name.c_str());

  15.  
  16. status_t status = service->registerAsService(name);//将IComposer注册到hwservicemanager中

  17.  
  18. if (status == OK) {

  19. ALOGI("Registration complete for %s/%s.",

  20. Interface::descriptor, name.c_str());

  21. } else {

  22. ALOGE("Could not register service %s/%s (%d).",

  23. Interface::descriptor, name.c_str(), status);

  24. }

  25.  
  26. return status;

  27. }

Hal进程获取IComposer类对象

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

composer\2.1\android.hardware.graphics.composer@2.1_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.  
  9. sp<IComposer> iface = nullptr;

  10.  
  11. const sp<::android::hidl::manager::V1_0::IServiceManager> sm = defaultServiceManager(); //获取hwservicemanager的代理

  12. if (sm == nullptr) {

  13. ALOGE("getService: defaultServiceManager() is null");

  14. return nullptr;

  15. }

  16.  
  17. Return<Transport> transportRet = sm->getTransport(IComposer::descriptor, serviceName);//查询IComposer的Transport

  18. if (!transportRet.isOk()) {

  19. ALOGE("getService: defaultServiceManager()->getTransport returns %s", transportRet.description().c_str());

  20. return nullptr;

  21. }

  22. Transport transport = transportRet;

  23. const bool vintfHwbinder = (transport == Transport::HWBINDER);

  24. const bool vintfPassthru = (transport == Transport::PASSTHROUGH); //Transport类型判断

  25. #ifdef __ANDROID_TREBLE__

  26.  
  27. #ifdef __ANDROID_DEBUGGABLE__

  28. const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");

  29. const bool trebleTestingOverride = env && !strcmp(env, "true");

  30. const bool vintfLegacy = (transport == Transport::EMPTY) && trebleTestingOverride;

  31. #else // __ANDROID_TREBLE__ but not __ANDROID_DEBUGGABLE__

  32. const bool trebleTestingOverride = false;

  33. const bool vintfLegacy = false;

  34. #endif // __ANDROID_DEBUGGABLE__

  35.  
  36. #else // not __ANDROID_TREBLE__

  37. const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");

  38. const bool trebleTestingOverride = env && !strcmp(env, "true");

  39. const bool vintfLegacy = (transport == Transport::EMPTY);

  40.  
  41. #endif // __ANDROID_TREBLE__

  42.     //hwbinder方式下获取IComposer对象

  43. for (int tries = 0; !getStub && (vintfHwbinder || (vintfLegacy && tries == 0)); tries++) {

  44. if (tries > 1) {

  45. ALOGI("getService: Will do try %d for %s/%s in 1s...", tries, IComposer::descriptor, serviceName.c_str());

  46. sleep(1);

  47. }

  48. if (vintfHwbinder && tries > 0) {

  49. waitForHwService(IComposer::descriptor, serviceName);

  50. }

  51. Return<sp<::android::hidl::base::V1_0::IBase>> ret =

  52. sm->get(IComposer::descriptor, serviceName);

  53. if (!ret.isOk()) {

  54. ALOGE("IComposer: defaultServiceManager()->get returns %s", ret.description().c_str());

  55. break;

  56. }

  57. sp<::android::hidl::base::V1_0::IBase> base = ret;

  58. if (base == nullptr) {

  59. if (tries > 0) {

  60. ALOGW("IComposer: found null hwbinder interface");

  61. }continue;

  62. }

  63. Return<sp<IComposer>> castRet = IComposer::castFrom(base, true /* emitError */);

  64. if (!castRet.isOk()) {

  65. if (castRet.isDeadObject()) {

  66. ALOGW("IComposer: found dead hwbinder service");

  67. continue;

  68. } else {

  69. ALOGW("IComposer: cannot call into hwbinder service: %s; No permission? Check for selinux denials.", castRet.description().c_str());

  70. break;

  71. }

  72. }

  73. iface = castRet;

  74. if (iface == nullptr) {

  75. ALOGW("IComposer: received incompatible service; bug in hwservicemanager?");

  76. break;

  77. }

  78. return iface;

  79. }

  80. //passthrough方式下获取IComposer对象

  81.     if (getStub || vintfPassthru || vintfLegacy) {

  82.         const sp<::android::hidl::manager::V1_0::IServiceManager> pm = getPassthroughServiceManager();

  83.         if (pm != nullptr) {

  84.             Return<sp<::android::hidl::base::V1_0::IBase>> ret =

  85.                     pm->get(IComposer::descriptor, serviceName);

  86.             if (ret.isOk()) {

  87.                 sp<::android::hidl::base::V1_0::IBase> baseInterface = ret;

  88.                 if (baseInterface != nullptr) {

  89.                     iface = IComposer::castFrom(baseInterface);

  90.                     if (!getStub || trebleTestingOverride) {

  91.                         iface = new BsComposer(iface);

  92.                     }

  93.                 }

  94.             }

  95.         }

  96.     }

  97.     return iface;

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

manifest.xml文件的读取和解析都是由hwservicemanager来完成的,此时android.hardware.graphics.composer@2.1-service作为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.  
  5. //fqName looks like android.hardware.foo@1.0::IFoo

  6. size_t idx = stdFqName.find("::");

  7.  
  8. if (idx == std::string::npos ||

  9. idx + strlen("::") + 1 >= stdFqName.size()) {

  10. LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;

  11. return nullptr;

  12. }

  13.  
  14. std::string packageAndVersion = stdFqName.substr(0, idx);

  15. std::string ifaceName = stdFqName.substr(idx + strlen("::"));

  16.  
  17. const std::string prefix = packageAndVersion + "-impl";

  18. const std::string sym = "HIDL_FETCH_" + ifaceName;

  19.  
  20. const android_namespace_t* sphal_namespace = android_get_exported_namespace("sphal");

  21. const int dlMode = RTLD_LAZY;

  22. void *handle = nullptr;

  23.  
  24. // TODO: lookup in VINTF instead

  25. // TODO(b/34135607): Remove HAL_LIBRARY_PATH_SYSTEM

  26.  
  27. dlerror(); // clear

  28.  
  29. for (const std::string &path : {

  30. HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, HAL_LIBRARY_PATH_SYSTEM

  31. }) {

  32. std::vector<std::string> libs = search(path, prefix, ".so");

  33.  
  34. for (const std::string &lib : libs) {

  35. const std::string fullPath = path + lib;

  36.  
  37. // If sphal namespace is available, try to load from the

  38. // namespace first. If it fails, fall back to the original

  39. // dlopen, which loads from the current namespace.

  40. if (sphal_namespace != nullptr && path != HAL_LIBRARY_PATH_SYSTEM) {

  41. const android_dlextinfo dlextinfo = {

  42. .flags = ANDROID_DLEXT_USE_NAMESPACE,

  43. // const_cast is dirty but required because

  44. // library_namespace field is non-const.

  45. .library_namespace = const_cast<android_namespace_t*>(sphal_namespace),

  46. };

  47. handle = android_dlopen_ext(fullPath.c_str(), dlMode, &dlextinfo);

  48. if (handle == nullptr) {

  49. const char* error = dlerror();

  50. LOG(WARNING) << "Failed to dlopen " << lib << " from sphal namespace:"

  51. << (error == nullptr ? "unknown error" : error);

  52. } else {

  53. LOG(DEBUG) << lib << " loaded from sphal namespace.";

  54. }

  55. }

  56. if (handle == nullptr) {

  57. handle = dlopen(fullPath.c_str(), dlMode);

  58. }

  59.  
  60. if (handle == nullptr) {

  61. const char* error = dlerror();

  62. LOG(ERROR) << "Failed to dlopen " << lib << ": "

  63. << (error == nullptr ? "unknown error" : error);

  64. continue;

  65. }

  66.  
  67. IBase* (*generator)(const char* name);

  68. *(void **)(&generator) = dlsym(handle, sym.c_str());

  69. if(!generator) {

  70. const char* error = dlerror();

  71. LOG(ERROR) << "Passthrough lookup opened " << lib

  72. << " but could not find symbol " << sym << ": "

  73. << (error == nullptr ? "unknown error" : error);

  74. dlclose(handle);

  75. continue;

  76. }

  77.  
  78. IBase *interface = (*generator)(name.c_str());

  79.  
  80. if (interface == nullptr) {

  81. dlclose(handle);

  82. continue; // this module doesn't provide this instance name

  83. }

  84.  
  85. registerReference(fqName, name);

  86.  
  87. return interface;

  88. }

  89. }

  90.  
  91. return nullptr;

  92. }

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

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

 
  1. cc_library_shared {

  2. name: "android.hardware.graphics.composer@2.1-impl",

  3. defaults: ["hidl_defaults"],

  4. proprietary: true,

  5. relative_install_path: "hw",

  6. srcs: ["Hwc.cpp"],

  7. static_libs: ["libhwcomposer-client"],

  8. shared_libs: [

  9. "android.hardware.graphics.composer@2.1",

  10. "android.hardware.graphics.mapper@2.0",

  11. "libbase",

  12. "libcutils",

  13. "libfmq",

  14. "libhardware",

  15. "libhidlbase",

  16. "libhidltransport",

  17. "liblog",

  18. "libsync",

  19. "libutils",

  20. "libhwc2on1adapter"

  21. ],

  22. }

从上面的编译脚本可知,android.hardware.graphics.composer@2.1-impl.so的源码文件为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.  
  10. return new HwcHal(module);

  11. }

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。

android.hidl.manager@1.0_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.  
  4. return _hidl_out;

  5. }

 
  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.  
  20. ::android::hardware::Parcel _hidl_data;

  21. ::android::hardware::Parcel _hidl_reply;

  22. ::android::status_t _hidl_err;

  23. ::android::hardware::Status _hidl_status;

  24.  
  25. _hidl_err = _hidl_data.writeInterfaceToken(BpHwServiceManager::descriptor);

  26. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  27.  
  28. size_t _hidl_fqName_parent;

  29.  
  30. _hidl_err = _hidl_data.writeBuffer(&fqName, sizeof(fqName), &_hidl_fqName_parent);

  31. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  32.  
  33. _hidl_err = ::android::hardware::writeEmbeddedToParcel(

  34. fqName,

  35. &_hidl_data,

  36. _hidl_fqName_parent,

  37. 0 /* parentOffset */);

  38.  
  39. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  40.  
  41. size_t _hidl_name_parent;

  42.  
  43. _hidl_err = _hidl_data.writeBuffer(&name, sizeof(name), &_hidl_name_parent);

  44. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  45.  
  46. _hidl_err = ::android::hardware::writeEmbeddedToParcel(

  47. name,

  48. &_hidl_data,

  49. _hidl_name_parent,

  50. 0 /* parentOffset */);

  51.  
  52. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  53.  
  54. _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact(8 /* registerPassthroughClient */, _hidl_data, &_hidl_reply);

  55. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  56.  
  57. _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);

  58. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  59.  
  60. if (!_hidl_status.isOk()) { return _hidl_status; }

  61.  
  62. atrace_end(ATRACE_TAG_HAL);

  63. #ifdef __ANDROID_DEBUGGABLE__

  64. if (UNLIKELY(mEnableInstrumentation)) {

  65. std::vector<void *> _hidl_args;

  66. for (const auto &callback: mInstrumentationCallbacks) {

  67. callback(InstrumentationEvent::CLIENT_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args);

  68. }

  69. }

  70. #endif // __ANDROID_DEBUGGABLE__

  71.  
  72. _hidl_status.setFromStatusT(_hidl_err);

  73. return ::android::hardware::Return<void>();

  74.  
  75. _hidl_error:

  76. _hidl_status.setFromStatusT(_hidl_err);

  77. return ::android::hardware::Return<void>(_hidl_status);

  78. }

这里和普通binder通信相同,先就需要传输的函数参数打包到Parcel对象中,然后调用binder代理对象的transact函数将函数参数,函数调用码发送到Server端进程,这里的_hidl_this其实指向的是BpHwServiceManager,这个是与业务相关的代理对象,通过asBinder函数得到与传输相关的binder代理,那这个binder代理是什么类型呢? 其实就是BpHwBinder,关于hwservicemanager代理对象的获取,asBinder函数的实现,在后续的章节中进行分析。经过BpHwServiceManager的请求,最终位于hwservicemanager进程中的BnHwServiceManager将接收函数调用请求:

android.hidl.manager@1.0_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.  
  9. switch (_hidl_code) {

  10. case 8 /* registerPassthroughClient */:

  11. {

  12. _hidl_err = ::android::hidl::manager::V1_0::BnHwServiceManager::_hidl_registerPassthroughClient(this, _hidl_data, _hidl_reply, _hidl_cb);

  13. break;

  14. }

  15. default:

  16. {

  17. return ::android::hidl::base::V1_0::BnHwBase::onTransact(

  18. _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb);

  19. }

  20. }

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.  
  11. ::android::status_t _hidl_err = ::android::OK;

  12. if (!_hidl_data.enforceInterface(BnHwServiceManager::Pure::descriptor)) {

  13. _hidl_err = ::android::BAD_TYPE;

  14. return _hidl_err;

  15. }

  16.  
  17. const ::android::hardware::hidl_string* fqName;

  18. const ::android::hardware::hidl_string* name;

  19.  
  20. size_t _hidl_fqName_parent;

  21.  
  22. _hidl_err = _hidl_data.readBuffer(sizeof(*fqName), &_hidl_fqName_parent, reinterpret_cast<const void **>(&fqName));

  23.  
  24. if (_hidl_err != ::android::OK) { return _hidl_err; }

  25.  
  26. _hidl_err = ::android::hardware::readEmbeddedFromParcel(

  27. const_cast<::android::hardware::hidl_string &>(*fqName),

  28. _hidl_data,

  29. _hidl_fqName_parent,

  30. 0 /* parentOffset */);

  31.  
  32. if (_hidl_err != ::android::OK) { return _hidl_err; }

  33.  
  34. size_t _hidl_name_parent;

  35.  
  36. _hidl_err = _hidl_data.readBuffer(sizeof(*name), &_hidl_name_parent, reinterpret_cast<const void **>(&name));

  37.  
  38. if (_hidl_err != ::android::OK) { return _hidl_err; }

  39.  
  40. _hidl_err = ::android::hardware::readEmbeddedFromParcel(

  41. const_cast<::android::hardware::hidl_string &>(*name),

  42. _hidl_data,

  43. _hidl_name_parent,

  44. 0 /* parentOffset */);

  45.  
  46. if (_hidl_err != ::android::OK) { return _hidl_err; }

  47.  
  48. atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::registerPassthroughClient::server");

  49. #ifdef __ANDROID_DEBUGGABLE__

  50. if (UNLIKELY(mEnableInstrumentation)) {

  51. std::vector<void *> _hidl_args;

  52. _hidl_args.push_back((void *)fqName);

  53. _hidl_args.push_back((void *)name);

  54. for (const auto &callback: mInstrumentationCallbacks) {

  55. callback(InstrumentationEvent::SERVER_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args);

  56. }

  57. }

  58. #endif // __ANDROID_DEBUGGABLE__

  59.  
  60. static_cast<BnHwServiceManager*>(_hidl_this)->_hidl_mImpl->registerPassthroughClient(*fqName, *name);

  61.  
  62. (void) _hidl_cb;

  63.  
  64. atrace_end(ATRACE_TAG_HAL);

  65. #ifdef __ANDROID_DEBUGGABLE__

  66. if (UNLIKELY(mEnableInstrumentation)) {

  67. std::vector<void *> _hidl_args;

  68. for (const auto &callback: mInstrumentationCallbacks) {

  69. callback(InstrumentationEvent::SERVER_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args);

  70. }

  71. }

  72. #endif // __ANDROID_DEBUGGABLE__

  73.  
  74. ::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply);

  75.  
  76. return _hidl_err;

  77. }

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.  
  14. PackageInterfaceMap &ifaceMap = mServiceMap[fqName];

  15.  
  16. if (name.empty()) {

  17. LOG(WARNING) << "registerPassthroughClient encounters empty instance name for "

  18. << fqName.c_str();

  19. return Void();

  20. }

  21.  
  22. HidlService *service = ifaceMap.lookup(name);

  23.  
  24. if (service == nullptr) {

  25. auto adding = std::make_unique<HidlService>(fqName, name);

  26. adding->registerPassthroughClient(pid);

  27. ifaceMap.insertService(std::move(adding));

  28. } else {

  29. service->registerPassthroughClient(pid);

  30. }

  31. return Void();

  32. }

首先根据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\android.hardware.graphics.composer@2.1_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("android.hardware.graphics.composer@2.1", "IComposer", serviceName);

  3.  
  4. const ::android::sp<::android::hidl::manager::V1_0::IServiceManager> sm

  5. = ::android::hardware::defaultServiceManager();

  6. if (sm == nullptr) {

  7. return ::android::INVALID_OPERATION;

  8. }

  9. ::android::hardware::Return<bool> ret = sm->add(serviceName.c_str(), this);

  10. return ret.isOk() && ret ? ::android::OK : ::android::UNKNOWN_ERROR;

  11. }

首先执行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.  
  4. if (!startsWith(processName, packageName)) {

  5. return;

  6. }

  7.  
  8. // e.x. android.hardware.module.foo@1.0 -> foo@1.0

  9. size_t lastDot = packageName.rfind('.');

  10. size_t secondDot = packageName.rfind('.', lastDot - 1);

  11.  
  12. if (secondDot == std::string::npos) {

  13. return;

  14. }

  15.  
  16. std::string newName = processName.substr(secondDot + 1,

  17. 16 /* TASK_COMM_LEN */ - 1);

  18. ALOGI("Removing namespace from process name %s to %s.",

  19. processName.c_str(), newName.c_str());

  20.  
  21. int rc = pthread_setname_np(pthread_self(), newName.c_str());

  22. ALOGI_IF(rc != 0, "Removing namespace from process name %s failed.",

  23. processName.c_str());

  24. }

这里只是简单的修改了当前进程的名称。

android.hidl.manager@1.0_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.  
  4. return _hidl_out;

  5. }

 
  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.  
  20. ::android::hardware::Parcel _hidl_data;

  21. ::android::hardware::Parcel _hidl_reply;

  22. ::android::status_t _hidl_err;

  23. ::android::hardware::Status _hidl_status;

  24.  
  25. bool _hidl_out_success;

  26.  
  27. _hidl_err = _hidl_data.writeInterfaceToken(BpHwServiceManager::descriptor);

  28. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  29.  
  30. size_t _hidl_name_parent;

  31.  
  32. _hidl_err = _hidl_data.writeBuffer(&name, sizeof(name), &_hidl_name_parent);

  33. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  34.  
  35. _hidl_err = ::android::hardware::writeEmbeddedToParcel(

  36. name,

  37. &_hidl_data,

  38. _hidl_name_parent,

  39. 0 /* parentOffset */);

  40.  
  41. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  42.  
  43. if (service == nullptr) {

  44. _hidl_err = _hidl_data.writeStrongBinder(nullptr);

  45. } else {

  46. ::android::sp<::android::hardware::IBinder> _hidl_binder = ::android::hardware::toBinder<

  47. ::android::hidl::base::V1_0::IBase>(service);

  48. if (_hidl_binder.get() != nullptr) {

  49. _hidl_err = _hidl_data.writeStrongBinder(_hidl_binder);

  50. } else {

  51. _hidl_err = ::android::UNKNOWN_ERROR;

  52. }

  53. }

  54. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  55.  
  56. ::android::hardware::ProcessState::self()->startThreadPool();

  57. _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact(2 /* add */, _hidl_data, &_hidl_reply);

  58. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  59.  
  60. _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);

  61. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  62.  
  63. if (!_hidl_status.isOk()) { return _hidl_status; }

  64.  
  65. _hidl_err = _hidl_reply.readBool(&_hidl_out_success);

  66. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  67.  
  68. atrace_end(ATRACE_TAG_HAL);

  69. #ifdef __ANDROID_DEBUGGABLE__

  70. if (UNLIKELY(mEnableInstrumentation)) {

  71. std::vector<void *> _hidl_args;

  72. _hidl_args.push_back((void *)&_hidl_out_success);

  73. for (const auto &callback: mInstrumentationCallbacks) {

  74. callback(InstrumentationEvent::CLIENT_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args);

  75. }

  76. }

  77. #endif // __ANDROID_DEBUGGABLE__

  78.  
  79. _hidl_status.setFromStatusT(_hidl_err);

  80. return ::android::hardware::Return<bool>(_hidl_out_success);

  81.  
  82. _hidl_error:

  83. _hidl_status.setFromStatusT(_hidl_err);

  84. return ::android::hardware::Return<bool>(_hidl_status);

  85. }

这里的步骤和前面的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。

android.hidl.manager@1.0_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.  
  11. ::android::status_t _hidl_err = ::android::OK;

  12. if (!_hidl_data.enforceInterface(BnHwServiceManager::Pure::descriptor)) {

  13. _hidl_err = ::android::BAD_TYPE;

  14. return _hidl_err;

  15. }

  16.  
  17. const ::android::hardware::hidl_string* name;

  18. ::android::sp<::android::hidl::base::V1_0::IBase> service;

  19.  
  20. size_t _hidl_name_parent;

  21.  
  22. _hidl_err = _hidl_data.readBuffer(sizeof(*name), &_hidl_name_parent, reinterpret_cast<const void **>(&name));

  23.  
  24. if (_hidl_err != ::android::OK) { return _hidl_err; }

  25.  
  26. _hidl_err = ::android::hardware::readEmbeddedFromParcel(

  27. const_cast<::android::hardware::hidl_string &>(*name),

  28. _hidl_data,

  29. _hidl_name_parent,

  30. 0 /* parentOffset */);

  31.  
  32. if (_hidl_err != ::android::OK) { return _hidl_err; }

  33.  
  34. {

  35. ::android::sp<::android::hardware::IBinder> _hidl_service_binder;

  36. _hidl_err = _hidl_data.readNullableStrongBinder(&_hidl_service_binder);

  37. if (_hidl_err != ::android::OK) { return _hidl_err; }

  38.  
  39. 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);

  40. }

  41.  
  42. atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::add::server");

  43. #ifdef __ANDROID_DEBUGGABLE__

  44. if (UNLIKELY(mEnableInstrumentation)) {

  45. std::vector<void *> _hidl_args;

  46. _hidl_args.push_back((void *)name);

  47. _hidl_args.push_back((void *)&service);

  48. for (const auto &callback: mInstrumentationCallbacks) {

  49. callback(InstrumentationEvent::SERVER_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args);

  50. }

  51. }

  52. #endif // __ANDROID_DEBUGGABLE__

  53.  
  54. bool _hidl_out_success = static_cast<BnHwServiceManager*>(_hidl_this)->_hidl_mImpl->add(*name, service);

  55.  
  56. ::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply);

  57.  
  58. _hidl_err = _hidl_reply->writeBool(_hidl_out_success);

  59. /* _hidl_err ignored! */

  60.  
  61. atrace_end(ATRACE_TAG_HAL);

  62. #ifdef __ANDROID_DEBUGGABLE__

  63. if (UNLIKELY(mEnableInstrumentation)) {

  64. std::vector<void *> _hidl_args;

  65. _hidl_args.push_back((void *)&_hidl_out_success);

  66. for (const auto &callback: mInstrumentationCallbacks) {

  67. callback(InstrumentationEvent::SERVER_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args);

  68. }

  69. }

  70. #endif // __ANDROID_DEBUGGABLE__

  71.  
  72. _hidl_cb(*_hidl_reply);

  73. return _hidl_err;

  74. }

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.  
  4. if (service == nullptr) {

  5. return false;

  6. }

  7. LOG(INFO) << "register service " << name;

  8.  
  9. // TODO(b/34235311): use HIDL way to determine this

  10. // also, this assumes that the PID that is registering is the pid that is the service

  11. pid_t pid = IPCThreadState::self()->getCallingPid();

  12.  
  13. auto ret = service->interfaceChain([&](const auto &interfaceChain) {

  14. if (interfaceChain.size() == 0) {

  15. return;

  16. }

  17.         ...

  18. });

  19.  
  20. if (!ret.isOk()) {

  21. LOG(ERROR) << "Failed to retrieve interface chain.";

  22. return false;

  23. }

  24.  
  25. return isValidService;

  26. }

接着调用interfaceChain函数并传入一个函数回调,由于此时service是BpHwBase对象,BpHwBase的interfaceChain函数实现如下:

android.hidl.base@1.0_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.  
  4. return _hidl_out;

  5. }

 
  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.  
  14. atrace_begin(ATRACE_TAG_HAL, "HIDL::IBase::interfaceChain::client");

  15. #ifdef __ANDROID_DEBUGGABLE__

  16. if (UNLIKELY(mEnableInstrumentation)) {

  17. std::vector<void *> _hidl_args;

  18. for (const auto &callback: mInstrumentationCallbacks) {

  19. callback(InstrumentationEvent::CLIENT_API_ENTRY, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args);

  20. }

  21. }

  22. #endif // __ANDROID_DEBUGGABLE__

  23.  
  24. ::android::hardware::Parcel _hidl_data;

  25. ::android::hardware::Parcel _hidl_reply;

  26. ::android::status_t _hidl_err;

  27. ::android::hardware::Status _hidl_status;

  28.  
  29. const ::android::hardware::hidl_vec<::android::hardware::hidl_string>* _hidl_out_descriptors;

  30.  
  31. _hidl_err = _hidl_data.writeInterfaceToken(BpHwBase::descriptor);

  32. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  33.  
  34. _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact(256067662 /* interfaceChain */, _hidl_data, &_hidl_reply);

  35. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  36.  
  37. _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);

  38. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  39.  
  40. if (!_hidl_status.isOk()) { return _hidl_status; }

  41.  
  42. size_t _hidl__hidl_out_descriptors_parent;

  43.  
  44. _hidl_err = _hidl_reply.readBuffer(sizeof(*_hidl_out_descriptors), &_hidl__hidl_out_descriptors_parent, reinterpret_cast<const void **>(&_hidl_out_descriptors));

  45.  
  46. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  47.  
  48. size_t _hidl__hidl_out_descriptors_child;

  49.  
  50. _hidl_err = ::android::hardware::readEmbeddedFromParcel(

  51. const_cast<::android::hardware::hidl_vec<::android::hardware::hidl_string> &>(*_hidl_out_descriptors),

  52. _hidl_reply,

  53. _hidl__hidl_out_descriptors_parent,

  54. 0 /* parentOffset */, &_hidl__hidl_out_descriptors_child);

  55.  
  56. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  57.  
  58. for (size_t _hidl_index_0 = 0; _hidl_index_0 < _hidl_out_descriptors->size(); ++_hidl_index_0) {

  59. _hidl_err = ::android::hardware::readEmbeddedFromParcel(

  60. const_cast<::android::hardware::hidl_string &>((*_hidl_out_descriptors)[_hidl_index_0]),

  61. _hidl_reply,

  62. _hidl__hidl_out_descriptors_child,

  63. _hidl_index_0 * sizeof(::android::hardware::hidl_string));

  64.  
  65. if (_hidl_err != ::android::OK) { goto _hidl_error; }

  66.  
  67. }

  68.  
  69. _hidl_cb(*_hidl_out_descriptors);

  70.  
  71. atrace_end(ATRACE_TAG_HAL);

  72. #ifdef __ANDROID_DEBUGGABLE__

  73. if (UNLIKELY(mEnableInstrumentation)) {

  74. std::vector<void *> _hidl_args;

  75. _hidl_args.push_back((void *)_hidl_out_descriptors);

  76. for (const auto &callback: mInstrumentationCallbacks) {

  77. callback(InstrumentationEvent::CLIENT_API_EXIT, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args);

  78. }

  79. }

  80. #endif // __ANDROID_DEBUGGABLE__

  81.  
  82. _hidl_status.setFromStatusT(_hidl_err);

  83. return ::android::hardware::Return<void>();

  84.  
  85. _hidl_error:

  86. _hidl_status.setFromStatusT(_hidl_err);

  87. return ::android::hardware::Return<void>(_hidl_status);

  88. }

这里再次回到Hal进程空间,调用BnHwComposer的interfaceChain函数查询_hidl_out_descriptors,

然后调用传递进来的回调函数_hidl_cb。因此BnHwComposer的onTransact将接收请求:
composer\2.1\android.hardware.graphics.composer@2.1_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.  
  9. switch (_hidl_code) {

  10. case 256067662 /* interfaceChain */:

  11. {

  12. _hidl_err = ::android::hidl::base::V1_0::BnHwBase::_hidl_interfaceChain(this, _hidl_data, _hidl_reply, _hidl_cb);

  13. break;

  14. }

  15. default:

  16. {

  17. return ::android::hidl::base::V1_0::BnHwBase::onTransact(

  18. _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb);

  19. }

  20. }

  21.  
  22. if (_hidl_err == ::android::UNEXPECTED_NULL) {

  23. _hidl_err = ::android::hardware::writeToParcel(

  24. ::android::hardware::Status::fromExceptionCode(::android::hardware::Status::EX_NULL_POINTER),

  25. _hidl_reply);

  26. }return _hidl_err;

  27. }

注意,onTransact的最后一个参数是一个回调函数,是由IPCThreadState传递进来的,该回调函数将传入BnHwBase的interfaceChain中执行。这个实现由其父类BnHwBase来完成:

android.hidl.base@1.0_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.  
  11. ::android::status_t _hidl_err = ::android::OK;

  12. if (!_hidl_data.enforceInterface(BnHwBase::Pure::descriptor)) {

  13. _hidl_err = ::android::BAD_TYPE;

  14. return _hidl_err;

  15. }

  16.  
  17. atrace_begin(ATRACE_TAG_HAL, "HIDL::IBase::interfaceChain::server");

  18. #ifdef __ANDROID_DEBUGGABLE__

  19. if (UNLIKELY(mEnableInstrumentation)) {

  20. std::vector<void *> _hidl_args;

  21. for (const auto &callback: mInstrumentationCallbacks) {

  22. callback(InstrumentationEvent::SERVER_API_ENTRY, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args);

  23. }

  24. }

  25. #endif // __ANDROID_DEBUGGABLE__

  26.  
  27. bool _hidl_callbackCalled = false;

  28.  
  29. static_cast<BnHwBase*>(_hidl_this)->_hidl_mImpl->interfaceChain([&](const auto &_hidl_out_descriptors) {

  30. ...

  31.      });

  32.  
  33. if (!_hidl_callbackCalled) {

  34. LOG_ALWAYS_FATAL("interfaceChain: _hidl_cb not called, but must be called once.");

  35. }

  36.  
  37. return _hidl_err;

  38. }

BnHwBase的interfaceChain实现又转交给_hidl_mImpl,同时也传入一个匿名的回调函数,而BnHwBase的_hidl_mImpl保存的是HwcHal对象,HwcHal并没有实现该函数,该函数由其父类IComposer类实现。

composer\2.1\android.hardware.graphics.composer@2.1_genc++\gen\android\hardware\graphics\composer\2.1\ComposerAll.cpp

 
  1. ::android::hardware::Return<void> IComposer::interfaceChain(interfaceChain_cb _hidl_cb){

  2. _hidl_cb({

  3. IComposer::descriptor,

  4. ::android::hidl::base::V1_0::IBase::descriptor,

  5. });

  6. return ::android::hardware::Void();}

这里只是回调由BnHwBase传进来的回调函数,且函数参数是IComposer::descriptor, IBase::descriptor。回调函数实现如下:

 
  1. {

  2. if (_hidl_callbackCalled) {

  3. LOG_ALWAYS_FATAL("interfaceChain: _hidl_cb called a second time, but must be called once.");

  4. }

  5. _hidl_callbackCalled = true;

  6.  
  7. ::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply);

  8.  
  9. size_t _hidl__hidl_out_descriptors_parent;

  10.  
  11. _hidl_err = _hidl_reply->writeBuffer(&_hidl_out_descriptors, sizeof(_hidl_out_descriptors), &_hidl__hidl_out_descriptors_parent);

  12. /* _hidl_err ignored! */

  13.  
  14. size_t _hidl__hidl_out_descriptors_child;

  15.  
  16. _hidl_err = ::android::hardware::writeEmbeddedToParcel(

  17. _hidl_out_descriptors,

  18. _hidl_reply,

  19. _hidl__hidl_out_descriptors_parent,

  20. 0 /* parentOffset */, &_hidl__hidl_out_descriptors_child);

  21.  
  22. /* _hidl_err ignored! */

  23.  
  24. for (size_t _hidl_index_0 = 0; _hidl_index_0 < _hidl_out_descriptors.size(); ++_hidl_index_0) {

  25. _hidl_err = ::android::hardware::writeEmbeddedToParcel(

  26. _hidl_out_descriptors[_hidl_index_0],

  27. _hidl_reply,

  28. _hidl__hidl_out_descriptors_child,

  29. _hidl_index_0 * sizeof(::android::hardware::hidl_string));

  30.  
  31. /* _hidl_err ignored! */

  32.  
  33. }

  34.  
  35. atrace_end(ATRACE_TAG_HAL);

  36. #ifdef __ANDROID_DEBUGGABLE__

  37. if (UNLIKELY(mEnableInstrumentation)) {

  38. std::vector<void *> _hidl_args;

  39. _hidl_args.push_back((void *)&_hidl_out_descriptors);

  40. for (const auto &callback: mInstrumentationCallbacks) {

  41. callback(InstrumentationEvent::SERVER_API_EXIT, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args);

  42. }

  43. }

  44. #endif // __ANDROID_DEBUGGABLE__

  45.  
  46. _hidl_cb(*_hidl_reply);

  47. }

这里只是将回调函数的参数IComposer::descriptor,IBase::descriptor打包到Parcel对象中,然后继续调用由IPCThreadState传进入的回调函数,该回调实现如下:

system\libhwbinder\IPCThreadState.cpp

 
  1. auto reply_callback = [&] (auto &replyParcel) {

  2. if (reply_sent) {

  3. // Reply was sent earlier, ignore it.

  4. ALOGE("Dropping binder reply, it was sent already.");

  5. return;

  6. }

  7. reply_sent = true;

  8. if ((tr.flags & TF_ONE_WAY) == 0) {

  9. replyParcel.setError(NO_ERROR);

  10. sendReply(replyParcel, 0);

  11. } else {

  12. ALOGE("Not sending reply in one-way transaction");

  13. }

  14. };

该回调函数只是将打包后的Parcel发送给hwservicemanager进程。

也就是说,hwservicemanager将得到IComposer::descriptor,IBase::descriptor,BpHwBase读取到这些数据后,接着会回调由ServiceManager传入进来的回调函数:

system\hwservicemanager\ServiceManager.cpp

 
  1. {

  2. if (interfaceChain.size() == 0) {

  3. return;

  4. }

  5.  
  6. // First, verify you're allowed to add() the whole interface hierarchy

  7. for(size_t i = 0; i < interfaceChain.size(); i++) {

  8. std::string fqName = interfaceChain[i];

  9. if (!mAcl.canAdd(fqName, pid)) {

  10. return;

  11. }

  12. }

  13.  
  14. for(size_t i = 0; i < interfaceChain.size(); i++) {

  15. std::string fqName = interfaceChain[i];

  16. LOG(INFO) << "add service of " << fqName;

  17.  
  18. PackageInterfaceMap &ifaceMap = mServiceMap[fqName];

  19. HidlService *hidlService = ifaceMap.lookup(name);

  20.  
  21. if (hidlService == nullptr) {

  22. LOG(INFO) << "insertService " << name << " of " << fgName ;

  23. ifaceMap.insertService(

  24. std::make_unique<HidlService>(fqName, name, service, pid));

  25. } else {

  26. if (hidlService->getService() != nullptr) {

  27. auto ret = hidlService->getService()->unlinkToDeath(this);

  28. ret.isOk(); // ignore

  29. }

  30. LOG(INFO) << "setService " << " of " << fgName ;

  31. hidlService->setService(service, pid);

  32. }

  33.  
  34. ifaceMap.sendPackageRegistrationNotification(fqName, name);

  35. }

  36.  
  37. auto linkRet = service->linkToDeath(this, 0 /*cookie*/);

  38. linkRet.isOk(); // ignore

  39.  
  40. isValidService = true;

  41. }

该回调函数的参数值其实就是从Hal进程传递过来的IComposer::descriptor,IBase::descriptor,这时就开始完成服务注册了,整个服务注册过程分为三个步骤:
1.    服务校验过程
2.    服务添加过程
3.    死亡通知注册过程

 

服务校验

AccessControl类主要负责权限检查,包括SELinux权限。
system\hwservicemanager\AccessControl.cpp

 
  1. AccessControl::AccessControl() {

  2. mSeHandle = selinux_android_hw_service_context_handle();

  3. LOG_ALWAYS_FATAL_IF(mSeHandle == NULL, "Failed to acquire SELinux handle.");

  4.  
  5. if (getcon(&mSeContext) != 0) {

  6. LOG_ALWAYS_FATAL("Failed to acquire hwservicemanager context.");

  7. }

  8.  
  9. selinux_status_open(true);

  10.  
  11. mSeCallbacks.func_audit = AccessControl::auditCallback;

  12. selinux_set_callback(SELINUX_CB_AUDIT, mSeCallbacks);

  13.  
  14. mSeCallbacks.func_log = selinux_log_callback; /* defined in libselinux */

  15. selinux_set_callback(SELINUX_CB_LOG, mSeCallbacks);

  16. }

判断是否有权限添加过程如下:

 
  1. bool AccessControl::canAdd(const std::string& fqName, pid_t pid) {

  2. FQName fqIface(fqName);

  3.  
  4. if (!fqIface.isValid()) {

  5. return false;

  6. }

  7. const std::string checkName = fqIface.package() + "::" + fqIface.name();

  8. return checkPermission(pid, kPermissionAdd, checkName.c_str());

  9. }

system\tools\hidl\utils\FQName.cpp

 
  1. FQName::FQName(const std::vector<std::string> &names)

  2. : mValid(false),

  3. mIsIdentifier(false) {

  4. setTo(StringHelper::JoinStrings(names, "."));

  5. }

 
  1. bool FQName::setTo(const std::string &s) {

  2. clearVersion();

  3. mPackage.clear();

  4. mName.clear();

  5.  
  6. mValid = true;

  7.  
  8. std::smatch match;

  9. if (std::regex_match(s, match, kRE1)) {

  10. CHECK_EQ(match.size(), 5u);

  11.  
  12. mPackage = match.str(1);

  13. parseVersion(match.str(2), match.str(3));

  14. mName = match.str(4);

  15. } else if (std::regex_match(s, match, kRE2)) {

  16. CHECK_EQ(match.size(), 4u);

  17.  
  18. parseVersion(match.str(1), match.str(2));

  19. mName = match.str(3);

  20. } else if (std::regex_match(s, match, kRE3)) {

  21. CHECK_EQ(match.size(), 4u);

  22.  
  23. mPackage = match.str(1);

  24. parseVersion(match.str(2), match.str(3));

  25. } else if (std::regex_match(s, match, kRE4)) {

  26. mName = match.str(0);

  27. } else if (std::regex_match(s, match, kRE5)) {

  28. mIsIdentifier = true;

  29. mName = match.str(0);

  30. } else if (std::regex_match(s, match, kRE6)) {

  31. CHECK_EQ(match.size(), 6u);

  32.  
  33. mPackage = match.str(1);

  34. parseVersion(match.str(2), match.str(3));

  35. mName = match.str(4);

  36. mValueName = match.str(5);

  37. } else if (std::regex_match(s, match, kRE7)) {

  38. CHECK_EQ(match.size(), 5u);

  39.  
  40. parseVersion(match.str(1), match.str(2));

  41. mName = match.str(3);

  42. mValueName = match.str(4);

  43. } else if (std::regex_match(s, match, kRE8)) {

  44. CHECK_EQ(match.size(), 3u);

  45.  
  46. mName = match.str(1);

  47. mValueName = match.str(2);

  48. } else {

  49. mValid = false;

  50. }

  51.  
  52. // mValueName must go with mName.

  53. CHECK(mValueName.empty() || !mName.empty());

  54.  
  55. // package without version is not allowed.

  56. CHECK(mPackage.empty() || !version().empty());

  57.  
  58. return isValid();

  59. }

setTo函数其实就是使用正则表达式从android.hidl.manager@1.0::IServiceManager字符串中取出包名,版本号,及服务类名,从而检查包名是否符合命名规则,如果包名有效,则继续调用checkPermission函数来检查selinux权限。

 
  1. bool AccessControl::checkPermission(pid_t sourcePid, const char *targetContext,

  2. const char *perm, const char *interface) {

  3. char *sourceContext = NULL;

  4. bool allowed = false;

  5. struct audit_data ad;

  6.  
  7. if (getpidcon(sourcePid, &sourceContext) < 0) {

  8. ALOGE("SELinux: failed to retrieved process context for pid %d", sourcePid);

  9. return false;

  10. }

  11.  
  12. ad.pid = sourcePid;

  13. ad.interfaceName = interface;

  14.  
  15. allowed = (selinux_check_access(sourceContext, targetContext, "hwservice_manager",

  16. perm, (void *) &ad) == 0);

  17.  
  18. freecon(sourceContext);

  19.  
  20. return allowed;

  21. }

服务注册

如果服务注册进程有权限向hwservicemanager注册服务,接下来将完成服务添加。

每个服务接口对应多个实例,比如android.hidl.manager@1.1::IServiceManager可以注册多个实例,每个实例名称不同。

 
  1. PackageInterfaceMap &ifaceMap = mServiceMap[fqName];

  2. HidlService *hidlService = ifaceMap.lookup(name);

 
  1. const HidlService *ServiceManager::PackageInterfaceMap::lookup(

  2. const std::string &name) const {

  3. auto it = mInstanceMap.find(name);

  4.  
  5. if (it == mInstanceMap.end()) {

  6. return nullptr;

  7. }

  8. return it->second.get();

  9. }

根据名称查找HidlService,如果找不到,则新增一个HidlService,如果已经存在,则更新service。

 
  1. if (hidlService == nullptr) {

  2. LOG(INFO) << "insertService " << name << " of " << fgName ;

  3. ifaceMap.insertService(

  4. std::make_unique<HidlService>(fqName, name, service, pid));

  5. } else {

  6. if (hidlService->getService() != nullptr) {

  7. auto ret = hidlService->getService()->unlinkToDeath(this);

  8. ret.isOk(); // ignore

  9. }

  10. LOG(INFO) << "setService " << " of " << fgName ;

  11. hidlService->setService(service, pid);

  12. }

到此就完成了hidl服务注册。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值