AndroidO Treble架構下Hal進程啓動及HIDL服務註冊過程

通過前面對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.  
  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\[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.  
  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來完成的,此時[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.  
  5. //fqName looks like [email protected]::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=([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. name: "[email protected]",

  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. "[email protected]",

  10. "[email protected]",

  11. "libbase",

  12. "libcutils",

  13. "libfmq",

  14. "libhardware",

  15. "libhidlbase",

  16. "libhidltransport",

  17. "liblog",

  18. "libsync",

  19. "libutils",

  20. "libhwc2on1adapter"

  21. ],

  22. }

從上面的編譯腳本可知,[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.  
  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。

[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.  
  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將接收函數調用請求:

[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.  
  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\[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.  
  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. [email protected] -> [email protected]

  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. }

這裏只是簡單的修改了當前進程的名稱。

[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.  
  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。

[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.  
  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函數實現如下:

[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.  
  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\[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.  
  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來完成:

[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.  
  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\[email protected]_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函數其實就是使用正則表達式從[email protected]::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註冊服務,接下來將完成服務添加。

每個服務接口對應多個實例,比如[email protected]::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服務註冊。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章