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  
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]进程:

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

  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. }  
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设备。
  1. android::ProcessState::initWithDriver(“/dev/vndbinder”);  
android::ProcessState::initWithDriver("/dev/vndbinder");
这句说明composer hal通过vndbinder来通信的,接下来就是设置binder线程个数为4,并启动binder线程池,然后调用
  1. defaultPassthroughServiceImplementation<IComposer>(4)  
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. }  
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;
}
  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. }  
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的类对象。

扫描二维码关注公众号,回复: 876260 查看本文章

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;  
  98. }   
::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图:


  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. }  
    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<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. }  
sp<IServiceManager> getPassthroughServiceManager() {
    static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
    return manager;
}
这里只是简单的创建了一个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.     }  
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

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

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

  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(thisthis, fqName, name);  
  3.   
  4.     return _hidl_out;  
  5. }  
::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;
}
  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. }  
::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将接收函数调用请求:
[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. }  
::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端的注册。
  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. }  
::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启动过程时,会进行详细分析。
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. }  
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
  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. {}  
HidlService(const std::string &interfaceName,
            const std::string &instanceName)
: HidlService(
    interfaceName,
    instanceName,
    nullptr,
    static_cast<pid_t>(IServiceManager::PidConstant::NO_PID))
{}
因此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. }  
::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函数。
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. }  
void onRegistration(const std::string &packageName,
                    const std::string& /* interfaceName */,
                    const std::string& /* instanceName */) {
    tryShortenProcessName(packageName);
}
  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. }  
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

  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(thisthis, name, service);  
  3.   
  4.     return _hidl_out;  
  5. }  
::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;
}
  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. }  
::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对象。
  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. }  
::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。
[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. }  
::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;
}
  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. <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>  
  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. }  
::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:

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. }  
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函数实现如下:
[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(thisthis, _hidl_cb);  
  3.   
  4.     return _hidl_out;  
  5. }  
::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;
}
  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. <span style=”color:#FF0000;”>   <span style=“color:#000000;”> _hidl_err = _hidl_data.writeInterfaceToken(BpHwBase::descriptor);</span></span>  
  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. }  
::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,

然后调用传递进来的回调函数_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. }  
::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来完成:
[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. }  
::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类实现。
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();}  
::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。回调函数实现如下:

  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. <span style=”color:#FF0000;”>   <span style=“color:#000000;”>::android::hardware::writeToParcel(::android::hardware::Status::ok(), _hidl_reply);</span></span>  
  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. }  
{
    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传进入的回调函数,该回调实现如下:
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. };  
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进程。

也就是说,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. }  
{
    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

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

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

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

  1. FQName::FQName(const std::vector<std::string> &names)  
  2.     : mValid(false),  
  3.       mIsIdentifier(false) {  
  4.     setTo(StringHelper::JoinStrings(names, ”.”));  
  5. }  
FQName::FQName(const std::vector<std::string> &names)
    : mValid(false),
      mIsIdentifier(false) {
    setTo(StringHelper::JoinStrings(names, "."));
}
  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. }  
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权限。

  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.  <span style=”color:#FF0000;”> <span style=“color:#000000;”>  allowed = (selinux_check_access(sourceContext, targetContext, “hwservice_manager”,  
  16.                                     perm, (void *) &ad) == 0);</span></span>  
  17.   
  18.     freecon(sourceContext);  
  19.   
  20.     return allowed;  
  21. }  
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可以注册多个实例,每个实例名称不同。

  1. PackageInterfaceMap &ifaceMap = mServiceMap[fqName];  
  2. HidlService *hidlService = ifaceMap.lookup(name);  
PackageInterfaceMap &ifaceMap = mServiceMap[fqName];
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. }  
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。

  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. }  
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服务注册。



猜你喜欢

转载自blog.csdn.net/marshal_zsx/article/details/80293127