./frameworks/native/libs/binder/ProcessState.cpp
./frameworks/native/include/binder/ProcessState.h
./frameworks/av/media/mediaserver/main_mediaserver.cpp
int main(int argc __unused, char** argv)
{
sp<ProcessState> proc(ProcessState::self());
sp<IServiceManager> sm = defaultServiceManager();
AudioFlinger::instantiate();
MediaPlayerService::instantiate(); //该函数内部调用addService,把MediaPlayerService信息 add到ServiceManager中
ProcessState::self()->startThreadPool();
IPCThreadState::self()->joinThreadPool();
}
分析 一
sp<ProcessState> proc(ProcessState::self());
sp<ProcessState> ProcessState::self()
{
Mutex::Autolock _l(gProcessMutex);
if (gProcess != NULL) {
return gProcess;
}
gProcess = new ProcessState; //创建单类了
return gProcess; //这里返回的是指针,但是函数返回的是sp<xxx> 看成 ProcessState
}
ProcessState::ProcessState()
: mDriverFD(open_driver()) //open Bind /dev/binder
, mVMStart(MAP_FAILED) //映射内存的起始地址
, mManagesContexts(false)
, mBinderContextCheckFunc(NULL)
, mBinderContextUserData(NULL)
, mThreadPoolStarted(false)
, mThreadPoolSeq(1)
{
if (mDriverFD >= 0) {
if (mVMStart == MAP_FAILED) {
//将fd映射为内存,这样内存的memcpy等操作就相当于write/read(fd)了
mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);
close(mDriverFD);
mDriverFD = -1;
}
}
}
打开/dev/binder设备,这样的话就相当于和内核binder机制有了交互的通道
映射fd到内存,设备的fd传进去后,估计这块内存是和binder设备共享的
分析 二
sp<IServiceManager> sm = defaultServiceManager();
./frameworks/native/libs/binder/IServiceManager.cpp
./frameworks/native/include/binder/IServiceManager.h
./frameworks/native/include/binder/IInterface.h
sp<IServiceManager> defaultServiceManager()
{
if (gDefaultServiceManager != NULL) return gDefaultServiceManager;
{
AutoMutex _l(gDefaultServiceManagerLock);
while (gDefaultServiceManager == NULL) {
gDefaultServiceManager = interface_cast<IServiceManager>(
ProcessState::self()->getContextObject(NULL));//==gDefaultServiceManager = interface_cast<IServiceManager>(new BpBinder(0));
if (gDefaultServiceManager == NULL)
sleep(1);
}
}
return gDefaultServiceManager;
}
template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)
{
return INTERFACE::asInterface(obj);
}
所以,上面等价于
inline sp<IServiceManager> interface_cast(const sp<IBinder>& obj)
{
return IServiceManager::asInterface(obj);
}
class IServiceManager : public IInterface
{
public:
DECLARE_META_INTERFACE(ServiceManager);
/**
* Retrieve an existing service, blocking for a few seconds
* if it doesn't yet exist.
*/
virtual sp<IBinder> getService( const String16& name) const = 0;
/**
* Retrieve an existing service, non-blocking.
*/
virtual sp<IBinder> checkService( const String16& name) const = 0;
/**
* Register a service.
*/
virtual status_t addService( const String16& name,
const sp<IBinder>& service,
bool allowIsolated = false) = 0;
/**
* Return list of all existing services.
*/
virtual Vector<String16> listServices() = 0;
}
这两个宏DECLARE_META_INTERFACE和IMPLEMENT_META_INTERFACE(INTERFACE, NAME)都在
#define DECLARE_META_INTERFACE(INTERFACE) \
static const android::String16 descriptor; \
static android::sp<I##INTERFACE> asInterface( \
const android::sp<android::IBinder>& obj); \
virtual const android::String16& getInterfaceDescriptor() const; \
I##INTERFACE(); \
virtual ~I##INTERFACE(); \
我们把它兑现到IServiceManager就是:
static const android::String16 descriptor; \
static android::sp<IServiceManager> asInterface( \
const android::sp<android::IBinder>& obj); \增加一个asInterface函数
virtual const android::String16& getInterfaceDescriptor() const; \增加一个描述字符串 增加一个get函数
IServiceManager(); \
virtual ~IServiceManager(); \;增加构造和虚析购函数...
IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager");
#define IMPLEMENT_META_INTERFACE(INTERFACE, NAME) \
const android::String16 I##INTERFACE::descriptor(NAME); \
const android::String16& \
I##INTERFACE::getInterfaceDescriptor() const { \
return I##INTERFACE::descriptor; \
} \
android::sp<I##INTERFACE> I##INTERFACE::asInterface( \
const android::sp<android::IBinder>& obj) \
{ \
android::sp<I##INTERFACE> intr; \
if (obj != NULL) { \
intr = static_cast<I##INTERFACE*>( \
obj->queryLocalInterface( \
I##INTERFACE::descriptor).get()); \
if (intr == NULL) { \
intr = new Bp##INTERFACE(obj); \
} \
} \
return intr; \
} \
I##INTERFACE::I##INTERFACE() { } \
I##INTERFACE::~I##INTERFACE() { } \
我们把它兑现到IServiceManager就是:
const android::String16 IServiceManager::descriptor("android.os.IServiceManager"); \
const android::String16& \
IServiceManager::getInterfaceDescriptor() const { \
return IServiceManager::descriptor; \返回上面那个android.os.IServiceManager
} android::sp<IServiceManager>
} \
android::sp<IServiceManager> IServiceManager::asInterface( \
const android::sp<android::IBinder>& obj) \
{ \
android::sp<IServiceManager> intr; \
if (obj != NULL) { \
intr = static_cast<IServiceManager*>( \
obj->queryLocalInterface( \
IServiceManager::descriptor).get()); \
if (intr == NULL) { \
intr = new BpServiceManager(obj); //,终于看到和IServiceManager相关的东西了,看来 实际返回的是BpServiceManager(new BpBinder(0));
} \
} \
return intr; \
} \
IServiceManager::IServiceManager() { } \
IServiceManager::~IServiceManager() { } \
IServiceManager::asInterface(obj);
interface_cast<IServiceManager>(new BpBinder(0));
我们刚才解析过的 interface_cast<IServiceManager>(new BpBinder(0)),
原来就是调用 asInterface(new BpBinder(0))
BpServiceManager
终于可以讲解点架构上的东西了。p是proxy即代理的意思,Bp就是BinderProxy,
BpServiceManager,就是SM的Binder代理。既然是代理,那肯定希望对用户是透明的,那就是说头文件里边不会有这个Bp的定义。是吗?
果然,BpServiceManager就在刚才的IServiceManager.cpp中定义。
class BpServiceManager : public BpInterface<IServiceManager>
{
}
sp<IServiceManager> sm = defaultServiceManager();
返回的实际是BpServiceManager,它的remote对象是BpBinder,传入的那个handle参数是0。
分析 三
./frameworks/av/media/libmediaplayerservice/MediaPlayerService.cpp:499
./frameworks/av/media/libmediaplayerservice/MediaPlayerService.h
void MediaPlayerService::instantiate() {
defaultServiceManager()->addService(
String16("media.player"), new MediaPlayerService());
}
MediaPlayerService::MediaPlayerService()
{
mNextConnId = 1;
// reset battery stats
// if the mediaserver has crashed, battery stats could be left
// in bad state, reset the state upon service start.
const sp<IServiceManager> sm(defaultServiceManager());
if (sm != NULL) {
const String16 name("batterystats");
sp<IBatteryStats> batteryStats =
interface_cast<IBatteryStats>(sm->getService(name));
if (batteryStats != NULL) {
batteryStats->noteResetVideo();
batteryStats->noteResetAudio();
}
}
MediaPlayerFactory::registerBuiltinFactories();
}
MediaPlayerService 从 BnMediaPlayerService派生
class MediaPlayerService : public BnMediaPlayerService
Bn 是Binder Native的含义,是和Bp相对的,Bp的p是proxy代理的意思,那么另一端一定有一个和代理打交道的东西,这个就是Bn。
讲到这里会有点乱喔。先分析下,到目前为止都构造出来了什么。
l BpServiceManager
l BnMediaPlayerService
这两个东西不是相对的两端,从BnXXX就可以判断,BpServiceManager对应的应该是BnServiceManager,BnMediaPlayerService对应的应该是BpMediaPlayerService。
我们现在在哪里?对了,我们现在是创建了BnMediaPlayerService,想把它加入到系统的中去。
喔,明白了。我创建一个新的Service—BnMediaPlayerService,想把它告诉ServiceManager。
那我怎么和ServiceManager通讯呢?恩,利用BpServiceManager。所以嘛,我调用了BpServiceManager的addService函数!
为什么要搞个ServiceManager来呢?这个和Android机制有关系。所有Service都需要加入到ServiceManager来管理。同时也方便了Client来查询系统存在哪些Service,
没看见我们传入了字符串吗?这样就可以通过Human Readable的字符串来查找Service了。
addService(String16("media.player"), new MediaPlayerService());
virtual status_t addService(const String16& name, const sp<IBinder>& service)
status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);
tatus_t status = IPCThreadState::self()->transact( mHandle, code, data, reply, flags);
err = writeTransactionData(BC_TRANSACTION, flags, handle, code, data, NULL);
binder_transaction_data tr;
mOut.writeInt32(cmd);
mOut.write(&tr, sizeof(tr));
status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult)
talkWithDriver()
ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr) >= 0
分析 四
./frameworks/native/cmds/servicemanager/service_manager.c
BnServiceManager /处理BpServiceManager发过来的命令
int main(int argc, char **argv)
{
struct binder_state *bs;
bs = binder_open(128*1024);
if (binder_become_context_manager(bs)) { //成为manager
ALOGE("cannot become context manager (%s)\n", strerror(errno));
return -1;
}
selinux_enabled = is_selinux_enabled();
sehandle = selinux_android_service_context_handle();
if (selinux_enabled > 0) {
if (sehandle == NULL) {
ALOGE("SELinux: Failed to acquire sehandle. Aborting.\n");
abort();
}
if (getcon(&service_manager_context) != 0) {
ALOGE("SELinux: Failed to acquire service_manager context. Aborting.\n");
abort();
union selinux_callback cb;
cb.func_audit = audit_callback;
selinux_set_callback(SELINUX_CB_AUDIT, cb);
cb.func_log = selinux_log_callback;
selinux_set_callback(SELINUX_CB_LOG, cb);
svcmgr_handle = BINDER_SERVICE_MANAGER;
binder_loop(bs, svcmgr_handler); //处理BpServiceManager发过来的命令
return 0;
}
int binder_become_context_manager(struct binder_state *bs)
{
return ioctl(bs->fd, BINDER_SET_CONTEXT_MGR, 0);//把自己设为MANAGER
}
svcmgr_handler
do_add_service(bs, s, len, ptr, txn->sender_euid) //do_add_service真正添加BnMediaService信息
ServiceManager存在的意义
为何需要一个这样的东西呢?
原来,Android系统中Service信息都是先add到ServiceManager中,由ServiceManager来集中管理,
这样就可以查询当前系统有哪些服务。而且,Android系统中某个服务例如MediaPlayerService的客户端想要和MediaPlayerService通讯的话,
必须先向ServiceManager查询MediaPlayerService的信息,然后通过ServiceManager返回的东西再来和MediaPlayerService交互。
毕竟,要是MediaPlayerService身体不好,老是挂掉的话,客户的代码就麻烦了,就不知道后续新生的MediaPlayerService的信息了,所以只能这样:
l MediaPlayerService向SM注册
l MediaPlayerClient查询当前注册在SM中的MediaPlayerService的信息
l 根据这个信息,MediaPlayerClient和MediaPlayerService交互
另外,ServiceManager的handle标示是0,所以只要往handle是0的服务发送消息了,最终都会被传递到ServiceManager中去。
三 MediaService的运行
上一节的知识,我们知道了:
l defaultServiceManager得到了BpServiceManager,然后MediaPlayerService 实例化后,调用BpServiceManager的addService函数
l 这个过程中,是service_manager收到addService的请求,然后把对应信息放到自己保存的一个服务list中
到这儿,我们可看到,service_manager有一个binder_looper函数,专门等着从binder中接收请求。
虽然service_manager没有从BnServiceManager中派生,但是它肯定完成了BnServiceManager的功能。
同样,我们创建了MediaPlayerService即BnMediaPlayerService,那它也应该:
l 打开binder设备
l 也搞一个looper循环,然后坐等请求
service,service,这个和网络编程中的监听socket的工作很像嘛!