前两篇文章我们简要分析了Android8.0系统下框架层的Binder框架,包括servicemanager, native和java层面的binder顶层框架。今天我们来看binder在HAL层是如何实现跨进程管理的,在Android8.0的HAL层,HAL通过Binder将各种硬件驱动抽象为硬件服务,以削弱快速的版本更新带来的影响,通过只更新Framework层来达到消灭系统碎片化。废话少说,我们来一探究竟。
在HAL的binder框架与framework层的框架略有不同,let’s see the code!
class IBinder : public virtual RefBase
{
public:
......
virtual status_t transact( uint32_t code, //顶层函数
const Parcel& data,
Parcel* reply,
uint32_t flags = 0,
TransactCallback callback = nullptr) = 0;
......
virtual BHwBinder* localBinder();
virtual BpHwBinder* remoteBinder();
protected:
virtual ~IBinder();
private:
};
继承自IBinder, 实现了transact()函数
class BpHwBinder : public IBinder
{
public:
BpHwBinder(int32_t handle);
inline int32_t handle() const { return mHandle; }
virtual status_t transact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0,
TransactCallback callback = nullptr);
......
virtual BpHwBinder* remoteBinder();
status_t setConstantData(const void* data, size_t size);
void sendObituary();
......
protected:
virtual ~BpHwBinder();
virtual void onFirstRef();
virtual void onLastStrongRef(const void* id);
virtual bool onIncStrongAttempted(uint32_t flags, const void* id);
};
BHwBinder作为Binder.cpp的内部类同样继承自IBinder
class BHwBinder : public IBinder
{
public:
BHwBinder();
virtual status_t transact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0,
TransactCallback callback = nullptr);
.......
protected:
virtual ~BHwBinder();
virtual status_t onTransact( uint32_t code, //接受处理来自Binder驱动的指令
const Parcel& data,
Parcel* reply,
uint32_t flags = 0,
TransactCallback callback = nullptr);
int mSchedPolicy; // policy to run transaction from this node at
// priority [-20..19] for SCHED_NORMAL, [1..99] for SCHED_FIFO/RT
int mSchedPriority;
private:
BHwBinder(const BHwBinder& o);
BHwBinder& operator=(const BHwBinder& o);
class Extras;
std::atomic<Extras*> mExtras;
void* mReserved0;
};
// ---------------------------------------------------------------------------
class BpHwRefBase : public virtual RefBase // 内部类,持有远程Binder的引用
{
protected:
BpHwRefBase(const sp<IBinder>& o);
virtual ~BpHwRefBase();
virtual void onFirstRef();
virtual void onLastStrongRef(const void* id);
virtual bool onIncStrongAttempted(uint32_t flags, const void* id);
inline IBinder* remote() const { return mRemote; } //远程Binder
private:
BpHwRefBase(const BpHwRefBase& o);
BpHwRefBase& operator=(const BpHwRefBase& o);
IBinder* const mRemote;
RefBase::weakref_type* mRefs;
std::atomic<int32_t> mState;
};
}; // namespace hardware
}; // namespace android
IInterface略微简单,没有framework层的复杂,由此可以猜测HAL层的跨进程调用过程远比framework层复杂
class IInterface : public virtual RefBase
{
public:
IInterface();
static sp<IBinder> asBinder(const IInterface*);
static sp<IBinder> asBinder(const sp<IInterface>&);
protected:
virtual ~IInterface();
virtual IBinder* onAsBinder() = 0;
};
// ----------------------------------------------------------------------
template<typename INTERFACE> //服务端
class BnInterface : public INTERFACE, public IInterface, public BHwBinder
{
public:
BnInterface(const sp<INTERFACE>& impl);
protected:
const sp<INTERFACE> mImpl;
virtual IBinder* onAsBinder();
};
template<typename INTERFACE>
inline BnInterface<INTERFACE>::BnInterface(
const sp<INTERFACE>& impl) : mImpl(impl)
{
}
// ----------------------------------------------------------------------
template<typename INTERFACE> //代理端
class BpInterface : public INTERFACE, public IInterface, public BpHwRefBase
{
public:
BpInterface(const sp<IBinder>& remote);
virtual IBinder* onAsBinder();
};
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// No user-serviceable parts after this...
//具体实现
template<typename INTERFACE>
IBinder* BnInterface<INTERFACE>::onAsBinder()
{
return this;
}
template<typename INTERFACE>
inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)
: BpHwRefBase(remote)
{
}
template<typename INTERFACE>
inline IBinder* BpInterface<INTERFACE>::onAsBinder()
{
return remote();
}
除此外与Binder驱动的交互仍然通过ProcessState来完成通讯,在IInterface中我们并没有看到业务层与通讯层的耦合,由此,业务处理必定另有蹊跷,先略微暂停,先去看看服务是如何被管理的。
为了跟踪服务的管理过程,选择Power作为分析对象,因为它的结构相对简单。
hardware/interfaces/power/1.0/default/service.cpp
int main() {
return defaultPassthroughServiceImplementation<IPower>();
}
system/libhidl/transport/include/hidl/LegacySupport.h
Interface 模板参数为 IPower
template<class Interface>
__attribute__((warn_unused_result))
status_t defaultPassthroughServiceImplementation(std::string name,
size_t maxThreads = 1) {
configureRpcThreadpool(maxThreads, true);
status_t result = registerPassthroughServiceImplementation<Interface>(name); //调用注册
if (result != OK) {
return result;
}
joinRpcThreadpool();
return 0;
}
template<class Interface>
__attribute__((warn_unused_result))
status_t registerPassthroughServiceImplementation( //注册
std::string name = "default") {
sp<Interface> service = Interface::getService(name, true /* getStub */); //查询服务
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); //注册服务
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;
}
Android8.0引入HIDL接口定义语言,通过编译以后会在out目录下生成相对的cpp文件,在 out/soong/.intermediates/hardware/interfaces/power目录下对应编译生成的power交互文件,头文件在 out/soong/.intermediates/hardware/interfaces/power/1.0/[email protected]_genc++_headers/gen/android/hardware/power/1.0目录下,实现文件在 out/soong/.intermediates/hardware/interfaces/power/1.0/[email protected]_genc++/gen/android/hardware/power/1.0 目录下
我们首先来看头文件下的几个头文件的结构,在IPower.h头文件中实现了IBase
struct IPower : public ::android::hidl::base::V1_0::IBase {
virtual bool isRemote() const override { return false; }
......
};
那么IBase是哪里来的呢?一查找发现其实现了RefBae
struct IBase : virtual public ::android::RefBase {
virtual bool isRemote() const { return false; }
......
}
我们会退到主线继续, BpHwPower继承了BpInterface,从上文知道BpInterface实现了BpHwBinder
struct BpHwPower : public ::android::hardware::BpInterface<IPower>, public ::android::hardware::details::HidlInstrumentor {
explicit BpHwPower(const ::android::sp<::android::hardware::IBinder> &_hidl_impl);
typedef IPower Pure;
virtual bool isRemote() const override { return true; }
......
};
BnHwPower实现了BnHwBase
struct BnHwPower : public ::android::hidl::base::V1_0::BnHwBase {
explicit BnHwPower(const ::android::sp<IPower> &_hidl_impl);
explicit BnHwPower(const ::android::sp<IPower> &_hidl_impl, const std::string& HidlInstrumentor_package, const std::string& HidlInstrumentor_interface);
virtual ~BnHwPower();
::android::status_t onTransact(
uint32_t _hidl_code,
const ::android::hardware::Parcel &_hidl_data,
::android::hardware::Parcel *_hidl_reply,
uint32_t _hidl_flags = 0,
TransactCallback _hidl_cb = nullptr) override;
typedef IPower Pure;
::android::sp<IPower> getImpl() { return _hidl_mImpl; };
......
};
而BnHwBase又实现了BHwBinder
struct BnHwBase : public ::android::hardware::BHwBinder, public ::android::hardware::details::HidlInstrumentor {
explicit BnHwBase(const ::android::sp<IBase> &_hidl_impl);
explicit BnHwBase(const ::android::sp<IBase> &_hidl_impl, const std::string& HidlInstrumentor_package, const std::string& HidlInstrumentor_interface);
virtual ~BnHwBase();
::android::status_t onTransact(
uint32_t _hidl_code,
const ::android::hardware::Parcel &_hidl_data,
::android::hardware::Parcel *_hidl_reply,
uint32_t _hidl_flags = 0,
TransactCallback _hidl_cb = nullptr) override;
typedef IBase Pure;
::android::sp<IBase> getImpl() { return _hidl_mImpl; };
......
我们回到主线看看IPower实现文件目录下,它的静态构造函数如下,同时实现了上述三个头文件申明的函数,
const char* IPower::descriptor("[email protected]::IPower");
__attribute__((constructor))static void static_constructor() {
::android::hardware::details::gBnConstructorMap.set(IPower::descriptor,
[](void *iIntf) -> ::android::sp<::android::hardware::IBinder> {
return new BnHwPower(static_cast<IPower *>(iIntf));
});
::android::hardware::details::gBsConstructorMap.set(IPower::descriptor,
[](void *iIntf) -> ::android::sp<::android::hidl::base::V1_0::IBase> {
return new BsPower(static_cast<IPower *>(iIntf));
});
};
__attribute__((destructor))static void static_destructor() {
::android::hardware::details::gBnConstructorMap.erase(IPower::descriptor);
::android::hardware::details::gBsConstructorMap.erase(IPower::descriptor);
};
由此在执行 sp service = Interface::getService(name, true /* getStub */); 函数时将会执行PowerAll.cpp的getService()函数
::android::sp<IPower> IPower::getService(const std::string &serviceName, const bool getStub) {
......
sp<IPower> iface = nullptr;
//获取服务管家
const sp<::android::hidl::manager::V1_0::IServiceManager> sm = defaultServiceManager();
if (sm == nullptr) {
ALOGE("getService: defaultServiceManager() is null");
return nullptr;
}
//获取Binder方式
Return<Transport> transportRet = sm->getTransport(IPower::descriptor, serviceName);
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);
.....
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, IPower::descriptor, serviceName.c_str());
sleep(1);
}
if (vintfHwbinder && tries > 0) {
waitForHwService(IPower::descriptor, serviceName);
}
Return<sp<::android::hidl::base::V1_0::IBase>> ret =
sm->get(IPower::descriptor, serviceName);
if (!ret.isOk()) {
ALOGE("IPower: 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("IPower: found null hwbinder interface");
}continue;
}
Return<sp<IPower>> castRet = IPower::castFrom(base, true /* emitError */); //转换
if (!castRet.isOk()) {
if (castRet.isDeadObject()) {
ALOGW("IPower: found dead hwbinder service");
continue;
} else {
ALOGW("IPower: cannot call into hwbinder service: %s; No permission? Check for selinux denials.", castRet.description().c_str());
break;
}
}
iface = castRet;
if (iface == nullptr) {
ALOGW("IPower: received incompatible service; bug in hwservicemanager?");
break;
}
return iface;
}
if (getStub || vintfPassthru || vintfLegacy) {
//直通模式
const sp<::android::hidl::manager::V1_0::IServiceManager> pm = getPassthroughServiceManager();
if (pm != nullptr) {
Return<sp<::android::hidl::base::V1_0::IBase>> ret =
pm->get(IPower::descriptor, serviceName); //获取服务
if (ret.isOk()) {
sp<::android::hidl::base::V1_0::IBase> baseInterface = ret;
if (baseInterface != nullptr) {
iface = IPower::castFrom(baseInterface); //转换 IBase -> IPower(Binder类型)
if (!getStub || trebleTestingOverride) {
iface = new BsPower(iface); //非Stub模式
}
}
}
}
}
return iface; //返回服务
}
那么 getPassthroughServiceManager 又是如何获取ServiceManager呢,在ServiceManagerment.cpp中
sp<IServiceManager1_0> getPassthroughServiceManager() {
return getPassthroughServiceManager1_1();
}
sp<IServiceManager1_1> getPassthroughServiceManager1_1() {
static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
return manager;
}
PassthroughServiceManager实现了IServiceManager, get()函数调用了openLibs
struct PassthroughServiceManager : IServiceManager {
static void openLibs(const std::string& fqName,
std::function<bool /* continue */(void* /* handle */,
const std::string& /* lib */, const std::string& /* sym */)> eachLib) {
//fqName looks like [email protected]::IFoo
size_t idx = fqName.find("::");
if (idx == std::string::npos ||
idx + strlen("::") + 1 >= fqName.size()) {
LOG(ERROR) << "Invalid interface name passthrough lookup: " << fqName;
return;
}
std::string packageAndVersion = fqName.substr(0, idx);
std::string ifaceName = fqName.substr(idx + strlen("::"));
const std::string prefix = packageAndVersion + "-impl";
const std::string sym = "HIDL_FETCH_" + ifaceName; //非常重要
const int dlMode = RTLD_LAZY;
void *handle = nullptr;
dlerror(); // clear
std::vector<std::string> paths = {HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR,
HAL_LIBRARY_PATH_VNDK_SP, HAL_LIBRARY_PATH_SYSTEM};
#ifdef LIBHIDL_TARGET_DEBUGGABLE
const char* env = std::getenv("TREBLE_TESTING_OVERRIDE");
const bool trebleTestingOverride = env && !strcmp(env, "true");
if (trebleTestingOverride) {
const char* vtsRootPath = std::getenv("VTS_ROOT_PATH");
if (vtsRootPath && strlen(vtsRootPath) > 0) {
const std::string halLibraryPathVtsOverride =
std::string(vtsRootPath) + HAL_LIBRARY_PATH_SYSTEM;
paths.push_back(halLibraryPathVtsOverride);
}
}
#endif
for (const std::string& path : paths) { //遍历.so文件路径
std::vector<std::string> libs = search(path, prefix, ".so");
for (const std::string &lib : libs) {
const std::string fullPath = path + lib;
if (path != HAL_LIBRARY_PATH_SYSTEM) {
handle = android_load_sphal_library(fullPath.c_str(), dlMode);
} else {
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;
}
if (!eachLib(handle, lib, sym)) {
return;
}
}
}
}
Return<sp<IBase>> get(const hidl_string& fqName, //返回管理服务
const hidl_string& name) override {
sp<IBase> ret = nullptr;
openLibs(fqName, [&](void* handle, const std::string &lib, const std::string &sym) {
IBase* (*generator)(const char* name); //函数指针
*(void **)(&generator) = dlsym(handle, sym.c_str()); //调用Linux系统函数打开.so
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);
return true;
}
ret = (*generator)(name.c_str()); //返回
if (ret == nullptr) {
dlclose(handle);
return true; // this module doesn't provide this instance name
}
registerReference(fqName, name); // 注册
return false;
});
return ret;
}
Return<bool> add(const hidl_string& /* name */,
const sp<IBase>& /* service */) override {
LOG(FATAL) << "Cannot register services with passthrough service manager.";
return false;
}
Return<Transport> getTransport(const hidl_string& /* fqName */,
const hidl_string& /* name */) {
LOG(FATAL) << "Cannot getTransport with passthrough service manager.";
return Transport::EMPTY;
}
Return<void> list(list_cb /* _hidl_cb */) override {
LOG(FATAL) << "Cannot list services with passthrough service manager.";
return Void();
}
Return<void> listByInterface(const hidl_string& /* fqInstanceName */,
listByInterface_cb /* _hidl_cb */) override {
// TODO: add this functionality
LOG(FATAL) << "Cannot list services with passthrough service manager.";
return Void();
}
Return<bool> registerForNotifications(const hidl_string& /* fqName */,
const hidl_string& /* name */,
const sp<IServiceNotification>& /* callback */) override {
// This makes no sense.
LOG(FATAL) << "Cannot register for notifications with passthrough service manager.";
return false;
}
......
fetchPidsForPassthroughLibraries(&map);
hidl_vec<InstanceDebugInfo> vec;
vec.resize(map.size());
size_t idx = 0;
for (auto&& pair : map) {
vec[idx++] = std::move(pair.second);
}
_hidl_cb(vec);
return Void();
}
Return<void> registerPassthroughClient(const hidl_string &, const hidl_string &) override {
// This makes no sense.
LOG(FATAL) << "Cannot call registerPassthroughClient on passthrough service manager. "
<< "Call it on defaultServiceManager() instead.";
return Void();
......
}
};
const std::string sym = “HIDL_FETCH_” + ifaceName; 给出了要调用的函数,那么这个函数在哪里呢,回到hardware/interfaces目录下Power.cpp文件中,将走著名的HAL模块,这一块暂且跳过。
IPower* HIDL_FETCH_IPower(const char* /* name */) {
const hw_module_t* hw_module = nullptr;
power_module_t* power_module = nullptr;
int err = hw_get_module(POWER_HARDWARE_MODULE_ID, &hw_module);
if (err) {
ALOGE("hw_get_module %s failed: %d", POWER_HARDWARE_MODULE_ID, err);
return nullptr;
}
if (!hw_module->methods || !hw_module->methods->open) {
power_module = reinterpret_cast<power_module_t*>(
const_cast<hw_module_t*>(hw_module));
} else {
err = hw_module->methods->open(
hw_module, POWER_HARDWARE_MODULE_ID,
reinterpret_cast<hw_device_t**>(&power_module));
if (err) {
ALOGE("Passthrough failed to load legacy HAL.");
return nullptr;
}
}
return new Power(power_module);
}
继续服务的注册部分 registerReference()
static void registerReference(const hidl_string &interfaceName, const hidl_string &instanceName) {
sp<IServiceManager1_0> 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;
}
那么 registerPassthroughClient又是在哪里调用呢,在Servicemanager.cpp中,Servicemanager继承自IServicemanager可以看出它是通过一个二元结构存储IBase的
Return<void> ServiceManager::registerPassthroughClient(const hidl_string &fqName,
const hidl_string &name) {
pid_t pid = IPCThreadState::self()->getCallingPid();
if (!mAcl.canGet(fqName, 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();
}
PackageInterfaceMap &ifaceMap = mServiceMap[fqName]; //服务map
if (name.empty()) {
LOG(WARNING) << "registerPassthroughClient encounters empty instance name for "
<< fqName.c_str();
return Void();
}
HidlService *service = ifaceMap.lookup(name); //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();
}
至此,我们可以简略了解到服务是如何被管理的;此外可以看出由于C++是杂合型语言,非单根继承,在创建面向对象结构时需要建立顶层继承结构;而java是单根继承结构,面对同样的问题,Java在面向对象的复杂体系时,设计较为简单;在下一篇我们将分析在Framework层如何实现面向HAL的服务。