通过前面对Treble架构的介绍,我们知道,Android Framework进程和Hal分离,每个Hal独立运行在自己的进程地址空间,那么这些Hal进程是如何启动的呢?本文以composer hal为例展开分析。
在以下路径有composer hal的rc启动脚本:
hardware/interfaces/graphics/composer/2.1/default/[email protected]
- service hwcomposer-2-1 /vendor/bin/hw/[email protected]
- class hal animation
- user system
- group graphics drmrpc
- capabilities SYS_NICE
- onrestart restart surfaceflinger
service hwcomposer-2-1 /vendor/bin/hw/[email protected] class hal animation user system group graphics drmrpc capabilities SYS_NICE onrestart restart surfaceflinger
编译后,会将该脚本文件copy到vendor/etc/init目录,在开机时,init进程会读取并解析这个脚本,然后启动[email protected]进程:
- system 661 1 32288 7832 0 0 S [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
- int main() {
- // the conventional HAL might start binder services
- android::ProcessState::initWithDriver(“/dev/vndbinder”);
- android::ProcessState::self()->setThreadPoolMaxThreadCount(4);
- android::ProcessState::self()->startThreadPool();
- // same as SF main thread
- struct sched_param param = {0};
- param.sched_priority = 2;
- if (sched_setscheduler(0, SCHED_FIFO | SCHED_RESET_ON_FORK,
- ¶m) != 0) {
- ALOGE(“Couldn’t set SCHED_FIFO: %d”, errno);
- }
- return defaultPassthroughServiceImplementation<IComposer>(4);
- }
int main() { // the conventional HAL might start binder services android::ProcessState::initWithDriver("/dev/vndbinder"); android::ProcessState::self()->setThreadPoolMaxThreadCount(4); android::ProcessState::self()->startThreadPool(); // same as SF main thread struct sched_param param = {0}; param.sched_priority = 2; if (sched_setscheduler(0, SCHED_FIFO | SCHED_RESET_ON_FORK, ¶m) != 0) { ALOGE("Couldn't set SCHED_FIFO: %d", errno); } return defaultPassthroughServiceImplementation<IComposer>(4); }前面我们分析了Treble架构下的binder通信变化,在Treble架构下,存在了3个binder设备,分别是/dev/binder、/dev/vndbinder、/dev/hwbinder,上层需要通过binder库来访问这些binder设备,而/dev/binder和/dev/vndbinder都是由libbinder来访问,因此需要指定打开的binder设备。
- android::ProcessState::initWithDriver(“/dev/vndbinder”);
android::ProcessState::initWithDriver("/dev/vndbinder");这句说明composer hal通过vndbinder来通信的,接下来就是设置binder线程个数为4,并启动binder线程池,然后调用
- defaultPassthroughServiceImplementation<IComposer>(4)
defaultPassthroughServiceImplementation<IComposer>(4)
完成composer hal的启动。
system\libhidl\transport\include\hidl\LegacySupport.h
- template<class Interface>
- __attribute__((warn_unused_result))
- status_t defaultPassthroughServiceImplementation(std::string name,
- size_t maxThreads = 1) {
- configureRpcThreadpool(maxThreads, true); //配置binder线程个数
- status_t result = registerPassthroughServiceImplementation<Interface>(name);
- if (result != OK) {
- return result;
- }
- joinRpcThreadpool();
- return 0;
- }
template<class Interface> __attribute__((warn_unused_result)) status_t defaultPassthroughServiceImplementation(std::string name, size_t maxThreads = 1) { configureRpcThreadpool(maxThreads, true); //配置binder线程个数 status_t result = registerPassthroughServiceImplementation<Interface>(name); if (result != OK) { return result; } joinRpcThreadpool(); return 0; }
- template<class Interface>
- __attribute__((warn_unused_result))
- status_t registerPassthroughServiceImplementation(
- std::string name = ”default”) {
- sp<Interface> service = Interface::getService(name, true /* getStub */); //从当前进程空间中拿到IComposer接口类对象
- if (service == nullptr) {
- ALOGE(”Could not get passthrough implementation for %s/%s.”,
- Interface::descriptor, name.c_str());
- return EXIT_FAILURE;
- }
- LOG_FATAL_IF(service->isRemote(), ”Implementation of %s/%s is remote!”,
- Interface::descriptor, name.c_str());
- status_t status = service->registerAsService(name);//将IComposer注册到hwservicemanager中
- if (status == OK) {
- ALOGI(”Registration complete for %s/%s.”,
- Interface::descriptor, name.c_str());
- } else {
- ALOGE(”Could not register service %s/%s (%d).”,
- Interface::descriptor, name.c_str(), status);
- }
- return status;
- }
template<class Interface> __attribute__((warn_unused_result)) status_t registerPassthroughServiceImplementation( std::string name = "default") { sp<Interface> service = Interface::getService(name, true /* getStub */); //从当前进程空间中拿到IComposer接口类对象 if (service == nullptr) { ALOGE("Could not get passthrough implementation for %s/%s.", Interface::descriptor, name.c_str()); return EXIT_FAILURE; } LOG_FATAL_IF(service->isRemote(), "Implementation of %s/%s is remote!", Interface::descriptor, name.c_str()); status_t status = service->registerAsService(name);//将IComposer注册到hwservicemanager中 if (status == OK) { ALOGI("Registration complete for %s/%s.", Interface::descriptor, name.c_str()); } else { ALOGE("Could not register service %s/%s (%d).", Interface::descriptor, name.c_str(), status); } return status; }
Hal进程获取IComposer类对象
在composer hal进程启动时,首先调用IComposer 的getService(“default”,true)来获取IComposer的类对象。
composer\2.1\[email protected]_genc++\gen\android\hardware\graphics\composer\2.1\ComposerAll.cpp
- ::android::sp<IComposer> IComposer::getService(const std::string &serviceName, const bool getStub) {
- using ::android::hardware::defaultServiceManager;
- using ::android::hardware::details::waitForHwService;
- using ::android::hardware::getPassthroughServiceManager;
- using ::android::hardware::Return;
- using ::android::sp;
- using Transport = ::android::hidl::manager::V1_0::IServiceManager::Transport;
- sp<IComposer> iface = nullptr;
- const sp<::android::hidl::manager::V1_0::IServiceManager> sm = defaultServiceManager(); //获取hwservicemanager的代理
- if (sm == nullptr) {
- ALOGE(”getService: defaultServiceManager() is null”);
- return nullptr;
- }
- Return<Transport> transportRet = sm->getTransport(IComposer::descriptor, serviceName);//查询IComposer的Transport
- if (!transportRet.isOk()) {
- ALOGE(”getService: defaultServiceManager()->getTransport returns %s”, transportRet.description().c_str());
- return nullptr;
- }
- Transport transport = transportRet;
- const bool vintfHwbinder = (transport == Transport::HWBINDER);
- const bool vintfPassthru = (transport == Transport::PASSTHROUGH); //Transport类型判断
- #ifdef __ANDROID_TREBLE__
- #ifdef __ANDROID_DEBUGGABLE__
- const char* env = std::getenv(“TREBLE_TESTING_OVERRIDE”);
- const bool trebleTestingOverride = env && !strcmp(env, “true”);
- const bool vintfLegacy = (transport == Transport::EMPTY) && trebleTestingOverride;
- #else // __ANDROID_TREBLE__ but not __ANDROID_DEBUGGABLE__
- const bool trebleTestingOverride = false;
- const bool vintfLegacy = false;
- #endif // __ANDROID_DEBUGGABLE__
- #else // not __ANDROID_TREBLE__
- const char* env = std::getenv(“TREBLE_TESTING_OVERRIDE”);
- const bool trebleTestingOverride = env && !strcmp(env, “true”);
- const bool vintfLegacy = (transport == Transport::EMPTY);
- #endif // __ANDROID_TREBLE__
- //hwbinder方式下获取IComposer对象
- for (int tries = 0; !getStub && (vintfHwbinder || (vintfLegacy && tries == 0)); tries++) {
- if (tries > 1) {
- ALOGI(”getService: Will do try %d for %s/%s in 1s…”, tries, IComposer::descriptor, serviceName.c_str());
- sleep(1);
- }
- if (vintfHwbinder && tries > 0) {
- waitForHwService(IComposer::descriptor, serviceName);
- }
- Return<sp<::android::hidl::base::V1_0::IBase>> ret =
- sm->get(IComposer::descriptor, serviceName);
- if (!ret.isOk()) {
- ALOGE(”IComposer: defaultServiceManager()->get returns %s”, ret.description().c_str());
- break;
- }
- sp<::android::hidl::base::V1_0::IBase> base = ret;
- if (base == nullptr) {
- if (tries > 0) {
- ALOGW(”IComposer: found null hwbinder interface”);
- }continue;
- }
- Return<sp<IComposer>> castRet = IComposer::castFrom(base, true /* emitError */);
- if (!castRet.isOk()) {
- if (castRet.isDeadObject()) {
- ALOGW(”IComposer: found dead hwbinder service”);
- continue;
- } else {
- ALOGW(”IComposer: cannot call into hwbinder service: %s; No permission? Check for selinux denials.”, castRet.description().c_str());
- break;
- }
- }
- iface = castRet;
- if (iface == nullptr) {
- ALOGW(”IComposer: received incompatible service; bug in hwservicemanager?”);
- break;
- }
- return iface;
- }
- //passthrough方式下获取IComposer对象
- if (getStub || vintfPassthru || vintfLegacy) {
- const sp<::android::hidl::manager::V1_0::IServiceManager> pm = getPassthroughServiceManager();
- if (pm != nullptr) {
- Return<sp<::android::hidl::base::V1_0::IBase>> ret =
- pm->get(IComposer::descriptor, serviceName);
- if (ret.isOk()) {
- sp<::android::hidl::base::V1_0::IBase> baseInterface = ret;
- if (baseInterface != nullptr) {
- iface = IComposer::castFrom(baseInterface);
- if (!getStub || trebleTestingOverride) {
- iface = new BsComposer(iface);
- }
- }
- }
- }
- }
- return iface;
- }
::android::sp<IComposer> IComposer::getService(const std::string &serviceName, const bool getStub) { using ::android::hardware::defaultServiceManager; using ::android::hardware::details::waitForHwService; using ::android::hardware::getPassthroughServiceManager; using ::android::hardware::Return; using ::android::sp; using Transport = ::android::hidl::manager::V1_0::IServiceManager::Transport; sp<IComposer> iface = nullptr; const sp<::android::hidl::manager::V1_0::IServiceManager> sm = defaultServiceManager(); //获取hwservicemanager的代理 if (sm == nullptr) { ALOGE("getService: defaultServiceManager() is null"); return nullptr; } Return<Transport> transportRet = sm->getTransport(IComposer::descriptor, serviceName);//查询IComposer的Transport if (!transportRet.isOk()) { ALOGE("getService: defaultServiceManager()->getTransport returns %s", transportRet.description().c_str()); return nullptr; } Transport transport = transportRet; const bool vintfHwbinder = (transport == Transport::HWBINDER); const bool vintfPassthru = (transport == Transport::PASSTHROUGH); //Transport类型判断 #ifdef __ANDROID_TREBLE__ #ifdef __ANDROID_DEBUGGABLE__ const char* env = std::getenv("TREBLE_TESTING_OVERRIDE"); const bool trebleTestingOverride = env && !strcmp(env, "true"); const bool vintfLegacy = (transport == Transport::EMPTY) && trebleTestingOverride; #else // __ANDROID_TREBLE__ but not __ANDROID_DEBUGGABLE__ const bool trebleTestingOverride = false; const bool vintfLegacy = false; #endif // __ANDROID_DEBUGGABLE__ #else // not __ANDROID_TREBLE__ const char* env = std::getenv("TREBLE_TESTING_OVERRIDE"); const bool trebleTestingOverride = env && !strcmp(env, "true"); const bool vintfLegacy = (transport == Transport::EMPTY); #endif // __ANDROID_TREBLE__ //hwbinder方式下获取IComposer对象 for (int tries = 0; !getStub && (vintfHwbinder || (vintfLegacy && tries == 0)); tries++) { if (tries > 1) { ALOGI("getService: Will do try %d for %s/%s in 1s...", tries, IComposer::descriptor, serviceName.c_str()); sleep(1); } if (vintfHwbinder && tries > 0) { waitForHwService(IComposer::descriptor, serviceName); } Return<sp<::android::hidl::base::V1_0::IBase>> ret = sm->get(IComposer::descriptor, serviceName); if (!ret.isOk()) { ALOGE("IComposer: defaultServiceManager()->get returns %s", ret.description().c_str()); break; } sp<::android::hidl::base::V1_0::IBase> base = ret; if (base == nullptr) { if (tries > 0) { ALOGW("IComposer: found null hwbinder interface"); }continue; } Return<sp<IComposer>> castRet = IComposer::castFrom(base, true /* emitError */); if (!castRet.isOk()) { if (castRet.isDeadObject()) { ALOGW("IComposer: found dead hwbinder service"); continue; } else { ALOGW("IComposer: cannot call into hwbinder service: %s; No permission? Check for selinux denials.", castRet.description().c_str()); break; } } iface = castRet; if (iface == nullptr) { ALOGW("IComposer: received incompatible service; bug in hwservicemanager?"); break; } return iface; } //passthrough方式下获取IComposer对象 if (getStub || vintfPassthru || vintfLegacy) { const sp<::android::hidl::manager::V1_0::IServiceManager> pm = getPassthroughServiceManager(); if (pm != nullptr) { Return<sp<::android::hidl::base::V1_0::IBase>> ret = pm->get(IComposer::descriptor, serviceName); if (ret.isOk()) { sp<::android::hidl::base::V1_0::IBase> baseInterface = ret; if (baseInterface != nullptr) { iface = IComposer::castFrom(baseInterface); if (!getStub || trebleTestingOverride) { iface = new BsComposer(iface); } } } } } 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图:
- if (getStub || vintfPassthru || vintfLegacy) {
- const sp<::android::hidl::manager::V1_0::IServiceManager> pm = getPassthroughServiceManager();
- if (pm != nullptr) {
- Return<sp<::android::hidl::base::V1_0::IBase>> ret =
- pm->get(IComposer::descriptor, serviceName);
- if (ret.isOk()) {
- sp<::android::hidl::base::V1_0::IBase> baseInterface = ret;
- if (baseInterface != nullptr) {
- iface = IComposer::castFrom(baseInterface);
- if (!getStub || trebleTestingOverride) {
- iface = new BsComposer(iface);
- }
- }
- }
- }
- }
if (getStub || vintfPassthru || vintfLegacy) { const sp<::android::hidl::manager::V1_0::IServiceManager> pm = getPassthroughServiceManager(); if (pm != nullptr) { Return<sp<::android::hidl::base::V1_0::IBase>> ret = pm->get(IComposer::descriptor, serviceName); if (ret.isOk()) { sp<::android::hidl::base::V1_0::IBase> baseInterface = ret; if (baseInterface != nullptr) { iface = IComposer::castFrom(baseInterface); if (!getStub || trebleTestingOverride) { iface = new BsComposer(iface); } } } } }
- sp<IServiceManager> getPassthroughServiceManager() {
- static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
- return manager;
- }
sp<IServiceManager> getPassthroughServiceManager() { static sp<PassthroughServiceManager> manager(new PassthroughServiceManager()); return manager; }这里只是简单的创建了一个PassthroughServiceManager对象。PassthroughServiceManager也实现了IServiceManager接口。然后通过PassthroughServiceManager询服务:
- Return<sp<IBase>> get(const hidl_string& fqName,
- const hidl_string& name) override {
- std::string stdFqName(fqName.c_str());
- //fqName looks like [email protected]::IFoo
- size_t idx = stdFqName.find(“::”);
- if (idx == std::string::npos ||
- idx + strlen(”::”) + 1 >= stdFqName.size()) {
- LOG(ERROR) << ”Invalid interface name passthrough lookup: ” << fqName;
- return nullptr;
- }
- std::string packageAndVersion = stdFqName.substr(0, idx);
- std::string ifaceName = stdFqName.substr(idx + strlen(”::”));
- const std::string prefix = packageAndVersion + “-impl”;
- const std::string sym = “HIDL_FETCH_” + ifaceName;
- const android_namespace_t* sphal_namespace = android_get_exported_namespace(“sphal”);
- const int dlMode = RTLD_LAZY;
- void *handle = nullptr;
- // TODO: lookup in VINTF instead
- // TODO(b/34135607): Remove HAL_LIBRARY_PATH_SYSTEM
- dlerror(); // clear
- for (const std::string &path : {
- HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, HAL_LIBRARY_PATH_SYSTEM
- }) {
- std::vector<std::string> libs = search(path, prefix, ”.so”);
- for (const std::string &lib : libs) {
- const std::string fullPath = path + lib;
- // If sphal namespace is available, try to load from the
- // namespace first. If it fails, fall back to the original
- // dlopen, which loads from the current namespace.
- if (sphal_namespace != nullptr && path != HAL_LIBRARY_PATH_SYSTEM) {
- const android_dlextinfo dlextinfo = {
- .flags = ANDROID_DLEXT_USE_NAMESPACE,
- // const_cast is dirty but required because
- // library_namespace field is non-const.
- .library_namespace = const_cast<android_namespace_t*>(sphal_namespace),
- };
- handle = android_dlopen_ext(fullPath.c_str(), dlMode, &dlextinfo);
- if (handle == nullptr) {
- const char* error = dlerror();
- LOG(WARNING) << ”Failed to dlopen ” << lib << “ from sphal namespace:”
- << (error == nullptr ? ”unknown error” : error);
- } else {
- LOG(DEBUG) << lib << ” loaded from sphal namespace.”;
- }
- }
- if (handle == nullptr) {
- handle = dlopen(fullPath.c_str(), dlMode);
- }
- if (handle == nullptr) {
- const char* error = dlerror();
- LOG(ERROR) << ”Failed to dlopen ” << lib << “: ”
- << (error == nullptr ? ”unknown error” : error);
- continue;
- }
- IBase* (*generator)(const char* name);
- *(void **)(&generator) = dlsym(handle, sym.c_str());
- if(!generator) {
- const char* error = dlerror();
- LOG(ERROR) << ”Passthrough lookup opened ” << lib
- << ” but could not find symbol ” << sym << “: ”
- << (error == nullptr ? ”unknown error” : error);
- dlclose(handle);
- continue;
- }
- IBase *interface = (*generator)(name.c_str());
- if (interface == nullptr) {
- dlclose(handle);
- continue; // this module doesn’t provide this instance name
- }
- registerReference(fqName, name);
- return interface;
- }
- }
- return nullptr;
- }
Return<sp<IBase>> get(const hidl_string& fqName, const hidl_string& name) override { std::string stdFqName(fqName.c_str()); //fqName looks like [email protected]::IFoo size_t idx = stdFqName.find("::"); if (idx == std::string::npos || idx + strlen("::") + 1 >= stdFqName.size()) { LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName; return nullptr; } std::string packageAndVersion = stdFqName.substr(0, idx); std::string ifaceName = stdFqName.substr(idx + strlen("::")); const std::string prefix = packageAndVersion + "-impl"; const std::string sym = "HIDL_FETCH_" + ifaceName; const android_namespace_t* sphal_namespace = android_get_exported_namespace("sphal"); const int dlMode = RTLD_LAZY; void *handle = nullptr; // TODO: lookup in VINTF instead // TODO(b/34135607): Remove HAL_LIBRARY_PATH_SYSTEM dlerror(); // clear for (const std::string &path : { HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR, HAL_LIBRARY_PATH_SYSTEM }) { std::vector<std::string> libs = search(path, prefix, ".so"); for (const std::string &lib : libs) { const std::string fullPath = path + lib; // If sphal namespace is available, try to load from the // namespace first. If it fails, fall back to the original // dlopen, which loads from the current namespace. if (sphal_namespace != nullptr && path != HAL_LIBRARY_PATH_SYSTEM) { const android_dlextinfo dlextinfo = { .flags = ANDROID_DLEXT_USE_NAMESPACE, // const_cast is dirty but required because // library_namespace field is non-const. .library_namespace = const_cast<android_namespace_t*>(sphal_namespace), }; handle = android_dlopen_ext(fullPath.c_str(), dlMode, &dlextinfo); if (handle == nullptr) { const char* error = dlerror(); LOG(WARNING) << "Failed to dlopen " << lib << " from sphal namespace:" << (error == nullptr ? "unknown error" : error); } else { LOG(DEBUG) << lib << " loaded from sphal namespace."; } } if (handle == nullptr) { handle = dlopen(fullPath.c_str(), dlMode); } if (handle == nullptr) { const char* error = dlerror(); LOG(ERROR) << "Failed to dlopen " << lib << ": " << (error == nullptr ? "unknown error" : error); continue; } IBase* (*generator)(const char* name); *(void **)(&generator) = dlsym(handle, sym.c_str()); if(!generator) { const char* error = dlerror(); LOG(ERROR) << "Passthrough lookup opened " << lib << " but could not find symbol " << sym << ": " << (error == nullptr ? "unknown error" : error); dlclose(handle); continue; } IBase *interface = (*generator)(name.c_str()); if (interface == nullptr) { dlclose(handle); continue; // this module doesn't provide this instance name } registerReference(fqName, name); return interface; } } return nullptr; }
根据传入的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
- cc_library_shared {
- name: “[email protected]”,
- defaults: [“hidl_defaults”],
- proprietary: true,
- relative_install_path: “hw”,
- srcs: [“Hwc.cpp”],
- static_libs: [“libhwcomposer-client”],
- shared_libs: [
- “[email protected]”,
- “[email protected]”,
- “libbase”,
- “libcutils”,
- “libfmq”,
- “libhardware”,
- “libhidlbase”,
- “libhidltransport”,
- “liblog”,
- “libsync”,
- “libutils”,
- “libhwc2on1adapter”
- ],
- }
cc_library_shared { name: "[email protected]", defaults: ["hidl_defaults"], proprietary: true, relative_install_path: "hw", srcs: ["Hwc.cpp"], static_libs: ["libhwcomposer-client"], shared_libs: [ "[email protected]", "[email protected]", "libbase", "libcutils", "libfmq", "libhardware", "libhidlbase", "libhidltransport", "liblog", "libsync", "libutils", "libhwc2on1adapter" ], }从上面的编译脚本可知,[email protected]的源码文件为Hwc.cpp:
hardware/interfaces/graphics/composer/2.1/default/Hwc.cpp
- IComposer* HIDL_FETCH_IComposer(const char*)
- {
- const hw_module_t* module = nullptr;
- int err = hw_get_module(HWC_HARDWARE_MODULE_ID, &module);
- if (err) {
- ALOGE(”failed to get hwcomposer module”);
- return nullptr;
- }
- return new HwcHal(module);
- }
IComposer* HIDL_FETCH_IComposer(const char*) { const hw_module_t* module = nullptr; int err = hw_get_module(HWC_HARDWARE_MODULE_ID, &module); if (err) { ALOGE("failed to get hwcomposer module"); return nullptr; } return new HwcHal(module); }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
- static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
- sp<IServiceManager> binderizedManager = defaultServiceManager();
- if (binderizedManager == nullptr) {
- LOG(WARNING) << ”Could not registerReference for ”
- << interfaceName << ”/” << instanceName
- << ”: null binderized manager.”;
- return;
- }
- auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName);
- if (!ret.isOk()) {
- LOG(WARNING) << ”Could not registerReference for ”
- << interfaceName << ”/” << instanceName
- << ”: ” << ret.description();
- return;
- }
- LOG(VERBOSE) << ”Successfully registerReference for ”
- << interfaceName << ”/” << instanceName;
- }
static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) { sp<IServiceManager> binderizedManager = defaultServiceManager(); if (binderizedManager == nullptr) { LOG(WARNING) << "Could not registerReference for " << interfaceName << "/" << instanceName << ": null binderized manager."; return; } auto ret = binderizedManager->registerPassthroughClient(interfaceName, instanceName); if (!ret.isOk()) { LOG(WARNING) << "Could not registerReference for " << interfaceName << "/" << instanceName << ": " << ret.description(); return; } LOG(VERBOSE) << "Successfully registerReference for " << interfaceName << "/" << instanceName; }这里通过hwservicemanager的代理对象跨进程调用registerPassthroughClient。
[email protected]_genc++\gen\android\hidl\manager\1.0\ServiceManagerAll.cpp
- ::android::hardware::Return<void> BpHwServiceManager::registerPassthroughClient(const ::android::hardware::hidl_string& fqName, const ::android::hardware::hidl_string& name){
- ::android::hardware::Return<void> _hidl_out = ::android::hidl::manager::V1_0::BpHwServiceManager::_hidl_registerPassthroughClient(this, this, fqName, name);
- return _hidl_out;
- }
::android::hardware::Return<void> BpHwServiceManager::registerPassthroughClient(const ::android::hardware::hidl_string& fqName, const ::android::hardware::hidl_string& name){ ::android::hardware::Return<void> _hidl_out = ::android::hidl::manager::V1_0::BpHwServiceManager::_hidl_registerPassthroughClient(this, this, fqName, name); return _hidl_out; }
- ::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) {
- #ifdef __ANDROID_DEBUGGABLE__
- bool mEnableInstrumentation = _hidl_this_instrumentor->isInstrumentationEnabled();
- const auto &mInstrumentationCallbacks = _hidl_this_instrumentor->getInstrumentationCallbacks();
- #else
- (void) _hidl_this_instrumentor;
- #endif // __ANDROID_DEBUGGABLE__
- atrace_begin(ATRACE_TAG_HAL, ”HIDL::IServiceManager::registerPassthroughClient::client”);
- #ifdef __ANDROID_DEBUGGABLE__
- if (UNLIKELY(mEnableInstrumentation)) {
- std::vector<void *> _hidl_args;
- _hidl_args.push_back((void *)&fqName);
- _hidl_args.push_back((void *)&name);
- for (const auto &callback: mInstrumentationCallbacks) {
- callback(InstrumentationEvent::CLIENT_API_ENTRY, ”android.hidl.manager”, “1.0”, “IServiceManager”, “registerPassthroughClient”, &_hidl_args);
- }
- }
- #endif // __ANDROID_DEBUGGABLE__
- ::android::hardware::Parcel _hidl_data;
- ::android::hardware::Parcel _hidl_reply;
- ::android::status_t _hidl_err;
- ::android::hardware::Status _hidl_status;
- _hidl_err = _hidl_data.writeInterfaceToken(BpHwServiceManager::descriptor);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- size_t _hidl_fqName_parent;
- _hidl_err = _hidl_data.writeBuffer(&fqName, sizeof(fqName), &_hidl_fqName_parent);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- _hidl_err = ::android::hardware::writeEmbeddedToParcel(
- fqName,
- &_hidl_data,
- _hidl_fqName_parent,
- 0 /* parentOffset */);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- size_t _hidl_name_parent;
- _hidl_err = _hidl_data.writeBuffer(&name, sizeof(name), &_hidl_name_parent);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- _hidl_err = ::android::hardware::writeEmbeddedToParcel(
- name,
- &_hidl_data,
- _hidl_name_parent,
- 0 /* parentOffset */);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact(8 /* registerPassthroughClient */, _hidl_data, &_hidl_reply);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- if (!_hidl_status.isOk()) { return _hidl_status; }
- atrace_end(ATRACE_TAG_HAL);
- #ifdef __ANDROID_DEBUGGABLE__
- if (UNLIKELY(mEnableInstrumentation)) {
- std::vector<void *> _hidl_args;
- for (const auto &callback: mInstrumentationCallbacks) {
- callback(InstrumentationEvent::CLIENT_API_EXIT, ”android.hidl.manager”, “1.0”, “IServiceManager”, “registerPassthroughClient”, &_hidl_args);
- }
- }
- #endif // __ANDROID_DEBUGGABLE__
- _hidl_status.setFromStatusT(_hidl_err);
- return ::android::hardware::Return<void>();
- _hidl_error:
- _hidl_status.setFromStatusT(_hidl_err);
- return ::android::hardware::Return<void>(_hidl_status);
- }
::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) { #ifdef __ANDROID_DEBUGGABLE__ bool mEnableInstrumentation = _hidl_this_instrumentor->isInstrumentationEnabled(); const auto &mInstrumentationCallbacks = _hidl_this_instrumentor->getInstrumentationCallbacks(); #else (void) _hidl_this_instrumentor; #endif // __ANDROID_DEBUGGABLE__ atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::registerPassthroughClient::client"); #ifdef __ANDROID_DEBUGGABLE__ if (UNLIKELY(mEnableInstrumentation)) { std::vector<void *> _hidl_args; _hidl_args.push_back((void *)&fqName); _hidl_args.push_back((void *)&name); for (const auto &callback: mInstrumentationCallbacks) { callback(InstrumentationEvent::CLIENT_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args); } } #endif // __ANDROID_DEBUGGABLE__ ::android::hardware::Parcel _hidl_data; ::android::hardware::Parcel _hidl_reply; ::android::status_t _hidl_err; ::android::hardware::Status _hidl_status; _hidl_err = _hidl_data.writeInterfaceToken(BpHwServiceManager::descriptor); if (_hidl_err != ::android::OK) { goto _hidl_error; } size_t _hidl_fqName_parent; _hidl_err = _hidl_data.writeBuffer(&fqName, sizeof(fqName), &_hidl_fqName_parent); if (_hidl_err != ::android::OK) { goto _hidl_error; } _hidl_err = ::android::hardware::writeEmbeddedToParcel( fqName, &_hidl_data, _hidl_fqName_parent, 0 /* parentOffset */); if (_hidl_err != ::android::OK) { goto _hidl_error; } size_t _hidl_name_parent; _hidl_err = _hidl_data.writeBuffer(&name, sizeof(name), &_hidl_name_parent); if (_hidl_err != ::android::OK) { goto _hidl_error; } _hidl_err = ::android::hardware::writeEmbeddedToParcel( name, &_hidl_data, _hidl_name_parent, 0 /* parentOffset */); if (_hidl_err != ::android::OK) { goto _hidl_error; } _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact(8 /* registerPassthroughClient */, _hidl_data, &_hidl_reply); if (_hidl_err != ::android::OK) { goto _hidl_error; } _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply); if (_hidl_err != ::android::OK) { goto _hidl_error; } if (!_hidl_status.isOk()) { return _hidl_status; } atrace_end(ATRACE_TAG_HAL); #ifdef __ANDROID_DEBUGGABLE__ if (UNLIKELY(mEnableInstrumentation)) { std::vector<void *> _hidl_args; for (const auto &callback: mInstrumentationCallbacks) { callback(InstrumentationEvent::CLIENT_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args); } } #endif // __ANDROID_DEBUGGABLE__ _hidl_status.setFromStatusT(_hidl_err); return ::android::hardware::Return<void>(); _hidl_error: _hidl_status.setFromStatusT(_hidl_err); return ::android::hardware::Return<void>(_hidl_status); }这里和普通binder通信相同,先就需要传输的函数参数打包到Parcel对象中,然后调用binder代理对象的transact函数将函数参数,函数调用码发送到Server端进程,这里的_hidl_this其实指向的是BpHwServiceManager,这个是与业务相关的代理对象,通过asBinder函数得到与传输相关的binder代理,那这个binder代理是什么类型呢? 其实就是BpHwBinder,关于hwservicemanager代理对象的获取,asBinder函数的实现,在后续的章节中进行分析。经过BpHwServiceManager的请求,最终位于hwservicemanager进程中的BnHwServiceManager将接收函数调用请求:
- ::android::status_t BnHwServiceManager::onTransact(
- uint32_t _hidl_code,
- const ::android::hardware::Parcel &_hidl_data,
- ::android::hardware::Parcel *_hidl_reply,
- uint32_t _hidl_flags,
- TransactCallback _hidl_cb) {
- ::android::status_t _hidl_err = ::android::OK;
- switch (_hidl_code) {
- case 8 /* registerPassthroughClient */:
- {
- _hidl_err = ::android::hidl::manager::V1_0::BnHwServiceManager::_hidl_registerPassthroughClient(this, _hidl_data, _hidl_reply, _hidl_cb);
- break;
- }
- default:
- {
- return ::android::hidl::base::V1_0::BnHwBase::onTransact(
- _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb);
- }
- }
::android::status_t BnHwServiceManager::onTransact( uint32_t _hidl_code, const ::android::hardware::Parcel &_hidl_data, ::android::hardware::Parcel *_hidl_reply, uint32_t _hidl_flags, TransactCallback _hidl_cb) { ::android::status_t _hidl_err = ::android::OK; switch (_hidl_code) { case 8 /* registerPassthroughClient */: { _hidl_err = ::android::hidl::manager::V1_0::BnHwServiceManager::_hidl_registerPassthroughClient(this, _hidl_data, _hidl_reply, _hidl_cb); break; } default: { return ::android::hidl::base::V1_0::BnHwBase::onTransact( _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb); } }BnHwServiceManager将调用_hidl_registerPassthroughClient来执行Client端的注册。
- ::android::status_t BnHwServiceManager::_hidl_registerPassthroughClient(
- ::android::hidl::base::V1_0::BnHwBase* _hidl_this,
- const ::android::hardware::Parcel &_hidl_data,
- ::android::hardware::Parcel *_hidl_reply,
- TransactCallback _hidl_cb) {
- #ifdef __ANDROID_DEBUGGABLE__
- bool mEnableInstrumentation = _hidl_this->isInstrumentationEnabled();
- const auto &mInstrumentationCallbacks = _hidl_this->getInstrumentationCallbacks();
- #endif // __ANDROID_DEBUGGABLE__
- ::android::status_t _hidl_err = ::android::OK;
- if (!_hidl_data.enforceInterface(BnHwServiceManager::Pure::descriptor)) {
- _hidl_err = ::android::BAD_TYPE;
- return _hidl_err;
- }
- const ::android::hardware::hidl_string* fqName;
- const ::android::hardware::hidl_string* name;
- size_t _hidl_fqName_parent;
- _hidl_err = _hidl_data.readBuffer(sizeof(*fqName), &_hidl_fqName_parent, reinterpret_cast<const void **>(&fqName));
- if (_hidl_err != ::android::OK) { return _hidl_err; }
- _hidl_err = ::android::hardware::readEmbeddedFromParcel(
- const_cast<::android::hardware::hidl_string &>(*fqName),
- _hidl_data,
- _hidl_fqName_parent,
- 0 /* parentOffset */);
- if (_hidl_err != ::android::OK) { return _hidl_err; }
- size_t _hidl_name_parent;
- _hidl_err = _hidl_data.readBuffer(sizeof(*name), &_hidl_name_parent, reinterpret_cast<const void **>(&name));
- if (_hidl_err != ::android::OK) { return _hidl_err; }
- _hidl_err = ::android::hardware::readEmbeddedFromParcel(
- const_cast<::android::hardware::hidl_string &>(*name),
- _hidl_data,
- _hidl_name_parent,
- 0 /* parentOffset */);
- if (_hidl_err != ::android::OK) { return _hidl_err; }
- atrace_begin(ATRACE_TAG_HAL, ”HIDL::IServiceManager::registerPassthroughClient::server”);
- #ifdef __ANDROID_DEBUGGABLE__
- if (UNLIKELY(mEnableInstrumentation)) {
- std::vector<void *> _hidl_args;
- _hidl_args.push_back((void *)fqName);
- _hidl_args.push_back((void *)name);
- for (const auto &callback: mInstrumentationCallbacks) {
- callback(InstrumentationEvent::SERVER_API_ENTRY, ”android.hidl.manager”, “1.0”, “IServiceManager”, “registerPassthroughClient”, &_hidl_args);
- }
- }
- #endif // __ANDROID_DEBUGGABLE__
- static_cast<BnHwServiceManager*>(_hidl_this)->_hidl_mImpl->registerPassthroughClient(*fqName, *name);
- (void) _hidl_cb;
- atrace_end(ATRACE_TAG_HAL);
- #ifdef __ANDROID_DEBUGGABLE__
- if (UNLIKELY(mEnableInstrumentation)) {
- std::vector<void *> _hidl_args;
- for (const auto &callback: mInstrumentationCallbacks) {
- callback(InstrumentationEvent::SERVER_API_EXIT, ”android.hidl.manager”, “1.0”, “IServiceManager”, “registerPassthroughClient”, &_hidl_args);
- }
- }
- #endif // __ANDROID_DEBUGGABLE__
- ::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply);
- return _hidl_err;
- }
::android::status_t BnHwServiceManager::_hidl_registerPassthroughClient( ::android::hidl::base::V1_0::BnHwBase* _hidl_this, const ::android::hardware::Parcel &_hidl_data, ::android::hardware::Parcel *_hidl_reply, TransactCallback _hidl_cb) { #ifdef __ANDROID_DEBUGGABLE__ bool mEnableInstrumentation = _hidl_this->isInstrumentationEnabled(); const auto &mInstrumentationCallbacks = _hidl_this->getInstrumentationCallbacks(); #endif // __ANDROID_DEBUGGABLE__ ::android::status_t _hidl_err = ::android::OK; if (!_hidl_data.enforceInterface(BnHwServiceManager::Pure::descriptor)) { _hidl_err = ::android::BAD_TYPE; return _hidl_err; } const ::android::hardware::hidl_string* fqName; const ::android::hardware::hidl_string* name; size_t _hidl_fqName_parent; _hidl_err = _hidl_data.readBuffer(sizeof(*fqName), &_hidl_fqName_parent, reinterpret_cast<const void **>(&fqName)); if (_hidl_err != ::android::OK) { return _hidl_err; } _hidl_err = ::android::hardware::readEmbeddedFromParcel( const_cast<::android::hardware::hidl_string &>(*fqName), _hidl_data, _hidl_fqName_parent, 0 /* parentOffset */); if (_hidl_err != ::android::OK) { return _hidl_err; } size_t _hidl_name_parent; _hidl_err = _hidl_data.readBuffer(sizeof(*name), &_hidl_name_parent, reinterpret_cast<const void **>(&name)); if (_hidl_err != ::android::OK) { return _hidl_err; } _hidl_err = ::android::hardware::readEmbeddedFromParcel( const_cast<::android::hardware::hidl_string &>(*name), _hidl_data, _hidl_name_parent, 0 /* parentOffset */); if (_hidl_err != ::android::OK) { return _hidl_err; } atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::registerPassthroughClient::server"); #ifdef __ANDROID_DEBUGGABLE__ if (UNLIKELY(mEnableInstrumentation)) { std::vector<void *> _hidl_args; _hidl_args.push_back((void *)fqName); _hidl_args.push_back((void *)name); for (const auto &callback: mInstrumentationCallbacks) { callback(InstrumentationEvent::SERVER_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args); } } #endif // __ANDROID_DEBUGGABLE__ static_cast<BnHwServiceManager*>(_hidl_this)->_hidl_mImpl->registerPassthroughClient(*fqName, *name); (void) _hidl_cb; atrace_end(ATRACE_TAG_HAL); #ifdef __ANDROID_DEBUGGABLE__ if (UNLIKELY(mEnableInstrumentation)) { std::vector<void *> _hidl_args; for (const auto &callback: mInstrumentationCallbacks) { callback(InstrumentationEvent::SERVER_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "registerPassthroughClient", &_hidl_args); } } #endif // __ANDROID_DEBUGGABLE__ ::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply); return _hidl_err; }BnHwServiceManager首先读取BpHwServiceManager发送过来的函数参数,然后将registerPassthroughClient的执行转交个其成员变量的_hidl_mImpl对象,然后将执行结果返回给BpHwServiceManager,那么_hidl_mImpl保存的是什么对象呢? 其实_hidl_mImpl指向的是ServiceManager对象,这个是在构造BnHwServiceManager对象时传入的,在后续分析hwservicemanager启动过程时,会进行详细分析。
- Return<void> ServiceManager::registerPassthroughClient(const hidl_string &fqName,
- const hidl_string &name) {
- pid_t pid = IPCThreadState::self()->getCallingPid();
- if (!mAcl.canGet(fqName, pid)) { //根据Client端的pid及注册接口的包名,判断是否有权限注册
- /* We guard this function with “get”, because it’s typically used in
- * the getService() path, albeit for a passthrough service in this
- * case
- */
- return Void();
- }
- LOG(INFO) << ”registerPassthroughClient ” << fgName.c_str() << “ of ”
- << name.c_str()
- PackageInterfaceMap &ifaceMap = mServiceMap[fqName];
- if (name.empty()) {
- LOG(WARNING) << ”registerPassthroughClient encounters empty instance name for ”
- << fqName.c_str();
- return Void();
- }
- HidlService *service = ifaceMap.lookup(name);
- if (service == nullptr) {
- auto adding = std::make_unique<HidlService>(fqName, name);
- adding->registerPassthroughClient(pid);
- ifaceMap.insertService(std::move(adding));
- } else {
- service->registerPassthroughClient(pid);
- }
- return Void();
- }
Return<void> ServiceManager::registerPassthroughClient(const hidl_string &fqName, const hidl_string &name) { pid_t pid = IPCThreadState::self()->getCallingPid(); if (!mAcl.canGet(fqName, pid)) { //根据Client端的pid及注册接口的包名,判断是否有权限注册 /* We guard this function with "get", because it's typically used in * the getService() path, albeit for a passthrough service in this * case */ return Void(); } LOG(INFO) << "registerPassthroughClient " << fgName.c_str() << " of " << name.c_str() PackageInterfaceMap &ifaceMap = mServiceMap[fqName]; if (name.empty()) { LOG(WARNING) << "registerPassthroughClient encounters empty instance name for " << fqName.c_str(); return Void(); } HidlService *service = ifaceMap.lookup(name); if (service == nullptr) { auto adding = std::make_unique<HidlService>(fqName, name); adding->registerPassthroughClient(pid); ifaceMap.insertService(std::move(adding)); } else { service->registerPassthroughClient(pid); } return Void(); }首先根据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
- HidlService(const std::string &interfaceName,
- const std::string &instanceName)
- : HidlService(
- interfaceName,
- instanceName,
- nullptr,
- static_cast<pid_t>(IServiceManager::PidConstant::NO_PID))
- {}
HidlService(const std::string &interfaceName, const std::string &instanceName) : HidlService( interfaceName, instanceName, nullptr, static_cast<pid_t>(IServiceManager::PidConstant::NO_PID)) {}
registerAsService注册
registerAsService用于向hwservicemanager注册IBase对象,由于前面通过PassthroughServiceManager得到的HwcHal继承于IBase,因此可以调用registerAsService函数来注册。- ::android::status_t IComposer::registerAsService(const std::string &serviceName) {
- ::android::hardware::details::onRegistration(”[email protected]”, “IComposer”, serviceName);
- const ::android::sp<::android::hidl::manager::V1_0::IServiceManager> sm
- = ::android::hardware::defaultServiceManager();
- if (sm == nullptr) {
- return ::android::INVALID_OPERATION;
- }
- ::android::hardware::Return<bool> ret = sm->add(serviceName.c_str(), this);
- return ret.isOk() && ret ? ::android::OK : ::android::UNKNOWN_ERROR;
- }
::android::status_t IComposer::registerAsService(const std::string &serviceName) { ::android::hardware::details::onRegistration("[email protected]", "IComposer", serviceName); const ::android::sp<::android::hidl::manager::V1_0::IServiceManager> sm = ::android::hardware::defaultServiceManager(); if (sm == nullptr) { return ::android::INVALID_OPERATION; } ::android::hardware::Return<bool> ret = sm->add(serviceName.c_str(), this); return ret.isOk() && ret ? ::android::OK : ::android::UNKNOWN_ERROR; }首先执行onRegistration函数,然后调用hwservicemanager的代理对象的add函数。
- void onRegistration(const std::string &packageName,
- const std::string& /* interfaceName */,
- const std::string& /* instanceName */) {
- tryShortenProcessName(packageName);
- }
void onRegistration(const std::string &packageName, const std::string& /* interfaceName */, const std::string& /* instanceName */) { tryShortenProcessName(packageName); }
- void tryShortenProcessName(const std::string &packageName) {
- std::string processName = binaryName();
- if (!startsWith(processName, packageName)) {
- return;
- }
- // e.x. [email protected] -> [email protected]
- size_t lastDot = packageName.rfind(‘.’);
- size_t secondDot = packageName.rfind(‘.’, lastDot - 1);
- if (secondDot == std::string::npos) {
- return;
- }
- std::string newName = processName.substr(secondDot + 1,
- 16 /* TASK_COMM_LEN */ - 1);
- ALOGI(”Removing namespace from process name %s to %s.”,
- processName.c_str(), newName.c_str());
- int rc = pthread_setname_np(pthread_self(), newName.c_str());
- ALOGI_IF(rc != 0, ”Removing namespace from process name %s failed.”,
- processName.c_str());
- }
void tryShortenProcessName(const std::string &packageName) { std::string processName = binaryName(); if (!startsWith(processName, packageName)) { return; } // e.x. [email protected] -> [email protected] size_t lastDot = packageName.rfind('.'); size_t secondDot = packageName.rfind('.', lastDot - 1); if (secondDot == std::string::npos) { return; } std::string newName = processName.substr(secondDot + 1, 16 /* TASK_COMM_LEN */ - 1); ALOGI("Removing namespace from process name %s to %s.", processName.c_str(), newName.c_str()); int rc = pthread_setname_np(pthread_self(), newName.c_str()); ALOGI_IF(rc != 0, "Removing namespace from process name %s failed.", processName.c_str()); }这里只是简单的修改了当前进程的名称。
[email protected]_genc++\gen\android\hidl\manager\1.0\ServiceManagerAll.cpp
- ::android::hardware::Return<bool> BpHwServiceManager::add(const ::android::hardware::hidl_string& name, const ::android::sp<::android::hidl::base::V1_0::IBase>& service){
- ::android::hardware::Return<bool> _hidl_out = ::android::hidl::manager::V1_0::BpHwServiceManager::_hidl_add(this, this, name, service);
- return _hidl_out;
- }
::android::hardware::Return<bool> BpHwServiceManager::add(const ::android::hardware::hidl_string& name, const ::android::sp<::android::hidl::base::V1_0::IBase>& service){ ::android::hardware::Return<bool> _hidl_out = ::android::hidl::manager::V1_0::BpHwServiceManager::_hidl_add(this, this, name, service); return _hidl_out; }
- ::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) {
- #ifdef __ANDROID_DEBUGGABLE__
- bool mEnableInstrumentation = _hidl_this_instrumentor->isInstrumentationEnabled();
- const auto &mInstrumentationCallbacks = _hidl_this_instrumentor->getInstrumentationCallbacks();
- #else
- (void) _hidl_this_instrumentor;
- #endif // __ANDROID_DEBUGGABLE__
- atrace_begin(ATRACE_TAG_HAL, ”HIDL::IServiceManager::add::client”);
- #ifdef __ANDROID_DEBUGGABLE__
- if (UNLIKELY(mEnableInstrumentation)) {
- std::vector<void *> _hidl_args;
- _hidl_args.push_back((void *)&name);
- _hidl_args.push_back((void *)&service);
- for (const auto &callback: mInstrumentationCallbacks) {
- callback(InstrumentationEvent::CLIENT_API_ENTRY, ”android.hidl.manager”, “1.0”, “IServiceManager”, “add”, &_hidl_args);
- }
- }
- #endif // __ANDROID_DEBUGGABLE__
- ::android::hardware::Parcel _hidl_data;
- ::android::hardware::Parcel _hidl_reply;
- ::android::status_t _hidl_err;
- ::android::hardware::Status _hidl_status;
- bool _hidl_out_success;
- _hidl_err = _hidl_data.writeInterfaceToken(BpHwServiceManager::descriptor);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- size_t _hidl_name_parent;
- _hidl_err = _hidl_data.writeBuffer(&name, sizeof(name), &_hidl_name_parent);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- _hidl_err = ::android::hardware::writeEmbeddedToParcel(
- name,
- &_hidl_data,
- _hidl_name_parent,
- 0 /* parentOffset */);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- if (service == nullptr) {
- _hidl_err = _hidl_data.writeStrongBinder(nullptr);
- } else {
- ::android::sp<::android::hardware::IBinder> _hidl_binder = ::android::hardware::toBinder<
- ::android::hidl::base::V1_0::IBase>(service);
- if (_hidl_binder.get() != nullptr) {
- _hidl_err = _hidl_data.writeStrongBinder(_hidl_binder);
- } else {
- _hidl_err = ::android::UNKNOWN_ERROR;
- }
- }
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- ::android::hardware::ProcessState::self()->startThreadPool();
- _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact(2 /* add */, _hidl_data, &_hidl_reply);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- if (!_hidl_status.isOk()) { return _hidl_status; }
- _hidl_err = _hidl_reply.readBool(&_hidl_out_success);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- atrace_end(ATRACE_TAG_HAL);
- #ifdef __ANDROID_DEBUGGABLE__
- if (UNLIKELY(mEnableInstrumentation)) {
- std::vector<void *> _hidl_args;
- _hidl_args.push_back((void *)&_hidl_out_success);
- for (const auto &callback: mInstrumentationCallbacks) {
- callback(InstrumentationEvent::CLIENT_API_EXIT, ”android.hidl.manager”, “1.0”, “IServiceManager”, “add”, &_hidl_args);
- }
- }
- #endif // __ANDROID_DEBUGGABLE__
- _hidl_status.setFromStatusT(_hidl_err);
- return ::android::hardware::Return<bool>(_hidl_out_success);
- _hidl_error:
- _hidl_status.setFromStatusT(_hidl_err);
- return ::android::hardware::Return<bool>(_hidl_status);
- }
::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) { #ifdef __ANDROID_DEBUGGABLE__ bool mEnableInstrumentation = _hidl_this_instrumentor->isInstrumentationEnabled(); const auto &mInstrumentationCallbacks = _hidl_this_instrumentor->getInstrumentationCallbacks(); #else (void) _hidl_this_instrumentor; #endif // __ANDROID_DEBUGGABLE__ atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::add::client"); #ifdef __ANDROID_DEBUGGABLE__ if (UNLIKELY(mEnableInstrumentation)) { std::vector<void *> _hidl_args; _hidl_args.push_back((void *)&name); _hidl_args.push_back((void *)&service); for (const auto &callback: mInstrumentationCallbacks) { callback(InstrumentationEvent::CLIENT_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args); } } #endif // __ANDROID_DEBUGGABLE__ ::android::hardware::Parcel _hidl_data; ::android::hardware::Parcel _hidl_reply; ::android::status_t _hidl_err; ::android::hardware::Status _hidl_status; bool _hidl_out_success; _hidl_err = _hidl_data.writeInterfaceToken(BpHwServiceManager::descriptor); if (_hidl_err != ::android::OK) { goto _hidl_error; } size_t _hidl_name_parent; _hidl_err = _hidl_data.writeBuffer(&name, sizeof(name), &_hidl_name_parent); if (_hidl_err != ::android::OK) { goto _hidl_error; } _hidl_err = ::android::hardware::writeEmbeddedToParcel( name, &_hidl_data, _hidl_name_parent, 0 /* parentOffset */); if (_hidl_err != ::android::OK) { goto _hidl_error; } if (service == nullptr) { _hidl_err = _hidl_data.writeStrongBinder(nullptr); } else { ::android::sp<::android::hardware::IBinder> _hidl_binder = ::android::hardware::toBinder< ::android::hidl::base::V1_0::IBase>(service); if (_hidl_binder.get() != nullptr) { _hidl_err = _hidl_data.writeStrongBinder(_hidl_binder); } else { _hidl_err = ::android::UNKNOWN_ERROR; } } if (_hidl_err != ::android::OK) { goto _hidl_error; } ::android::hardware::ProcessState::self()->startThreadPool(); _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact(2 /* add */, _hidl_data, &_hidl_reply); if (_hidl_err != ::android::OK) { goto _hidl_error; } _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply); if (_hidl_err != ::android::OK) { goto _hidl_error; } if (!_hidl_status.isOk()) { return _hidl_status; } _hidl_err = _hidl_reply.readBool(&_hidl_out_success); if (_hidl_err != ::android::OK) { goto _hidl_error; } atrace_end(ATRACE_TAG_HAL); #ifdef __ANDROID_DEBUGGABLE__ if (UNLIKELY(mEnableInstrumentation)) { std::vector<void *> _hidl_args; _hidl_args.push_back((void *)&_hidl_out_success); for (const auto &callback: mInstrumentationCallbacks) { callback(InstrumentationEvent::CLIENT_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args); } } #endif // __ANDROID_DEBUGGABLE__ _hidl_status.setFromStatusT(_hidl_err); return ::android::hardware::Return<bool>(_hidl_out_success); _hidl_error: _hidl_status.setFromStatusT(_hidl_err); return ::android::hardware::Return<bool>(_hidl_status); }这里的步骤和前面的registerPassthroughClient基本一致,唯一不同的是,此时需要向Server端hwservicemanager传输一个IBase对象。
- ::android::sp<::android::hardware::IBinder> _hidl_binder = ::android::hardware::toBinder<
- ::android::hidl::base::V1_0::IBase>(service);
- if (_hidl_binder.get() != nullptr) {
- _hidl_err = _hidl_data.writeStrongBinder(_hidl_binder);
- }
::android::sp<::android::hardware::IBinder> _hidl_binder = ::android::hardware::toBinder< ::android::hidl::base::V1_0::IBase>(service); if (_hidl_binder.get() != nullptr) { _hidl_err = _hidl_data.writeStrongBinder(_hidl_binder); }这里首先通过toBinder函数将IBase对象,其实就是HwcHal对象转换为IBinder对象,然后通过writeStrongBinder将IBinder对象序列化到Parcel中,toBinder函数在后续进行分析,我们这里只需要知道经过toBinder函数后,在Hal进程端会创建一个BnHwComposer本地binder对象,然后通过IPC调用发送给hwservicemanager。
- ::android::status_t BnHwServiceManager::onTransact(
- uint32_t _hidl_code,
- const ::android::hardware::Parcel &_hidl_data,
- ::android::hardware::Parcel *_hidl_reply,
- uint32_t _hidl_flags,
- TransactCallback _hidl_cb) {
- ::android::status_t _hidl_err = ::android::OK;
- switch (_hidl_code) {
- case 2 /* add */:
- {
- _hidl_err = ::android::hidl::manager::V1_0::BnHwServiceManager::_hidl_add(this, _hidl_data, _hidl_reply, _hidl_cb);
- break;
- }
- default:
- {
- return ::android::hidl::base::V1_0::BnHwBase::onTransact(
- _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb);
- }
- }
- if (_hidl_err == ::android::UNEXPECTED_NULL) {
- _hidl_err = ::android::hardware::writeToParcel(
- ::android::hardware::Status::fromExceptionCode(::android::hardware::Status::EX_NULL_POINTER),
- _hidl_reply);
- }return _hidl_err;
- }
::android::status_t BnHwServiceManager::onTransact( uint32_t _hidl_code, const ::android::hardware::Parcel &_hidl_data, ::android::hardware::Parcel *_hidl_reply, uint32_t _hidl_flags, TransactCallback _hidl_cb) { ::android::status_t _hidl_err = ::android::OK; switch (_hidl_code) { case 2 /* add */: { _hidl_err = ::android::hidl::manager::V1_0::BnHwServiceManager::_hidl_add(this, _hidl_data, _hidl_reply, _hidl_cb); break; } default: { return ::android::hidl::base::V1_0::BnHwBase::onTransact( _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb); } } if (_hidl_err == ::android::UNEXPECTED_NULL) { _hidl_err = ::android::hardware::writeToParcel( ::android::hardware::Status::fromExceptionCode(::android::hardware::Status::EX_NULL_POINTER), _hidl_reply); }return _hidl_err; }
- ::android::status_t BnHwServiceManager::_hidl_add(
- ::android::hidl::base::V1_0::BnHwBase* _hidl_this,
- const ::android::hardware::Parcel &_hidl_data,
- ::android::hardware::Parcel *_hidl_reply,
- TransactCallback _hidl_cb) {
- #ifdef __ANDROID_DEBUGGABLE__
- bool mEnableInstrumentation = _hidl_this->isInstrumentationEnabled();
- const auto &mInstrumentationCallbacks = _hidl_this->getInstrumentationCallbacks();
- #endif // __ANDROID_DEBUGGABLE__
- ::android::status_t _hidl_err = ::android::OK;
- if (!_hidl_data.enforceInterface(BnHwServiceManager::Pure::descriptor)) {
- _hidl_err = ::android::BAD_TYPE;
- return _hidl_err;
- }
- const ::android::hardware::hidl_string* name;
- ::android::sp<::android::hidl::base::V1_0::IBase> service;
- size_t _hidl_name_parent;
- <span style=”color:#FF0000;”> <span style=“color:#000000;”>_hidl_err = _hidl_data.readBuffer(sizeof(*name), &_hidl_name_parent, reinterpret_cast<const void **>(&name));</span></span>
- if (_hidl_err != ::android::OK) { return _hidl_err; }
- _hidl_err = ::android::hardware::readEmbeddedFromParcel(
- const_cast<::android::hardware::hidl_string &>(*name),
- _hidl_data,
- _hidl_name_parent,
- 0 /* parentOffset */);
- if (_hidl_err != ::android::OK) { return _hidl_err; }
- {
- ::android::sp<::android::hardware::IBinder> _hidl_service_binder;
- _hidl_err = _hidl_data.readNullableStrongBinder(&_hidl_service_binder);
- if (_hidl_err != ::android::OK) { return _hidl_err; }
- 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);
- }
- atrace_begin(ATRACE_TAG_HAL, ”HIDL::IServiceManager::add::server”);
- #ifdef __ANDROID_DEBUGGABLE__
- if (UNLIKELY(mEnableInstrumentation)) {
- std::vector<void *> _hidl_args;
- _hidl_args.push_back((void *)name);
- _hidl_args.push_back((void *)&service);
- for (const auto &callback: mInstrumentationCallbacks) {
- callback(InstrumentationEvent::SERVER_API_ENTRY, ”android.hidl.manager”, “1.0”, “IServiceManager”, “add”, &_hidl_args);
- }
- }
- #endif // __ANDROID_DEBUGGABLE__
- bool _hidl_out_success = static_cast<BnHwServiceManager*>(_hidl_this)->_hidl_mImpl->add(*name, service);
- ::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply);
- _hidl_err = _hidl_reply->writeBool(_hidl_out_success);
- /* _hidl_err ignored! */
- atrace_end(ATRACE_TAG_HAL);
- #ifdef __ANDROID_DEBUGGABLE__
- if (UNLIKELY(mEnableInstrumentation)) {
- std::vector<void *> _hidl_args;
- _hidl_args.push_back((void *)&_hidl_out_success);
- for (const auto &callback: mInstrumentationCallbacks) {
- callback(InstrumentationEvent::SERVER_API_EXIT, ”android.hidl.manager”, “1.0”, “IServiceManager”, “add”, &_hidl_args);
- }
- }
- #endif // __ANDROID_DEBUGGABLE__
- _hidl_cb(*_hidl_reply);
- return _hidl_err;
- }
::android::status_t BnHwServiceManager::_hidl_add(
::android::hidl::base::V1_0::BnHwBase* _hidl_this,
const ::android::hardware::Parcel &_hidl_data,
::android::hardware::Parcel *_hidl_reply,
TransactCallback _hidl_cb) {
#ifdef __ANDROID_DEBUGGABLE__
bool mEnableInstrumentation = _hidl_this->isInstrumentationEnabled();
const auto &mInstrumentationCallbacks = _hidl_this->getInstrumentationCallbacks();
#endif // __ANDROID_DEBUGGABLE__
::android::status_t _hidl_err = ::android::OK;
if (!_hidl_data.enforceInterface(BnHwServiceManager::Pure::descriptor)) {
_hidl_err = ::android::BAD_TYPE;
return _hidl_err;
}
const ::android::hardware::hidl_string* name;
::android::sp<::android::hidl::base::V1_0::IBase> service;
size_t _hidl_name_parent;
_hidl_err = _hidl_data.readBuffer(sizeof(*name), &_hidl_name_parent, reinterpret_cast<const void **>(&name));
if (_hidl_err != ::android::OK) { return _hidl_err; }
_hidl_err = ::android::hardware::readEmbeddedFromParcel(
const_cast<::android::hardware::hidl_string &>(*name),
_hidl_data,
_hidl_name_parent,
0 /* parentOffset */);
if (_hidl_err != ::android::OK) { return _hidl_err; }
{
::android::sp<::android::hardware::IBinder> _hidl_service_binder;
_hidl_err = _hidl_data.readNullableStrongBinder(&_hidl_service_binder);
if (_hidl_err != ::android::OK) { return _hidl_err; }
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);
}
atrace_begin(ATRACE_TAG_HAL, "HIDL::IServiceManager::add::server");
#ifdef __ANDROID_DEBUGGABLE__
if (UNLIKELY(mEnableInstrumentation)) {
std::vector<void *> _hidl_args;
_hidl_args.push_back((void *)name);
_hidl_args.push_back((void *)&service);
for (const auto &callback: mInstrumentationCallbacks) {
callback(InstrumentationEvent::SERVER_API_ENTRY, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args);
}
}
#endif // __ANDROID_DEBUGGABLE__
bool _hidl_out_success = static_cast<BnHwServiceManager*>(_hidl_this)->_hidl_mImpl->add(*name, service);
::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply);
_hidl_err = _hidl_reply->writeBool(_hidl_out_success);
/* _hidl_err ignored! */
atrace_end(ATRACE_TAG_HAL);
#ifdef __ANDROID_DEBUGGABLE__
if (UNLIKELY(mEnableInstrumentation)) {
std::vector<void *> _hidl_args;
_hidl_args.push_back((void *)&_hidl_out_success);
for (const auto &callback: mInstrumentationCallbacks) {
callback(InstrumentationEvent::SERVER_API_EXIT, "android.hidl.manager", "1.0", "IServiceManager", "add", &_hidl_args);
}
}
#endif // __ANDROID_DEBUGGABLE__
_hidl_cb(*_hidl_reply);
return _hidl_err;
}
hwservicemanager进程通过_hidl_err = _hidl_data.readNullableStrongBinder(&_hidl_service_binder);拿到client进程发送过来的BnHwComposer对象,binder实体到达目的端进程将变为binder代理对象,然后通过fromBinder函数将binder代理对象转换为业务代理对象BpHwBase,这个过程在后续进行详细分析,接下来继续调用_hidl_mImpl的add函数,而我们知道_hidl_mImpl其实就是ServiceManager:
- Return<bool> ServiceManager::add(const hidl_string& name, const sp<IBase>& service) {
- bool isValidService = false;
- if (service == nullptr) {
- return false;
- }
- LOG(INFO) << ”register service ” << name;
- // TODO(b/34235311): use HIDL way to determine this
- // also, this assumes that the PID that is registering is the pid that is the service
- pid_t pid = IPCThreadState::self()->getCallingPid();
- auto ret = service->interfaceChain([&](const auto &interfaceChain) {
- if (interfaceChain.size() == 0) {
- return;
- }
- …
- });
- if (!ret.isOk()) {
- LOG(ERROR) << ”Failed to retrieve interface chain.”;
- return false;
- }
- return isValidService;
- }
Return<bool> ServiceManager::add(const hidl_string& name, const sp<IBase>& service) { bool isValidService = false; if (service == nullptr) { return false; } LOG(INFO) << "register service " << name; // TODO(b/34235311): use HIDL way to determine this // also, this assumes that the PID that is registering is the pid that is the service pid_t pid = IPCThreadState::self()->getCallingPid(); auto ret = service->interfaceChain([&](const auto &interfaceChain) { if (interfaceChain.size() == 0) { return; } ... }); if (!ret.isOk()) { LOG(ERROR) << "Failed to retrieve interface chain."; return false; } return isValidService; }接着调用interfaceChain函数并传入一个函数回调,由于此时service是BpHwBase对象,BpHwBase的interfaceChain函数实现如下:
- ::android::hardware::Return<void> BpHwBase::interfaceChain(interfaceChain_cb _hidl_cb){
- ::android::hardware::Return<void> _hidl_out = ::android::hidl::base::V1_0::BpHwBase::_hidl_interfaceChain(this, this, _hidl_cb);
- return _hidl_out;
- }
::android::hardware::Return<void> BpHwBase::interfaceChain(interfaceChain_cb _hidl_cb){ ::android::hardware::Return<void> _hidl_out = ::android::hidl::base::V1_0::BpHwBase::_hidl_interfaceChain(this, this, _hidl_cb); return _hidl_out; }
- ::android::hardware::Return<void> BpHwBase::_hidl_interfaceChain(::android::hardware::IInterface *_hidl_this, ::android::hardware::details::HidlInstrumentor *_hidl_this_instrumentor, interfaceChain_cb _hidl_cb) {
- #ifdef __ANDROID_DEBUGGABLE__
- bool mEnableInstrumentation = _hidl_this_instrumentor->isInstrumentationEnabled();
- const auto &mInstrumentationCallbacks = _hidl_this_instrumentor->getInstrumentationCallbacks();
- #else
- (void) _hidl_this_instrumentor;
- #endif // __ANDROID_DEBUGGABLE__
- if (_hidl_cb == nullptr) {
- return ::android::hardware::Status::fromExceptionCode(
- ::android::hardware::Status::EX_ILLEGAL_ARGUMENT,
- ”Null synchronous callback passed.”);
- }
- atrace_begin(ATRACE_TAG_HAL, ”HIDL::IBase::interfaceChain::client”);
- #ifdef __ANDROID_DEBUGGABLE__
- if (UNLIKELY(mEnableInstrumentation)) {
- std::vector<void *> _hidl_args;
- for (const auto &callback: mInstrumentationCallbacks) {
- callback(InstrumentationEvent::CLIENT_API_ENTRY, ”android.hidl.base”, “1.0”, “IBase”, “interfaceChain”, &_hidl_args);
- }
- }
- #endif // __ANDROID_DEBUGGABLE__
- ::android::hardware::Parcel _hidl_data;
- ::android::hardware::Parcel _hidl_reply;
- ::android::status_t _hidl_err;
- ::android::hardware::Status _hidl_status;
- const ::android::hardware::hidl_vec<::android::hardware::hidl_string>* _hidl_out_descriptors;
- <span style=”color:#FF0000;”> <span style=“color:#000000;”> _hidl_err = _hidl_data.writeInterfaceToken(BpHwBase::descriptor);</span></span>
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- _hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact(256067662 /* interfaceChain */, _hidl_data, &_hidl_reply);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- _hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- if (!_hidl_status.isOk()) { return _hidl_status; }
- size_t _hidl__hidl_out_descriptors_parent;
- _hidl_err = _hidl_reply.readBuffer(sizeof(*_hidl_out_descriptors), &_hidl__hidl_out_descriptors_parent, reinterpret_cast<const void **>(&_hidl_out_descriptors));
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- size_t _hidl__hidl_out_descriptors_child;
- _hidl_err = ::android::hardware::readEmbeddedFromParcel(
- const_cast<::android::hardware::hidl_vec<::android::hardware::hidl_string> &>(*_hidl_out_descriptors),
- _hidl_reply,
- _hidl__hidl_out_descriptors_parent,
- 0 /* parentOffset */, &_hidl__hidl_out_descriptors_child);
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- for (size_t _hidl_index_0 = 0; _hidl_index_0 < _hidl_out_descriptors->size(); ++_hidl_index_0) {
- _hidl_err = ::android::hardware::readEmbeddedFromParcel(
- const_cast<::android::hardware::hidl_string &>((*_hidl_out_descriptors)[_hidl_index_0]),
- _hidl_reply,
- _hidl__hidl_out_descriptors_child,
- _hidl_index_0 * sizeof(::android::hardware::hidl_string));
- if (_hidl_err != ::android::OK) { goto _hidl_error; }
- }
- _hidl_cb(*_hidl_out_descriptors);
- atrace_end(ATRACE_TAG_HAL);
- #ifdef __ANDROID_DEBUGGABLE__
- if (UNLIKELY(mEnableInstrumentation)) {
- std::vector<void *> _hidl_args;
- _hidl_args.push_back((void *)_hidl_out_descriptors);
- for (const auto &callback: mInstrumentationCallbacks) {
- callback(InstrumentationEvent::CLIENT_API_EXIT, ”android.hidl.base”, “1.0”, “IBase”, “interfaceChain”, &_hidl_args);
- }
- }
- #endif // __ANDROID_DEBUGGABLE__
- _hidl_status.setFromStatusT(_hidl_err);
- return ::android::hardware::Return<void>();
- _hidl_error:
- _hidl_status.setFromStatusT(_hidl_err);
- return ::android::hardware::Return<void>(_hidl_status);
- }
::android::hardware::Return<void> BpHwBase::_hidl_interfaceChain(::android::hardware::IInterface *_hidl_this, ::android::hardware::details::HidlInstrumentor *_hidl_this_instrumentor, interfaceChain_cb _hidl_cb) {
#ifdef __ANDROID_DEBUGGABLE__
bool mEnableInstrumentation = _hidl_this_instrumentor->isInstrumentationEnabled();
const auto &mInstrumentationCallbacks = _hidl_this_instrumentor->getInstrumentationCallbacks();
#else
(void) _hidl_this_instrumentor;
#endif // __ANDROID_DEBUGGABLE__
if (_hidl_cb == nullptr) {
return ::android::hardware::Status::fromExceptionCode(
::android::hardware::Status::EX_ILLEGAL_ARGUMENT,
"Null synchronous callback passed.");
}
atrace_begin(ATRACE_TAG_HAL, "HIDL::IBase::interfaceChain::client");
#ifdef __ANDROID_DEBUGGABLE__
if (UNLIKELY(mEnableInstrumentation)) {
std::vector<void *> _hidl_args;
for (const auto &callback: mInstrumentationCallbacks) {
callback(InstrumentationEvent::CLIENT_API_ENTRY, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args);
}
}
#endif // __ANDROID_DEBUGGABLE__
::android::hardware::Parcel _hidl_data;
::android::hardware::Parcel _hidl_reply;
::android::status_t _hidl_err;
::android::hardware::Status _hidl_status;
const ::android::hardware::hidl_vec<::android::hardware::hidl_string>* _hidl_out_descriptors;
_hidl_err = _hidl_data.writeInterfaceToken(BpHwBase::descriptor);
if (_hidl_err != ::android::OK) { goto _hidl_error; }
_hidl_err = ::android::hardware::IInterface::asBinder(_hidl_this)->transact(256067662 /* interfaceChain */, _hidl_data, &_hidl_reply);
if (_hidl_err != ::android::OK) { goto _hidl_error; }
_hidl_err = ::android::hardware::readFromParcel(&_hidl_status, _hidl_reply);
if (_hidl_err != ::android::OK) { goto _hidl_error; }
if (!_hidl_status.isOk()) { return _hidl_status; }
size_t _hidl__hidl_out_descriptors_parent;
_hidl_err = _hidl_reply.readBuffer(sizeof(*_hidl_out_descriptors), &_hidl__hidl_out_descriptors_parent, reinterpret_cast<const void **>(&_hidl_out_descriptors));
if (_hidl_err != ::android::OK) { goto _hidl_error; }
size_t _hidl__hidl_out_descriptors_child;
_hidl_err = ::android::hardware::readEmbeddedFromParcel(
const_cast<::android::hardware::hidl_vec<::android::hardware::hidl_string> &>(*_hidl_out_descriptors),
_hidl_reply,
_hidl__hidl_out_descriptors_parent,
0 /* parentOffset */, &_hidl__hidl_out_descriptors_child);
if (_hidl_err != ::android::OK) { goto _hidl_error; }
for (size_t _hidl_index_0 = 0; _hidl_index_0 < _hidl_out_descriptors->size(); ++_hidl_index_0) {
_hidl_err = ::android::hardware::readEmbeddedFromParcel(
const_cast<::android::hardware::hidl_string &>((*_hidl_out_descriptors)[_hidl_index_0]),
_hidl_reply,
_hidl__hidl_out_descriptors_child,
_hidl_index_0 * sizeof(::android::hardware::hidl_string));
if (_hidl_err != ::android::OK) { goto _hidl_error; }
}
_hidl_cb(*_hidl_out_descriptors);
atrace_end(ATRACE_TAG_HAL);
#ifdef __ANDROID_DEBUGGABLE__
if (UNLIKELY(mEnableInstrumentation)) {
std::vector<void *> _hidl_args;
_hidl_args.push_back((void *)_hidl_out_descriptors);
for (const auto &callback: mInstrumentationCallbacks) {
callback(InstrumentationEvent::CLIENT_API_EXIT, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args);
}
}
#endif // __ANDROID_DEBUGGABLE__
_hidl_status.setFromStatusT(_hidl_err);
return ::android::hardware::Return<void>();
_hidl_error:
_hidl_status.setFromStatusT(_hidl_err);
return ::android::hardware::Return<void>(_hidl_status);
}
这里再次回到Hal进程空间,调用BnHwComposer的interfaceChain函数查询_hidl_out_descriptors,
composer\2.1\[email protected]_genc++\gen\android\hardware\graphics\composer\2.1\ComposerAll.cpp
- ::android::status_t BnHwComposer::onTransact(
- uint32_t _hidl_code,
- const ::android::hardware::Parcel &_hidl_data,
- ::android::hardware::Parcel *_hidl_reply,
- uint32_t _hidl_flags,
- TransactCallback _hidl_cb) {
- ::android::status_t _hidl_err = ::android::OK;
- switch (_hidl_code) {
- case 256067662 /* interfaceChain */:
- {
- _hidl_err = ::android::hidl::base::V1_0::BnHwBase::_hidl_interfaceChain(this, _hidl_data, _hidl_reply, _hidl_cb);
- break;
- }
- default:
- {
- return ::android::hidl::base::V1_0::BnHwBase::onTransact(
- _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb);
- }
- }
- if (_hidl_err == ::android::UNEXPECTED_NULL) {
- _hidl_err = ::android::hardware::writeToParcel(
- ::android::hardware::Status::fromExceptionCode(::android::hardware::Status::EX_NULL_POINTER),
- _hidl_reply);
- }return _hidl_err;
- }
::android::status_t BnHwComposer::onTransact( uint32_t _hidl_code, const ::android::hardware::Parcel &_hidl_data, ::android::hardware::Parcel *_hidl_reply, uint32_t _hidl_flags, TransactCallback _hidl_cb) { ::android::status_t _hidl_err = ::android::OK; switch (_hidl_code) { case 256067662 /* interfaceChain */: { _hidl_err = ::android::hidl::base::V1_0::BnHwBase::_hidl_interfaceChain(this, _hidl_data, _hidl_reply, _hidl_cb); break; } default: { return ::android::hidl::base::V1_0::BnHwBase::onTransact( _hidl_code, _hidl_data, _hidl_reply, _hidl_flags, _hidl_cb); } } if (_hidl_err == ::android::UNEXPECTED_NULL) { _hidl_err = ::android::hardware::writeToParcel( ::android::hardware::Status::fromExceptionCode(::android::hardware::Status::EX_NULL_POINTER), _hidl_reply); }return _hidl_err; }注意,onTransact的最后一个参数是一个回调函数,是由IPCThreadState传递进来的,该回调函数将传入BnHwBase的interfaceChain中执行。这个实现由其父类BnHwBase来完成:
- ::android::status_t BnHwBase::_hidl_interfaceChain(
- BnHwBase* _hidl_this,
- const ::android::hardware::Parcel &_hidl_data,
- ::android::hardware::Parcel *_hidl_reply,
- TransactCallback _hidl_cb) {
- #ifdef __ANDROID_DEBUGGABLE__
- bool mEnableInstrumentation = _hidl_this->isInstrumentationEnabled();
- const auto &mInstrumentationCallbacks = _hidl_this->getInstrumentationCallbacks();
- #endif // __ANDROID_DEBUGGABLE__
- ::android::status_t _hidl_err = ::android::OK;
- if (!_hidl_data.enforceInterface(BnHwBase::Pure::descriptor)) {
- _hidl_err = ::android::BAD_TYPE;
- return _hidl_err;
- }
- atrace_begin(ATRACE_TAG_HAL, ”HIDL::IBase::interfaceChain::server”);
- #ifdef __ANDROID_DEBUGGABLE__
- if (UNLIKELY(mEnableInstrumentation)) {
- std::vector<void *> _hidl_args;
- for (const auto &callback: mInstrumentationCallbacks) {
- callback(InstrumentationEvent::SERVER_API_ENTRY, ”android.hidl.base”, “1.0”, “IBase”, “interfaceChain”, &_hidl_args);
- }
- }
- #endif // __ANDROID_DEBUGGABLE__
- bool _hidl_callbackCalled = false;
- static_cast<BnHwBase*>(_hidl_this)->_hidl_mImpl->interfaceChain([&](const auto &_hidl_out_descriptors) {
- …
- });
- if (!_hidl_callbackCalled) {
- LOG_ALWAYS_FATAL(”interfaceChain: _hidl_cb not called, but must be called once.”);
- }
- return _hidl_err;
- }
::android::status_t BnHwBase::_hidl_interfaceChain( BnHwBase* _hidl_this, const ::android::hardware::Parcel &_hidl_data, ::android::hardware::Parcel *_hidl_reply, TransactCallback _hidl_cb) { #ifdef __ANDROID_DEBUGGABLE__ bool mEnableInstrumentation = _hidl_this->isInstrumentationEnabled(); const auto &mInstrumentationCallbacks = _hidl_this->getInstrumentationCallbacks(); #endif // __ANDROID_DEBUGGABLE__ ::android::status_t _hidl_err = ::android::OK; if (!_hidl_data.enforceInterface(BnHwBase::Pure::descriptor)) { _hidl_err = ::android::BAD_TYPE; return _hidl_err; } atrace_begin(ATRACE_TAG_HAL, "HIDL::IBase::interfaceChain::server"); #ifdef __ANDROID_DEBUGGABLE__ if (UNLIKELY(mEnableInstrumentation)) { std::vector<void *> _hidl_args; for (const auto &callback: mInstrumentationCallbacks) { callback(InstrumentationEvent::SERVER_API_ENTRY, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args); } } #endif // __ANDROID_DEBUGGABLE__ bool _hidl_callbackCalled = false; static_cast<BnHwBase*>(_hidl_this)->_hidl_mImpl->interfaceChain([&](const auto &_hidl_out_descriptors) { ... }); if (!_hidl_callbackCalled) { LOG_ALWAYS_FATAL("interfaceChain: _hidl_cb not called, but must be called once."); } return _hidl_err; }BnHwBase的interfaceChain实现又转交给_hidl_mImpl,同时也传入一个匿名的回调函数,而BnHwBase的_hidl_mImpl保存的是HwcHal对象,HwcHal并没有实现该函数,该函数由其父类IComposer类实现。
- ::android::hardware::Return<void> IComposer::interfaceChain(interfaceChain_cb _hidl_cb){
- _hidl_cb({
- IComposer::descriptor,
- ::android::hidl::base::V1_0::IBase::descriptor,
- });
- return ::android::hardware::Void();}
::android::hardware::Return<void> IComposer::interfaceChain(interfaceChain_cb _hidl_cb){ _hidl_cb({ IComposer::descriptor, ::android::hidl::base::V1_0::IBase::descriptor, }); return ::android::hardware::Void();}
这里只是回调由BnHwBase传进来的回调函数,且函数参数是IComposer::descriptor, IBase::descriptor。回调函数实现如下:
- {
- if (_hidl_callbackCalled) {
- LOG_ALWAYS_FATAL(”interfaceChain: _hidl_cb called a second time, but must be called once.”);
- }
- _hidl_callbackCalled = true;
- <span style=”color:#FF0000;”> <span style=“color:#000000;”>::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply);</span></span>
- size_t _hidl__hidl_out_descriptors_parent;
- _hidl_err = _hidl_reply->writeBuffer(&_hidl_out_descriptors, sizeof(_hidl_out_descriptors), &_hidl__hidl_out_descriptors_parent);
- /* _hidl_err ignored! */
- size_t _hidl__hidl_out_descriptors_child;
- _hidl_err = ::android::hardware::writeEmbeddedToParcel(
- _hidl_out_descriptors,
- _hidl_reply,
- _hidl__hidl_out_descriptors_parent,
- 0 /* parentOffset */, &_hidl__hidl_out_descriptors_child);
- /* _hidl_err ignored! */
- for (size_t _hidl_index_0 = 0; _hidl_index_0 < _hidl_out_descriptors.size(); ++_hidl_index_0) {
- _hidl_err = ::android::hardware::writeEmbeddedToParcel(
- _hidl_out_descriptors[_hidl_index_0],
- _hidl_reply,
- _hidl__hidl_out_descriptors_child,
- _hidl_index_0 * sizeof(::android::hardware::hidl_string));
- /* _hidl_err ignored! */
- }
- atrace_end(ATRACE_TAG_HAL);
- #ifdef __ANDROID_DEBUGGABLE__
- if (UNLIKELY(mEnableInstrumentation)) {
- std::vector<void *> _hidl_args;
- _hidl_args.push_back((void *)&_hidl_out_descriptors);
- for (const auto &callback: mInstrumentationCallbacks) {
- callback(InstrumentationEvent::SERVER_API_EXIT, ”android.hidl.base”, “1.0”, “IBase”, “interfaceChain”, &_hidl_args);
- }
- }
- #endif // __ANDROID_DEBUGGABLE__
- _hidl_cb(*_hidl_reply);
- }
{
if (_hidl_callbackCalled) {
LOG_ALWAYS_FATAL("interfaceChain: _hidl_cb called a second time, but must be called once.");
}
_hidl_callbackCalled = true;
::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply);
size_t _hidl__hidl_out_descriptors_parent;
_hidl_err = _hidl_reply->writeBuffer(&_hidl_out_descriptors, sizeof(_hidl_out_descriptors), &_hidl__hidl_out_descriptors_parent);
/* _hidl_err ignored! */
size_t _hidl__hidl_out_descriptors_child;
_hidl_err = ::android::hardware::writeEmbeddedToParcel(
_hidl_out_descriptors,
_hidl_reply,
_hidl__hidl_out_descriptors_parent,
0 /* parentOffset */, &_hidl__hidl_out_descriptors_child);
/* _hidl_err ignored! */
for (size_t _hidl_index_0 = 0; _hidl_index_0 < _hidl_out_descriptors.size(); ++_hidl_index_0) {
_hidl_err = ::android::hardware::writeEmbeddedToParcel(
_hidl_out_descriptors[_hidl_index_0],
_hidl_reply,
_hidl__hidl_out_descriptors_child,
_hidl_index_0 * sizeof(::android::hardware::hidl_string));
/* _hidl_err ignored! */
}
atrace_end(ATRACE_TAG_HAL);
#ifdef __ANDROID_DEBUGGABLE__
if (UNLIKELY(mEnableInstrumentation)) {
std::vector<void *> _hidl_args;
_hidl_args.push_back((void *)&_hidl_out_descriptors);
for (const auto &callback: mInstrumentationCallbacks) {
callback(InstrumentationEvent::SERVER_API_EXIT, "android.hidl.base", "1.0", "IBase", "interfaceChain", &_hidl_args);
}
}
#endif // __ANDROID_DEBUGGABLE__
_hidl_cb(*_hidl_reply);
}
这里只是将回调函数的参数IComposer::descriptor,IBase::descriptor打包到Parcel对象中,然后继续调用由IPCThreadState传进入的回调函数,该回调实现如下:
- auto reply_callback = [&] (auto &replyParcel) {
- if (reply_sent) {
- // Reply was sent earlier, ignore it.
- ALOGE(”Dropping binder reply, it was sent already.”);
- return;
- }
- reply_sent = true;
- if ((tr.flags & TF_ONE_WAY) == 0) {
- replyParcel.setError(NO_ERROR);
- sendReply(replyParcel, 0);
- } else {
- ALOGE(”Not sending reply in one-way transaction”);
- }
- };
auto reply_callback = [&] (auto &replyParcel) { if (reply_sent) { // Reply was sent earlier, ignore it. ALOGE("Dropping binder reply, it was sent already."); return; } reply_sent = true; if ((tr.flags & TF_ONE_WAY) == 0) { replyParcel.setError(NO_ERROR); sendReply(replyParcel, 0); } else { ALOGE("Not sending reply in one-way transaction"); } };该回调函数只是将打包后的Parcel发送给hwservicemanager进程。
- {
- if (interfaceChain.size() == 0) {
- return;
- }
- // First, verify you’re allowed to add() the whole interface hierarchy
- for(size_t i = 0; i < interfaceChain.size(); i++) {
- std::string fqName = interfaceChain[i];
- if (!mAcl.canAdd(fqName, pid)) {
- return;
- }
- }
- for(size_t i = 0; i < interfaceChain.size(); i++) {
- std::string fqName = interfaceChain[i];
- LOG(INFO) << ”add service of ” << fqName;
- PackageInterfaceMap &ifaceMap = mServiceMap[fqName];
- HidlService *hidlService = ifaceMap.lookup(name);
- if (hidlService == nullptr) {
- LOG(INFO) << ”insertService ” << name << “ of ” << fgName ;
- ifaceMap.insertService(
- std::make_unique<HidlService>(fqName, name, service, pid));
- } else {
- if (hidlService->getService() != nullptr) {
- auto ret = hidlService->getService()->unlinkToDeath(this);
- ret.isOk(); // ignore
- }
- LOG(INFO) << ”setService ” << “ of ” << fgName ;
- hidlService->setService(service, pid);
- }
- ifaceMap.sendPackageRegistrationNotification(fqName, name);
- }
- auto linkRet = service->linkToDeath(this, 0 /*cookie*/);
- linkRet.isOk(); // ignore
- isValidService = true;
- }
{ if (interfaceChain.size() == 0) { return; } // First, verify you're allowed to add() the whole interface hierarchy for(size_t i = 0; i < interfaceChain.size(); i++) { std::string fqName = interfaceChain[i]; if (!mAcl.canAdd(fqName, pid)) { return; } } for(size_t i = 0; i < interfaceChain.size(); i++) { std::string fqName = interfaceChain[i]; LOG(INFO) << "add service of " << fqName; PackageInterfaceMap &ifaceMap = mServiceMap[fqName]; HidlService *hidlService = ifaceMap.lookup(name); if (hidlService == nullptr) { LOG(INFO) << "insertService " << name << " of " << fgName ; ifaceMap.insertService( std::make_unique<HidlService>(fqName, name, service, pid)); } else { if (hidlService->getService() != nullptr) { auto ret = hidlService->getService()->unlinkToDeath(this); ret.isOk(); // ignore } LOG(INFO) << "setService " << " of " << fgName ; hidlService->setService(service, pid); } ifaceMap.sendPackageRegistrationNotification(fqName, name); } auto linkRet = service->linkToDeath(this, 0 /*cookie*/); linkRet.isOk(); // ignore isValidService = true; }该回调函数的参数值其实就是从Hal进程传递过来的IComposer::descriptor,IBase::descriptor,这时就开始完成服务注册了,整个服务注册过程分为三个步骤:
1. 服务校验过程
2. 服务添加过程
3. 死亡通知注册过程
服务校验
AccessControl类主要负责权限检查,包括SELinux权限。
system\hwservicemanager\AccessControl.cpp
- AccessControl::AccessControl() {
- mSeHandle = selinux_android_hw_service_context_handle();
- LOG_ALWAYS_FATAL_IF(mSeHandle == NULL, ”Failed to acquire SELinux handle.”);
- if (getcon(&mSeContext) != 0) {
- LOG_ALWAYS_FATAL(”Failed to acquire hwservicemanager context.”);
- }
- selinux_status_open(true);
- mSeCallbacks.func_audit = AccessControl::auditCallback;
- selinux_set_callback(SELINUX_CB_AUDIT, mSeCallbacks);
- mSeCallbacks.func_log = selinux_log_callback; /* defined in libselinux */
- selinux_set_callback(SELINUX_CB_LOG, mSeCallbacks);
- }
AccessControl::AccessControl() { mSeHandle = selinux_android_hw_service_context_handle(); LOG_ALWAYS_FATAL_IF(mSeHandle == NULL, "Failed to acquire SELinux handle."); if (getcon(&mSeContext) != 0) { LOG_ALWAYS_FATAL("Failed to acquire hwservicemanager context."); } selinux_status_open(true); mSeCallbacks.func_audit = AccessControl::auditCallback; selinux_set_callback(SELINUX_CB_AUDIT, mSeCallbacks); mSeCallbacks.func_log = selinux_log_callback; /* defined in libselinux */ selinux_set_callback(SELINUX_CB_LOG, mSeCallbacks); }
判断是否有权限添加过程如下:
- bool AccessControl::canAdd(const std::string& fqName, pid_t pid) {
- FQName fqIface(fqName);
- if (!fqIface.isValid()) {
- return false;
- }
- const std::string checkName = fqIface.package() + “::” + fqIface.name();
- return checkPermission(pid, kPermissionAdd, checkName.c_str());
- }
bool AccessControl::canAdd(const std::string& fqName, pid_t pid) { FQName fqIface(fqName); if (!fqIface.isValid()) { return false; } const std::string checkName = fqIface.package() + "::" + fqIface.name(); return checkPermission(pid, kPermissionAdd, checkName.c_str()); }
system\tools\hidl\utils\FQName.cpp
- FQName::FQName(const std::vector<std::string> &names)
- : mValid(false),
- mIsIdentifier(false) {
- setTo(StringHelper::JoinStrings(names, ”.”));
- }
FQName::FQName(const std::vector<std::string> &names) : mValid(false), mIsIdentifier(false) { setTo(StringHelper::JoinStrings(names, ".")); }
- bool FQName::setTo(const std::string &s) {
- clearVersion();
- mPackage.clear();
- mName.clear();
- mValid = true;
- std::smatch match;
- if (std::regex_match(s, match, kRE1)) {
- CHECK_EQ(match.size(), 5u);
- mPackage = match.str(1);
- parseVersion(match.str(2), match.str(3));
- mName = match.str(4);
- } else if (std::regex_match(s, match, kRE2)) {
- CHECK_EQ(match.size(), 4u);
- parseVersion(match.str(1), match.str(2));
- mName = match.str(3);
- } else if (std::regex_match(s, match, kRE3)) {
- CHECK_EQ(match.size(), 4u);
- mPackage = match.str(1);
- parseVersion(match.str(2), match.str(3));
- } else if (std::regex_match(s, match, kRE4)) {
- mName = match.str(0);
- } else if (std::regex_match(s, match, kRE5)) {
- mIsIdentifier = true;
- mName = match.str(0);
- } else if (std::regex_match(s, match, kRE6)) {
- CHECK_EQ(match.size(), 6u);
- mPackage = match.str(1);
- parseVersion(match.str(2), match.str(3));
- mName = match.str(4);
- mValueName = match.str(5);
- } else if (std::regex_match(s, match, kRE7)) {
- CHECK_EQ(match.size(), 5u);
- parseVersion(match.str(1), match.str(2));
- mName = match.str(3);
- mValueName = match.str(4);
- } else if (std::regex_match(s, match, kRE8)) {
- CHECK_EQ(match.size(), 3u);
- mName = match.str(1);
- mValueName = match.str(2);
- } else {
- mValid = false;
- }
- // mValueName must go with mName.
- CHECK(mValueName.empty() || !mName.empty());
- // package without version is not allowed.
- CHECK(mPackage.empty() || !version().empty());
- return isValid();
- }
bool FQName::setTo(const std::string &s) { clearVersion(); mPackage.clear(); mName.clear(); mValid = true; std::smatch match; if (std::regex_match(s, match, kRE1)) { CHECK_EQ(match.size(), 5u); mPackage = match.str(1); parseVersion(match.str(2), match.str(3)); mName = match.str(4); } else if (std::regex_match(s, match, kRE2)) { CHECK_EQ(match.size(), 4u); parseVersion(match.str(1), match.str(2)); mName = match.str(3); } else if (std::regex_match(s, match, kRE3)) { CHECK_EQ(match.size(), 4u); mPackage = match.str(1); parseVersion(match.str(2), match.str(3)); } else if (std::regex_match(s, match, kRE4)) { mName = match.str(0); } else if (std::regex_match(s, match, kRE5)) { mIsIdentifier = true; mName = match.str(0); } else if (std::regex_match(s, match, kRE6)) { CHECK_EQ(match.size(), 6u); mPackage = match.str(1); parseVersion(match.str(2), match.str(3)); mName = match.str(4); mValueName = match.str(5); } else if (std::regex_match(s, match, kRE7)) { CHECK_EQ(match.size(), 5u); parseVersion(match.str(1), match.str(2)); mName = match.str(3); mValueName = match.str(4); } else if (std::regex_match(s, match, kRE8)) { CHECK_EQ(match.size(), 3u); mName = match.str(1); mValueName = match.str(2); } else { mValid = false; } // mValueName must go with mName. CHECK(mValueName.empty() || !mName.empty()); // package without version is not allowed. CHECK(mPackage.empty() || !version().empty()); return isValid(); }
setTo函数其实就是使用正则表达式从[email protected]::IServiceManager字符串中取出包名,版本号,及服务类名,从而检查包名是否符合命名规则,如果包名有效,则继续调用checkPermission函数来检查selinux权限。
- bool AccessControl::checkPermission(pid_t sourcePid, const char *targetContext,
- const char *perm, const char *interface) {
- char *sourceContext = NULL;
- bool allowed = false;
- struct audit_data ad;
- if (getpidcon(sourcePid, &sourceContext) < 0) {
- ALOGE(”SELinux: failed to retrieved process context for pid %d”, sourcePid);
- return false;
- }
- ad.pid = sourcePid;
- ad.interfaceName = interface;
- <span style=”color:#FF0000;”> <span style=“color:#000000;”> allowed = (selinux_check_access(sourceContext, targetContext, “hwservice_manager”,
- perm, (void *) &ad) == 0);</span></span>
- freecon(sourceContext);
- return allowed;
- }
bool AccessControl::checkPermission(pid_t sourcePid, const char *targetContext,
const char *perm, const char *interface) {
char *sourceContext = NULL;
bool allowed = false;
struct audit_data ad;
if (getpidcon(sourcePid, &sourceContext) < 0) {
ALOGE("SELinux: failed to retrieved process context for pid %d", sourcePid);
return false;
}
ad.pid = sourcePid;
ad.interfaceName = interface;
allowed = (selinux_check_access(sourceContext, targetContext, "hwservice_manager",
perm, (void *) &ad) == 0);
freecon(sourceContext);
return allowed;
}
服务注册
如果服务注册进程有权限向hwservicemanager注册服务,接下来将完成服务添加。
每个服务接口对应多个实例,比如[email protected]::IServiceManager可以注册多个实例,每个实例名称不同。
- PackageInterfaceMap &ifaceMap = mServiceMap[fqName];
- HidlService *hidlService = ifaceMap.lookup(name);
PackageInterfaceMap &ifaceMap = mServiceMap[fqName]; HidlService *hidlService = ifaceMap.lookup(name);
- const HidlService *ServiceManager::PackageInterfaceMap::lookup(
- const std::string &name) const {
- auto it = mInstanceMap.find(name);
- if (it == mInstanceMap.end()) {
- return nullptr;
- }
- return it->second.get();
- }
const HidlService *ServiceManager::PackageInterfaceMap::lookup( const std::string &name) const { auto it = mInstanceMap.find(name); if (it == mInstanceMap.end()) { return nullptr; } return it->second.get(); }
根据名称查找HidlService,如果找不到,则新增一个HidlService,如果已经存在,则更新service。
- if (hidlService == nullptr) {
- LOG(INFO) << ”insertService ” << name << “ of ” << fgName ;
- ifaceMap.insertService(
- std::make_unique<HidlService>(fqName, name, service, pid));
- } else {
- if (hidlService->getService() != nullptr) {
- auto ret = hidlService->getService()->unlinkToDeath(this);
- ret.isOk(); // ignore
- }
- LOG(INFO) << ”setService ” << “ of ” << fgName ;
- hidlService->setService(service, pid);
- }
if (hidlService == nullptr) { LOG(INFO) << "insertService " << name << " of " << fgName ; ifaceMap.insertService( std::make_unique<HidlService>(fqName, name, service, pid)); } else { if (hidlService->getService() != nullptr) { auto ret = hidlService->getService()->unlinkToDeath(this); ret.isOk(); // ignore } LOG(INFO) << "setService " << " of " << fgName ; hidlService->setService(service, pid); }
到此就完成了hidl服务注册。