cameraprovider进程是Camer HAL所在进程,在分析HAL启动流程前,必须先分析下cameraprovider的启动流程
本文在此对cameraprovider的启动流程做简要的分析
rc启动脚本:
//hardware\interfaces\camera\provider\2.4\default\[email protected]
service camera-provider-2-4 /vendor/bin/hw/android.hardware.camera.provider@2.4-service
class hal
user root
group audio camera input drmrpc
ioprio rt 4
capabilities SYS_NICE
writepid /dev/cpuset/camera-daemon/tasks /dev/stune/foreground/tasks
从rc脚本看:
cameraprovider进程名:camera-provider-2-4
,
bin文件:/vendor/bin/hw/[email protected]
编译文件:
//hardware\interfaces\camera\provider\2.4\default\
cc_binary {
name: "[email protected]",//name
defaults: ["hidl_defaults"],
proprietary: true,
relative_install_path: "hw",//install目录位/vendor/lib/hw
srcs: ["service.cpp"],//源码
compile_multilib: "32",//编译为32位
init_rc: ["[email protected]"],//rc文件
shared_libs: [
"libhidlbase",
"libhidltransport",
"libbinder",
"liblog",
"libutils",
"[email protected]",
"[email protected]_vendor",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
],
}
从上边看,服务源码为:service.cpp,服务入口如下:
//hardware\interfaces\camera\provider\2.4\default\service.cpp
int main()
{
ALOGI("Camera provider Service is starting.");
// The camera HAL may communicate to other vendor components via
// /dev/vndbinder
android::ProcessState::initWithDriver("/dev/vndbinder");
//该方法实现了
//1、通过Passthrough方法(直通式,本人理解为在同一个进程中运行)获取CameraProvider对象
//2、注册服务给hwservicemanager
return defaultPassthroughServiceImplementation<ICameraProvider>("legacy/0", /*maxThreads*/ 6);
}
defaultPassthroughServiceImplementation时,使用了ICameraProvider类,
ICameraProvider
类是由HIDL接口定义文件ICameraProvider.hal
通过hidl-gen
编译工具编译生成。
ICameraProvider.hal
接口定义文件如下:
//hardware\interfaces\camera\provider\2.4\ICameraProvider.hal
package android.hardware.camera.provider@2.4;
import ICameraProviderCallback;
import android.hardware.camera.common@1.0::types;
import android.hardware.camera.device@1.0::ICameraDevice;
import android.hardware.camera.device@3.2::ICameraDevice;
interface ICameraProvider {
setCallback(ICameraProviderCallback callback) generates (Status status);
getVendorTags() generates (Status status, vec<VendorTagSection> sections);
getCameraIdList()
generates (Status status, vec<string> cameraDeviceNames);
isSetTorchModeSupported() generates (Status status, bool support);
getCameraDeviceInterface_V1_x(string cameraDeviceName) generates
(Status status,
android.hardware.camera.device@1.0::ICameraDevice device);
getCameraDeviceInterface_V3_x(string cameraDeviceName) generates
(Status status,
android.hardware.camera.device@3.2::ICameraDevice device);
};
其编译命令如下:
//hardware\interfaces\camera\Android.bp
// This file is autogenerated by hidl-gen. Do not edit manually.
filegroup {
name: "[email protected]_hal",
srcs: [
"ICameraProvider.hal",
"ICameraProviderCallback.hal",
],
}
genrule {
name: "[email protected]_genc++",
tools: ["hidl-gen"],
cmd: "$(location hidl-gen) -o $(genDir) -Lc++-sources -randroid.hardware:hardware/interfaces -randroid.hidl:system/libhidl/transport [email protected]",
srcs: [
":[email protected]_hal",
],
out: [
"android/hardware/camera/provider/2.4/CameraProviderAll.cpp",
"android/hardware/camera/provider/2.4/CameraProviderCallbackAll.cpp",
],
}
genrule {
name: "[email protected]_genc++_headers",
tools: ["hidl-gen"],
cmd: "$(location hidl-gen) -o $(genDir) -Lc++-headers -randroid.hardware:hardware/interfaces -randroid.hidl:system/libhidl/transport [email protected]",
srcs: [
":[email protected]_hal",
],
out: [
"android/hardware/camera/provider/2.4/ICameraProvider.h",
"android/hardware/camera/provider/2.4/IHwCameraProvider.h",
"android/hardware/camera/provider/2.4/BnHwCameraProvider.h",
"android/hardware/camera/provider/2.4/BpHwCameraProvider.h",
"android/hardware/camera/provider/2.4/BsCameraProvider.h",
....
],
}
cc_library {
name: "[email protected]",
defaults: ["hidl-module-defaults"],
generated_sources: ["[email protected]_genc++"],
generated_headers: ["[email protected]_genc++_headers"],
export_generated_headers: ["[email protected]_genc++_headers"],
vendor_available: true,
vndk: {
enabled: true,
},
....
}
通过上述编译命令看,ICameraProvider.hal
通过hidl-gen
编译生成了ICameraProvider.h,BnHwCameraProvider.h,BpHwCameraProvider.h,BsCameraProvider.h
等头文件和一个CameraProviderAll.cpp
CPP文件
并最终生成了[email protected]
文件
接着继续分析下defaultPassthroughServiceImplementation
//system\libhidl\transport\include\hidl\LegacySupport.h
//模板方法,class为ICameraProvider
template<class Interface>
__attribute__((warn_unused_result))
status_t defaultPassthroughServiceImplementation(std::string name,
size_t maxThreads = 1) {
//打开/dev/hwbinder
//通知kernel,当前进程最大允许的线程数量maxThreads
configureRpcThreadpool(maxThreads, true);
//获取Passthrough(直通)的服务实现
//然后将获取的服务注册给hwservicemanager
status_t result = registerPassthroughServiceImplementation<Interface>(name);
...
joinRpcThreadpool();
return 0;
}
分析下configureRpcThreadpool
//system\libhidl\transport\HidlTransportSupport.cpp
void configureRpcThreadpool(size_t maxThreads, bool callerWillJoin) {
// TODO(b/32756130) this should be transport-dependent
configureBinderRpcThreadpool(maxThreads, callerWillJoin);
}
//system\libhidl\transport\HidlBinderSupport.cpp
void configureBinderRpcThreadpool(size_t maxThreads, bool callerWillJoin) {
ProcessState::self()->setThreadPoolConfiguration(maxThreads, callerWillJoin /*callerJoinsPool*/);
}
ProcessState::self()
获取ProcessState
的全局单例变量gProcess
//system\libhwbinder\ProcessState.cpp
sp<ProcessState> ProcessState::self()
{
Mutex::Autolock _l(gProcessMutex);
if (gProcess != NULL) {
return gProcess;
}
gProcess = new ProcessState;
return gProcess;
}
ProcessState
的构造函数会打开/dev/hwbinder
设备节点,并将内存映射到当前进程
//system\libhwbinder\ProcessState.cpp
ProcessState::ProcessState()
: mDriverFD(open_driver())//打开/dev/hwbinder节点
, mVMStart(MAP_FAILED)
, mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
, mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
, mExecutingThreadsCount(0)
, mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
, mStarvationStartTimeMs(0)
, mManagesContexts(false)
, mBinderContextCheckFunc(NULL)
, mBinderContextUserData(NULL)
, mThreadPoolStarted(false)
, mSpawnThreadOnStart(true)
, mThreadPoolSeq(1)
{
if (mDriverFD >= 0) {
// mmap the binder, providing a chunk of virtual address space to receive transactions.
//内存映射
mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
if (mVMStart == MAP_FAILED) {
// *sigh*
ALOGE("Using /dev/hwbinder failed: unable to mmap transaction memory.\n");
close(mDriverFD);
mDriverFD = -1;
}
}
else {
ALOGE("Binder driver could not be opened. Terminating.");
}
}
打开/dev/hwbinde
r的代码
//system\libhwbinder\ProcessState.cpp
static int open_driver()
{
int fd = open("/dev/hwbinder", O_RDWR | O_CLOEXEC);
if (fd >= 0) {
int vers = 0;
status_t result = ioctl(fd, BINDER_VERSION, &vers);
if (result == -1) {
ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));
close(fd);
fd = -1;
}
if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)!", vers, BINDER_CURRENT_PROTOCOL_VERSION);
close(fd);
fd = -1;
}
size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);
if (result == -1) {
ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));
}
} else {
ALOGW("Opening '/dev/hwbinder' failed: %s\n", strerror(errno));
}
return fd;
}
从上述代码看,configureRpcThreadpool
主要作用有:
- 打开
/dev/hwbinder
节点,并将内存映射到当前进程 - 通过
ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads)
设置binder最大线程数
接着继续分析下registerPassthroughServiceImplementation
//system\libhidl\transport\include\hidl\LegacySupport.h
/**
* Registers passthrough service implementation.
*/
//Interface为ICameraProvider
//
template<class Interface>
__attribute__((warn_unused_result))
status_t registerPassthroughServiceImplementation(
std::string name = "default") {
//调用的是ICameraProvider::getService("legacy/0",true)
//是以passthrough方法获取的ICameraProvider子类CameraProvider对象
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;
}
//如果获取的对象是remote,则打印该异常log
//ICameraProvider.h isRemote()为false,passthrough方式获取的是ICameraProvider对象,isRemote()为false
//BpHwCameraProvider.h isRemote()为true
LOG_FATAL_IF(service->isRemote(), "Implementation of %s/%s is remote!",
Interface::descriptor, name.c_str());
//注册服务给hwservicemanager
status_t status = service->registerAsService(name);
...
return status;
}
1. 下边分析下ICameraProvider::getService(const std::string &serviceName, const bool getStub)
的流程
ICameraProvider::getService
的实现是ICameraProvider.hal
编译生成的,实现如下:
//out\soong\.intermediates\hardware\interfaces\camera\provider\2.4\[email protected]_genc++\gen\android\hardware\camera\provider\2.4\CameraProviderAll.cpp
::android::sp<ICameraProvider> ICameraProvider::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<ICameraProvider> iface = nullptr;
//获取IServiceManager代理对象BpHwServiceManager
const sp<::android::hidl::manager::V1_0::IServiceManager> sm = defaultServiceManager();
if (sm == nullptr) {
ALOGE("getService: defaultServiceManager() is null");
return nullptr;
}
//获取服务的Transport属性
//属性定义在device\qcom\projectName\manifest.xml
Return<Transport> transportRet = sm->getTransport(ICameraProvider::descriptor, serviceName);
if (!transportRet.isOk()) {
ALOGE("getService: defaultServiceManager()->getTransport returns %s", transportRet.description().c_str());
return nullptr;
}
//ICameraProvider的transport为Transport::HWBINDER,其定义在device\qcom\projectName\manifest.xml,下边会讲解
//所以vintfHwbinder 为true
//vintfPassthru为false
Transport transport = transportRet;
const bool vintfHwbinder = (transport == Transport::HWBINDER);
const bool vintfPassthru = (transport == Transport::PASSTHROUGH);
...
//getStub 为false且transport 属性为Transport::HWBINDER或者transport 属性为Transport::EMPTY
//该条件不满足,没有进入该循环
//在CameraSercvice获取cameraProvider服务时会进入该循环
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, ICameraProvider::descriptor, serviceName.c_str());
sleep(1);
}
if (vintfHwbinder && tries > 0) {
waitForHwService(ICameraProvider::descriptor, serviceName);
}
Return<sp<::android::hidl::base::V1_0::IBase>> ret =
sm->get(ICameraProvider::descriptor, serviceName);
if (!ret.isOk()) {
ALOGE("ICameraProvider: 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("ICameraProvider: found null hwbinder interface");
}continue;
}
Return<sp<ICameraProvider>> castRet = ICameraProvider::castFrom(base, true /* emitError */);
if (!castRet.isOk()) {
if (castRet.isDeadObject()) {
ALOGW("ICameraProvider: found dead hwbinder service");
continue;
} else {
ALOGW("ICameraProvider: cannot call into hwbinder service: %s; No permission? Check for selinux denials.", castRet.description().c_str());
break;
}
}
iface = castRet;
if (iface == nullptr) {
ALOGW("ICameraProvider: received incompatible service; bug in hwservicemanager?");
break;
}
return iface;
}
//getStub 为true或者transport 属性为Transport::PASSTHROUGH或者为transport 属性为Transport::EMPTY
//cameraprovider 启动时getStub为true;vintfPassthru为false;vintfLegacy为false,满足该循环进入条件
if (getStub || vintfPassthru || vintfLegacy) {
const sp<::android::hidl::manager::V1_0::IServiceManager> pm = getPassthroughServiceManager();
if (pm != nullptr) {
//ICameraProvider::descriptor为[email protected]::ICameraProvider
//serviceName为"legacy/0"
Return<sp<::android::hidl::base::V1_0::IBase>> ret =
pm->get(ICameraProvider::descriptor, serviceName);
if (ret.isOk()) {
sp<::android::hidl::base::V1_0::IBase> baseInterface = ret;
if (baseInterface != nullptr) {
//baseInterface转换为ICameraProvider类型
iface = ICameraProvider::castFrom(baseInterface);
if (!getStub || trebleTestingOverride) {
iface = new BsCameraProvider(iface);
}
}
}
}
}
//返回ICameraProvider对象
return iface;
}
camerarpovider
的transport
属性定义如下:
//device\qcom\projectName\manifest.xml
<!-- fingerprint hal: using remote service instead of Google's default service-->
<hal format="hidl">
<name>android.hardware.camera.provider</name>
<transport>hwbinder</transport>
<impl level="generic"></impl>
<version>2.4</version>
<interface>
<name>ICameraProvider</name>
<instance>legacy/0</instance>
</interface>
</hal>
接着分析下getPassthroughServiceManager
//system\libhidl\transport\ServiceManagement.cpp
sp<IServiceManager1_0> getPassthroughServiceManager() {
return getPassthroughServiceManager1_1();
}
sp<IServiceManager1_1> getPassthroughServiceManager1_1() {
//新建PassthroughServiceManager对象
static sp<PassthroughServiceManager> manager(new PassthroughServiceManager());
return manager;
}
通过上述代码看,getPassthroughServiceManager
实现的是创建一个新的PassthroughServiceManager
对象并返回该对象。
接着分析下PassthroughServiceManager
的get
方法:
//\system\libhidl\transport\ServiceManagement.cpp
//PassthroughServiceManager::get
Return<sp<IBase>> get(const hidl_string& fqName,
const hidl_string& name) override {
sp<IBase> ret = nullptr;
//调用openLibs方法
openLibs(fqName, [&](void* handle, const std::string &lib, const std::string &sym) {
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);
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;
}
先分析下openLibs方法:
//system\libhidl\transport\ServiceManagement.cpp
//PassthroughServiceManager::openLibs方法
//fqName为[email protected]::ICameraProvider
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;
}
//对应cameraprovider packageAndVersion为[email protected]
std::string packageAndVersion = fqName.substr(0, idx);
//对应cameraprovider ifaceName为ICameraProvider
std::string ifaceName = fqName.substr(idx + strlen("::"));
//对应cameraprovider prefix为[email protected]
const std::string prefix = packageAndVersion + "-impl";
//对应cameraprovider sym 为HIDL_FETCH_ICameraProvider
const std::string sym = "HIDL_FETCH_" + ifaceName;
const int dlMode = RTLD_LAZY;
void *handle = nullptr;
dlerror(); // clear
//查找的几个路径为/odm/lib(64)/hw/;/vendor/lib(64)/hw/;/system/lib(64)/vndk-sp/hw/;system/lib(64)/hw/
std::vector<std::string> paths = {
HAL_LIBRARY_PATH_ODM, HAL_LIBRARY_PATH_VENDOR,
HAL_LIBRARY_PATH_VNDK_SP, HAL_LIBRARY_PATH_SYSTEM};
.....
for (const std::string& path : paths) {
//查找名字为[email protected]的so
std::vector<std::string> libs = search(path, prefix, ".so");
for (const std::string &lib : libs) {
const std::string fullPath = path + lib;
//如果so不在system/lib(64)/hw/下边,调用android_load_sphal_library打开so获取其句柄值handle
//android_load_sphal_library这个函数就不分析了。其实现和 dlopen相似,
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;
}
//调用eachLib函数将handle,[email protected],
//sym=HIDL_FETCH_ICameraProvider
//回调给上层调用openLibs
if (!eachLib(handle, lib, sym)) {
return;
}
}
}
}
接着分析下eachLib
,其是一个lamda
函数,实现为:
std::function<bool /* continue */(void* /* handle */,const std::string& /* lib */, const std::string& /* sym */)> eachLib =
[&](void* handle, const std::string &lib, const std::string &sym) {
//定义一个类型为IBase*(*)(const char* )的变量generator
IBase* (*generator)(const char* name);
//调用dlsym方法获取HIDL_FETCH_ICameraProvider方法并赋值给generator
*(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);
return true;
}
//调用HIDL_FETCH_ICameraProvider方法
//ret的类型为 sp<IBase> ret
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;
}
接着分析下HIDL_FETCH_ICameraProvider
:
//hardware\interfaces\camera\provider\2.4\default\CameraProvider.cpp
ICameraProvider* HIDL_FETCH_ICameraProvider(const char* name) {
if (strcmp(name, kLegacyProviderName) != 0) {
return nullptr;
}
//新建一个CameraProvider对象
CameraProvider* provider = new CameraProvider();
if (provider == nullptr) {
ALOGE("%s: cannot allocate camera provider!", __FUNCTION__);
return nullptr;
}
if (provider->isInitFailed()) {
ALOGE("%s: camera provider init failed!", __FUNCTION__);
delete provider;
return nullptr;
}
return provider;
}
通过上述分析,HIDL_FETCH_ICameraProvider
方法,新建一个CameraProvider
对象,然后返回该对象。
通过上述分析,Return<sp<IBase>>PassthroughServiceManager::get(const hidl_string& fqName,const hidl_string& name)
方法,是通过dlopen的方式打开cameraprovider定义的so:[email protected]
,然后通过dlsym
获取其内部的c方法HIDL_FETCH_ICameraProvider,来获取对应的CameraProvider对象。整个该过程,都是在本进程中完成的,即Passthrough
(直通)式。
2. 下边分析下ICameraProvider::registerAsService(const std::string &serviceName)
的流程
上一步已经通过passthrough的方式获取了ICameraProvider的子类对象CameraProvider
接着分析下其注册服务给hwServiceManager的流程
//out\soong\.intermediates\hardware\interfaces\camera\provider\2.4\[email protected]_genc++\gen\android\hardware\camera\provider\2.4\CameraProviderAll.cpp
::android::status_t ICameraProvider::registerAsService(const std::string &serviceName) {
::android::hardware::details::onRegistration("[email protected]", "ICameraProvider", serviceName);
//获取IServiceManager的代理对象BpHwServiceManager
const ::android::sp<::android::hidl::manager::V1_0::IServiceManager> sm
= ::android::hardware::defaultServiceManager();
if (sm == nullptr) {
return ::android::INVALID_OPERATION;
}
//调用add注册服务ICameraProvider
::android::hardware::Return<bool> ret = sm->add(serviceName.c_str(), this);
return ret.isOk() && ret ? ::android::OK : ::android::UNKNOWN_ERROR;
}
接着分析下 BpHwServiceManager::add(const ::android::hardware::hidl_string& name, const ::android::sp<::android::hidl::base::V1_0::IBase>& service)方法
//out\soong\.intermediates\system\libhidl\transport\manager\1.1\[email protected]_genc++\gen\android\hidl\manager\1.1\ServiceManagerAll.cpp
//name为"legacy/0";service为passthrough方式获得的ICameraProvider对象
::android::hardware::Return<bool> BpHwServiceManager::add(const ::android::hardware::hidl_string& name, const ::android::sp<::android::hidl::base::V1_0::IBase>& service){
::android::hardware::Return<bool> _hidl_out = ::android::hidl::manager::V1_0::BpHwServiceManager::_hidl_add(this, this, name, service);
return _hidl_out;
}
接着调用了::android::hidl::manager::V1_0::BpHwServiceManager::_hidl_add
方法
//out\soong\.intermediates\system\libhidl\transport\manager\1.0\[email protected]_genc++\gen\android\hidl\manager\1.0\ServiceManagerAll.cpp
::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) {
....
::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 {
//将ICameraProvider对象转换为BnHwCameraProvider对象,
//::android::hardware::toBinder的实现在
///system/libhidl/transport/include/hidl/HidlBinderSupport.h
//稍后重点分析下
::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();
//给BnHwServiceManager发送消息添加服务
_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);
....
_hidl_status.setFromStatusT(_hidl_err);
return ::android::hardware::Return<bool>(_hidl_out_success);
_hidl_error:
_hidl_status.setFromStatusT(_hidl_err);
return ::android::hardware::Return<bool>(_hidl_status);
}
接下来分析下如何将::android::hidl::base::V1_0::IBase
转换为::android::hardware::IBinder
//system\libhidl\transport\include\hidl\HidlBinderSupport.h
//IType为::android::hidl::base::V1_0::IBase
//但是传入的是IBase的子类ICameraProvider对象
template <typename IType>
sp<IBinder> toBinder(sp<IType> iface) {
IType *ifacePtr = iface.get();
if (ifacePtr == nullptr) {
return nullptr;
}
//ICameraProvider的isRemote为false
if (ifacePtr->isRemote()) {
return ::android::hardware::IInterface::asBinder(
static_cast<BpInterface<IType>*>(ifacePtr));
} else {
//
std::string myDescriptor = details::getDescriptor(ifacePtr);
//获取的myDescriptor为[email protected]::ICameraProvider
if (myDescriptor.empty()) {
// interfaceDescriptor fails
return nullptr;
}
// for get + set
std::unique_lock<std::mutex> _lock = details::gBnMap.lock();
wp<BHwBinder> wBnObj = details::gBnMap.getLocked(ifacePtr, nullptr);
sp<IBinder> sBnObj = wBnObj.promote();
if (sBnObj == nullptr) {
//获取的func为static_constructor设置的一个lamda函数,
//为value为[](void *iIntf) -> ::android::sp<::android::hardware::IBinder> {
// return new BnHwCameraProvider(static_cast<ICameraProvider *>(iIntf));
//} 的lamda函数
auto func = details::gBnConstructorMap.get(myDescriptor, nullptr);
if (!func) {
return nullptr;
}
//调用上一步获取的lamda函数,获取BnHwCameraProvider对象
sBnObj = sp<IBinder>(func(static_cast<void*>(ifacePtr)));
if (sBnObj != nullptr) {
details::gBnMap.setLocked(ifacePtr, static_cast<BHwBinder*>(sBnObj.get()));
}
}
//返回BnHwCameraProvider对象
return sBnObj;
}
}
下边介绍下gBnConstructorMap
的设置过程
//out\soong\.intermediates\hardware\interfaces\camera\provider\2.4\[email protected]_genc++\gen\android\hardware\camera\provider\2.4\CameraProviderAll.cpp
__attribute__((constructor))static void static_constructor() {
//该方法为gBnConstructorMap设置了一个key为[email protected]::ICameraProvider
//value为[](void *iIntf) -> ::android::sp<::android::hardware::IBinder> {
// return new BnHwCameraProvider(static_cast<ICameraProvider *>(iIntf));
// }
//的lamda函数
::android::hardware::details::gBnConstructorMap.set(ICameraProvider::descriptor,
[](void *iIntf) -> ::android::sp<::android::hardware::IBinder> {
return new BnHwCameraProvider(static_cast<ICameraProvider *>(iIntf));
});
//该方法为gBsConstructorMap设置了一个key为[email protected]::ICameraProvider
//value为[](void *iIntf) -> ::android::sp<::android::hidl::base::V1_0::IBase> {
// return new BsCameraProvider(static_cast<ICameraProvider *>(iIntf));
// }
// 的lamda函数,
::android::hardware::details::gBsConstructorMap.set(ICameraProvider::descriptor,
[](void *iIntf) -> ::android::sp<::android::hidl::base::V1_0::IBase> {
return new BsCameraProvider(static_cast<ICameraProvider *>(iIntf));
});
};
调用该lamda函数,会创建一个BnHwCameraProvider
,BnHwCameraProvider
构造函数实现如下:
//out\soong\.intermediates\hardware\interfaces\camera\provider\2.4\[email protected]_genc++\gen\android\hardware\camera\provider\2.4\CameraProviderAll.cpp
BnHwCameraProvider::BnHwCameraProvider(const ::android::sp<ICameraProvider> &_hidl_impl)
: ::android::hidl::base::V1_0::BnHwBase(_hidl_impl, "[email protected]", "ICameraProvider") {
//_hidl_mImpl成员变量是getPassThrough获得的ICameraProvider对象指针
_hidl_mImpl = _hidl_impl;
auto prio = ::android::hardware::details::gServicePrioMap.get(_hidl_impl, {
SCHED_NORMAL, 0});
mSchedPolicy = prio.sched_policy;
mSchedPriority = prio.prio;
}
接着继续分析下BnHwServiceManager
的_hidl_add
//out\soong\.intermediates\system\libhidl\transport\manager\1.0\[email protected]_genc++\gen\android\hidl\manager\1.0\ServiceManagerAll.cpp
::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) {
....
::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");
....
//调用ServiceManager的add方法,_hidl_mImpl变量是BnHwServiceManager构造函数赋值的ServiceManager对象
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);
....
_hidl_cb(*_hidl_reply);
return _hidl_err;
}
接着分析下ServiceManager的add方法
//system\hwservicemanager\ServiceManager.cpp
Return<bool> ServiceManager::add(const hidl_string& name, const sp<IBase>& service) {
bool isValidService = false;
if (service == nullptr) {
return false;
}
// 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 context = mAcl.getContext(pid);
//interfaceChain的定义在system\libhidl\transport\base\1.0\IBase.hal
//cameraProvider 返回的interfaceChain,size=1,
//interfaceChain[0]= [email protected]::ICameraProvider
auto ret = service->interfaceChain([&](const auto &interfaceChain) {
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, context, pid)) {
return;
}
}
for(size_t i = 0; i < interfaceChain.size(); i++) {
//fqName为[email protected]::ICameraProvider获取PackageInterfaceMap
std::string fqName = interfaceChain[i];
//通过fqName获取PackageInterfaceMap
PackageInterfaceMap &ifaceMap = mServiceMap[fqName];
//name为legacy/0,通过name获取HidlService
HidlService *hidlService = ifaceMap.lookup(name);
//如果hidlService为空,则将该服务插入到mServiceMap中,
//key值为[email protected]::ICameraProvider
//如果hidlService不为空,则替换mServiceMap中的值
if (hidlService == nullptr) {
ifaceMap.insertService(
std::make_unique<HidlService>(fqName, name, service, pid));
} else {
if (hidlService->getService() != nullptr) {
auto ret = hidlService->getService()->unlinkToDeath(this);
ret.isOk(); // ignore
}
hidlService->setService(service, pid);
}
ifaceMap.sendPackageRegistrationNotification(fqName, name);
}
auto linkRet = service->linkToDeath(this, 0 /*cookie*/);
linkRet.isOk(); // ignore
isValidService = true;
});
if (!ret.isOk()) {
LOG(ERROR) << "Failed to retrieve interface chain.";
return false;
}
return isValidService;
}
总结下registerAsService的流程。
- 将
ICameraProvider::getService(..)
获得的ICameraProvider
对象转换为BnHwCameraProvider
对象 - 通过hwbinder,将
BnHwCameraProvider
注册个hwservicemanager
**
至此,分析完成了CameraProvider
服务启动的完整流程。