源码基于:Android R
下图是android 8.0 之前binder 的软件框架,依赖的驱动设备是/dev/binder,binder机制的四要素分别是client、server、servicemanager和binder驱动。
对于android 8.0后的binder 和vndbinder依然同这个框架,只不过驱动的设备多加/dev/vndbinder
这篇主要分析servicemanger的流程,hwservicemanger后续补充。
先来看下该bin 文件产生:
frameworks/native/cmds/servicemanager/Android.bp
cc_binary {
name: "servicemanager",
defaults: ["servicemanager_defaults"],
init_rc: ["servicemanager.rc"],
srcs: ["main.cpp"],
}
cc_binary {
name: "vndservicemanager",
defaults: ["servicemanager_defaults"],
init_rc: ["vndservicemanager.rc"],
vendor: true,
cflags: [
"-DVENDORSERVICEMANAGER=1",
],
srcs: ["main.cpp"],
}
该目录下通过同样的main.cpp 编译出两个bin 文件:servicemanager 和 vndservicemanager,两个bin 文件对应不同的 *.rc 文件。
frameworks/native/cmds/servicemanager/servicemanager.rc
service servicemanager /system/bin/servicemanager
class core animation
user system
group system readproc
critical
onrestart restart healthd
onrestart restart zygote
onrestart restart audioserver
onrestart restart media
onrestart restart surfaceflinger
onrestart restart inputflinger
onrestart restart drm
onrestart restart cameraserver
onrestart restart keystore
onrestart restart gatekeeperd
onrestart restart thermalservice
writepid /dev/cpuset/system-background/tasks
shutdown critical
frameworks/native/cmds/servicemanager/vndservicemanager.rc
service vndservicemanager /vendor/bin/vndservicemanager /dev/vndbinder
class core
user system
group system readproc
writepid /dev/cpuset/system-background/tasks
shutdown critical
frameworks/native/cmds/servicemanager/main.cpp
int main(int argc, char** argv) {
if (argc > 2) {
LOG(FATAL) << "usage: " << argv[0] << " [binder driver]";
}
//根据参数确认代码的设备是binder还是vndbinder
const char* driver = argc == 2 ? argv[1] : "/dev/binder";
//驱动设备的初始化工作,后面第 3.1 节详细说明
sp ps = ProcessState::initWithDriver(driver);
//告知驱动最大线程数,并设定servicemanger的线程最大数
ps->setThreadPoolMaxThreadCount(0);
//调用处理,以error方式还是fatal
ps->setCallRestriction(ProcessState::CallRestriction::FATAL_IF_NOT_ONEWAY);
//核心的接口都在这里
sp manager = new ServiceManager(std::make_unique());
//将servicemanager作为一个特殊service添加进来
if (!manager->addService("manager", manager, false /*allowIsolated*/, IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT).isOk()) {
LOG(ERROR) << "Could not self register servicemanager";
}
//保存进程的context obj
IPCThreadState::self()->setTheContextObject(manager);
//通知驱动context mgr是该context
ps->becomeContextManager(nullptr, nullptr);
//servicemanager 中新建一个looper,用以处理binder消息
sp looper = Looper::prepare(false /*allowNonCallbacks*/);
//通知驱动进入looper,并开始监听驱动消息,并设立callback进行处理
BinderCallback::setupTo(looper);
ClientCallbackCallback::setupTo(looper, manager);
//启动looper,进入每次的poll处理,进程如果没有出现异常情况导致abort是不会退出的
while(true) {
looper->pollAll(-1);
}
// should not be reached
return EXIT_FAILURE;
}
frameworks/native/libs/binder/ProcessState.cpp
sp ProcessState::initWithDriver(const char* driver)
{
Mutex::Autolock _l(gProcessMutex);
if (gProcess != nullptr) {
// Allow for initWithDriver to be called repeatedly with the same
// driver.
if (!strcmp(gProcess->getDriverName().c_str(), driver)) {
return gProcess;
}
LOG_ALWAYS_FATAL("ProcessState was already initialized.");
}
if (access(driver, R_OK) == -1) {
ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
driver = "/dev/binder";
}
gProcess = new ProcessState(driver);
return gProcess;
}
函数的参数为driver 的设备名称,是 /dev/binder 还是 /dev/vndbinder。
另外的逻辑比较简单,ProcesState 是管理 “进程状态”,Binder 中每个进程都会有且只有一个mProcess 对象,如果该实例不为空,则确认该实例打开的driver 是否为当前需要init 的driver 名称;如果该实例不存在,则通过 new 创建一个。
详细的PorcessState 可以查看第 4 节。
核心的接口都是位于Servicemanager 中,这里构造时新建一个Access 对象,如下:
frameworks/native/cmds/servicemanager/ServiceManager.cpp
ServiceManager::ServiceManager(std::unique_ptr&& access) : mAccess(std::move(access)) {
...
}
ProcesState 是管理 “进程状态”,Binder 中每个进程都会有且只有一个mProcess 对象。该对象用以:
frameworks/native/libs/binder/ProcessState.cpp
ProcessState::ProcessState(const char *driver)
: mDriverName(String8(driver))
, mDriverFD(open_driver(driver))
, mVMStart(MAP_FAILED)
, mThreadCountLock(PTHREAD_MUTEX_INITIALIZER)
, mThreadCountDecrement(PTHREAD_COND_INITIALIZER)
, mExecutingThreadsCount(0)
, mMaxThreads(DEFAULT_MAX_BINDER_THREADS)
, mStarvationStartTimeMs(0)
, mBinderContextCheckFunc(nullptr)
, mBinderContextUserData(nullptr)
, mThreadPoolStarted(false)
, mThreadPoolSeq(1)
, mCallRestriction(CallRestriction::NONE)
{
// TODO(b/139016109): enforce in build system
#if defined(__ANDROID_APEX__)
LOG_ALWAYS_FATAL("Cannot use libbinder in APEX (only system.img libbinder) since it is not stable.");
#endif
if (mDriverFD >= 0) {
// mmap the binder, providing a chunk of virtual address space to receive transactions.
mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
if (mVMStart == MAP_FAILED) {
// *sigh*
ALOGE("Using %s failed: unable to mmap transaction memory.\n", mDriverName.c_str());
close(mDriverFD);
mDriverFD = -1;
mDriverName.clear();
}
}
#ifdef __ANDROID__
LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver '%s' could not be opened. Terminating.", driver);
#endif
}
该函数主要做了如下:
在初始化列表中,通过调用 open_driver() 代码设备驱动;
如果驱动open 成功,mDriverFD 被赋值后,通过mmap() 创建大小 BINDER_VM_SIZE 的buffer,用以接收 transactions 数据。
通过命令行可以确认这个大小,假设 servicemanager 的PID 为510,则通过:
cat /proc/510/maps 可以看到:
748c323000-748c421000 r--p 00000000 00:1f 4 /dev/binderfs/binder
不用奇怪为什么不是/dev/binder,软连接而已:
lrwxrwxrwx 1 root root 20 1970-01-01 05:43 binder -> /dev/binderfs/binder
lrwxrwxrwx 1 root root 22 1970-01-01 05:43 hwbinder -> /dev/binderfs/hwbinder
lrwxrwxrwx 1 root root 22 1970-01-01 05:43 vndbinder -> /dev/binderfs/vndbinder
ProcessState 使用self() 函数获取对象,因为有 vndbinder 和binder共用一份代码,所以如果需要使用 vndbinder,需要在调用 self() 函数前调用 initWithDriver() 来指定驱动设备名称。当然如果强制使用self() 函数,那么获取的单例针对的驱动设备为 kDefaultDriver。
frameworks/native/libs/binder/ProcessState.cpp
#ifdef __ANDROID_VNDK__
const char* kDefaultDriver = "/dev/vndbinder";
#else
const char* kDefaultDriver = "/dev/binder";
#endif
sp ProcessState::self()
{
Mutex::Autolock _l(gProcessMutex);
if (gProcess != nullptr) {
return gProcess;
}
gProcess = new ProcessState(kDefaultDriver);
return gProcess;
}
对于 binder 和 vndbinder 设备,在 ProcessState 构造的时候会在初始化列表中调用 open_driver() 来对设备进行open 和初始化。
frameworks/native/libs/binder/ProcessState.cpp
static int open_driver(const char *driver)
{
//通过系统调用open 设备
int fd = open(driver, O_RDWR | O_CLOEXEC);
if (fd >= 0) {
int vers = 0;
//如果open 成功,会查询binder version是否匹配
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;
}
//如果不是当前的version,为什么还是不return?
if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {
ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)! ioctl() return value: %d",
vers, BINDER_CURRENT_PROTOCOL_VERSION, result);
close(fd);
fd = -1;
}
size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;
//如果binder version 是当前的,会通知驱动设置最大的线程数
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 '%s' failed: %s\n", driver, strerror(errno));
}
return fd;
}
这里需要注意,每个进程创建的 binder 的最大线程数为:DEFAULT_MAX_BINDER_THREADS
frameworks/native/libs/binder/ProcessState.cpp
#define DEFAULT_MAX_BINDER_THREADS 15
对于servicemanager,main 函数中设定为0,也就是servicemanager 直接使用主线程,普通service 限制最大的binder thread为 15,详细在后面进行驱动分析。
frameworks/native/libs/binder/ProcessState.cpp
String8 ProcessState::makeBinderThreadName() {
int32_t s = android_atomic_add(1, &mThreadPoolSeq);
pid_t pid = getpid();
String8 name;
name.appendFormat("Binder:%d_%X", pid, s);
return name;
}
这是产生binder 线程名称的函数,通过变量 mThreadPoolSeq 控制顺序和个数,最终的binder 线程名称类似 Binder:1234_F。
线程的最大数量是规定的,如上一些中说到的 DEFAULT_MAX_BINDER_THREADS (默认为15)。
当然,也可以通过 setThreadPoolMaxThreadCount() 函数来设定最大线程数,在servicemanager 中就是通过该函数指定 max threads为0,详细见第 3 节。
frameworks/native/libs/binder/ProcessState.cpp
status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
status_t result = NO_ERROR;
if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
mMaxThreads = maxThreads;
} else {
result = -errno;
ALOGE("Binder ioctl to set max threads failed: %s", strerror(-result));
}
return result;
}
frameworks/native/libs/binder/ProcessState.cpp
void ProcessState::spawnPooledThread(bool isMain)
{
if (mThreadPoolStarted) {
String8 name = makeBinderThreadName();
ALOGV("Spawning new pooled thread, name=%s\n", name.string());
sp t = new PoolThread(isMain);
t->run(name.string());
}
}
这个用来卵生新的binder thread,PoolThread 继承自Thread,run 的时候会将 binder name 带入,所以,在打印线程堆栈时能知道第几个Binder 的线程。而每一个binder thread都会通过IPCThreadState 管理:
frameworks/native/libs/binder/ProcessState.cpp
class PoolThread : public Thread
{
public:
explicit PoolThread(bool isMain)
: mIsMain(isMain)
{
}
protected:
virtual bool threadLoop()
{
IPCThreadState::self()->joinThreadPool(mIsMain);
return false;
}
const bool mIsMain;
};
同 ProcessState 类,每个进程有很多的线程用来记录 “线程状态”,在每次binder 的BINDER_WRITE_READ 调用后,驱动都会根据情况确定是否需要spawn 线程,而创建一个PoolThread(详见ProcessState) 都会伴随一个IPCThreadState进行管理,而binder 线程中所有的操作都是通过 IPCThreadState 进行的。
frameworks/native/libs/binder/IPCThreadState.cpp
IPCThreadState::IPCThreadState()
: mProcess(ProcessState::self()),
mServingStackPointer(nullptr),
mWorkSource(kUnsetWorkSource),
mPropagateWorkSource(false),
mStrictModePolicy(0),
mLastTransactionBinderFlags(0),
mCallRestriction(mProcess->mCallRestriction)
{
pthread_setspecific(gTLS, this);
clearCaller();
mIn.setDataCapacity(256);
mOut.setDataCapacity(256);
}
frameworks/native/libs/binder/IPCThreadState.cpp
IPCThreadState* IPCThreadState::self()
{
if (gHaveTLS.load(std::memory_order_acquire)) {
restart:
const pthread_key_t k = gTLS;
IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k);
if (st) return st;
return new IPCThreadState;
}
// Racey, heuristic test for simultaneous shutdown.
if (gShutdown.load(std::memory_order_relaxed)) {
ALOGW("Calling IPCThreadState::self() during shutdown is dangerous, expect a crash.\n");
return nullptr;
}
pthread_mutex_lock(&gTLSMutex);
if (!gHaveTLS.load(std::memory_order_relaxed)) {
int key_create_value = pthread_key_create(&gTLS, threadDestructor);
if (key_create_value != 0) {
pthread_mutex_unlock(&gTLSMutex);
ALOGW("IPCThreadState::self() unable to create TLS key, expect a crash: %s\n",
strerror(key_create_value));
return nullptr;
}
gHaveTLS.store(true, std::memory_order_release);
}
pthread_mutex_unlock(&gTLSMutex);
goto restart;
}
每个线程创建后,都会通过pthread_getspecific() 确认TLS中是否有已经创建了IPCThreadState,如果有就直接返回,如果没有则新建一个。