init进程启动后,ServiceManager进程的启动,远比zygote要早,因为在启动zygote进程时需要用到ServiceManager进程的服务。ServiceManager是一个守护进程,它维护着系统服务和客户端的binder通信。
在init.rc中声明ServiceManager作为一个服务启动:
service servicemanager /system/bin/servicemanager
class core
user system
group system
critical
onrestart restart healthd
onrestart restart zygote
onrestart restart media
onrestart restart surfaceflinger
onrestart restart drm
init.rc在android5/system/core/rootdir/init.rc目录下
ServiceManager进程启动后,会执行frameworks/native/cmds/servicemanager/service_manager.c目录下的main方法:
int main(int argc, char **argv)
{
struct binder_state *bs;
//宏:#define BINDER_SERVICE_MANAGER ((void*)0)。表示ServiceManager对应的句柄为0,表面自己是服务器管理者。其他的Server进程句柄值都是大于0的。
void *svcmgr = BINDER_SERVICE_MANAGER;
//打开Binder设备,映射128K的内存地址空间
bs = binder_open(128*1024);
//告诉Binder驱动程序自己是Binder上下文管理者
if (binder_become_context_manager(bs)) {
ALOGE("cannot become context manager (%s)\n", strerror(errno));
return -1;
}
//ServiceManager对应的句柄赋值
svcmgr_handle = svcmgr;
//进入一个无线循环,充当server角色,等待Client的请求
binder_loop(bs, svcmgr_handler);
return 0;
}
在main方法中主要完成下面4个工作:
1、打开/dev/binder文件:open("/dev/binder",O_RDWR);
2、 建立128K内存映射:mmap(NULL, mapsize, PROT_READ,MAP_PRIVATE, bs->fd, 0);
3、通知Binder驱动程序它是守护进程:binder_become_context_manager(bs);
4、进入循环等待请求的到来:binder_loop(bs,svcmgr_handler);
位于frameworks/native/cmds/servicemanager/binder.c。函数返回值为binder_state*类型,里面记录着刚刚打开的binder驱动文件句柄以及mmap()映射到的最终目标地址。
struct binder_state
{
int fd; // 文件描述符,打开的/dev/binder设备
void* mapped; // 把设备文件/dev/binder映射到进程空间的起始地址
unsigned mapsize; // 映射内存空间的大小
};
struct binder_state *binder_open(unsigned mapsize)
{
struct binder_state *bs;
bs = malloc(sizeof(*bs));
if (!bs) {
errno = ENOMEM;
return 0;
}
//打开/dev/binder驱动文件
bs->fd = open("/dev/binder", O_RDWR);
if (bs->fd < 0) {
fprintf(stderr,"binder: cannot open device (%s)\n",
strerror(errno));
goto fail_open;
}
//设置要映射的空间大小128*1024
bs->mapsize = mapsize;
//开始映射
bs->mapped = mmap(NULL, mapsize, PROT_READ, MAP_PRIVATE, bs->fd, 0);
if (bs->mapped == MAP_FAILED) {
fprintf(stderr,"binder: cannot map device (%s)\n",
strerror(errno));
goto fail_map;
}
/* TODO: check version */
return bs;
fail_map:
close(bs->fd);
fail_open:
free(bs);
return 0;
}
其中,参数mapsize表示它希望把binder驱动文件的多少字节映射到本地空间。可以看到,ServiceManager Service和普通进程所映射的binder大小并不相同。它把binder驱动文件的128K字节映射到内存空间,而普通进程则会映射binder文件里的BINDER_VM_SIZE(即1M减去8K)字节。
此函数作用是让当前进程成为整个系统中唯一的上下文管理器,即service管理器。其代码非常简单,仅仅是把BINDER_SET_CONTEXT_MGR发送到binder驱动而已。源码如下:
int binder_become_context_manager(struct binder_state *bs)
{
return ioctl(bs->fd, BINDER_SET_CONTEXT_MGR, 0);
}
binder_loop(struct binder_state *bs, binder_handler func)函数源码位置在frameworks/native/cmds/servicemanager/binder.c。此时已经正式进入循环,转正为一个server。注意这个函数的参数:bs是文件/dev/binder的描述符,func是函数svcmgr_handler。
void binder_loop(struct binder_state *bs, binder_handler func)
{
int res;
struct binder_write_read bwr;
unsigned readbuf[32];
bwr.write_size = 0;
bwr.write_consumed = 0;
bwr.write_buffer = 0;
readbuf[0] = BC_ENTER_LOOPER;
binder_write(bs, readbuf, sizeof(unsigned));
for (;;) {
bwr.read_size = sizeof(readbuf);
bwr.read_consumed = 0;
bwr.read_buffer = (unsigned) readbuf;
//通过设备描述符,将数据发给binder驱动
res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);
if (res < 0) {
ALOGE("binder_loop: ioctl failed (%s)\n", strerror(errno));
break;
}
//解析驱动的数据,调用回调函数func
res = binder_parse(bs, 0, readbuf, bwr.read_consumed, func);
if (res == 0) {
ALOGE("binder_loop: unexpected reply?!\n");
break;
}
if (res < 0) {
ALOGE("binder_loop: io error %d %s\n", res, strerror(errno));
break;
}
}
}
这个函数主要是对binder文件解析并执行相应的指令。这个函数的大头其实就是那个一路传过来的svcmgr_handler函数,就是那个参数func。
int binder_parse(struct binder_state *bs, struct binder_io *bio,
uint32_t *ptr, uint32_t size, binder_handler func)
{
int r = 1;
uint32_t *end = ptr + (size / 4);
while (ptr < end) {
uint32_t cmd = *ptr++;
...
//注意这个BR_TRANSACTION
case BR_TRANSACTION: {
struct binder_txn *txn = (void *) ptr;
if ((end - ptr) * sizeof(uint32_t) < sizeof(struct binder_txn)) {
ALOGE("parse: txn too small!\n");
return -1;
}
binder_dump_txn(txn);
if (func) {
unsigned rdata[256/4];
struct binder_io msg;
struct binder_io reply;
int res;
bio_init(&reply, rdata, sizeof(rdata), 4);
bio_init_from_txn(&msg, txn);
res = func(bs, txn, &msg, &reply);
binder_send_reply(bs, &reply, txn->data, res);
}
ptr += sizeof(*txn) / sizeof(uint32_t);
break;
}
...
}
return r;
}
这个函数源码位置在frameworks/native/cmds/servicemanager/service_manager.c中
int svcmgr_handler(struct binder_state *bs,
struct binder_txn *txn,
struct binder_io *msg,
struct binder_io *reply)
{
...
switch(txn->code) {
//客户端获取服务的请求
case SVC_MGR_GET_SERVICE:
case SVC_MGR_CHECK_SERVICE:
s = bio_get_string16(msg, &len);
ptr = do_find_service(bs, s, len, txn->sender_euid);
if (!ptr)
break;
bio_put_ref(reply, ptr);
return 0;
//服务端请求添加服务
case SVC_MGR_ADD_SERVICE:
s = bio_get_string16(msg, &len);
ptr = bio_get_ref(msg);
allow_isolated = bio_get_uint32(msg) ? 1 : 0;
if (do_add_service(bs, s, len, ptr, txn->sender_euid, allow_isolated))
return -1;
break;
...
}
bio_put_uint32(reply, 0);
return 0;
}
svclist链表,记录着所有添加进系统的“service代理”信息,这些信息被组织成一条单向链表当应用调用getService()获取系统服务的代理接口时,servicemanager就会搜索这张svclist链表
struct svcinfo *svclist = 0;
struct svcinfo
{
struct svcinfo *next;
void *ptr;//记录的就是系统service对应的 binder句柄值
struct binder_death death;
int allow_isolated;
unsigned len;
uint16_t name[0];//系统服务的名称
};
这个函数源码位置在frameworks/native/cmds/servicemanager/service_manager.c下
int do_add_service(struct binder_state *bs,
uint16_t *s, unsigned len,
void *ptr, unsigned uid, int allow_isolated)
{
struct svcinfo *si;
//ALOGI("add_service('%s',%p,%s) uid=%d\n", str8(s), ptr,
// allow_isolated ? "allow_isolated" : "!allow_isolated", uid);
if (!ptr || (len == 0) || (len > 127))
return -1;
//查看该服务是否有注册权限
if (!svc_can_register(uid, s)) {
ALOGE("add_service('%s',%p) uid=%d - PERMISSION DENIED\n",
str8(s), ptr, uid);
return -1;
}
//在服务列表中查找服务
si = find_svc(s, len);
//查看该服务是否已经注册
if (si) {
if (si->ptr) {
ALOGE("add_service('%s',%p) uid=%d - ALREADY REGISTERED, OVERRIDE\n",
str8(s), ptr, uid);
svcinfo_death(bs, si);
}
si->ptr = ptr;
} else {
//如果没有注册,则创建一个,并添加到svclist服务列表的表首。
si = malloc(sizeof(*si) + (len + 1) * sizeof(uint16_t));
if (!si) {
ALOGE("add_service('%s',%p) uid=%d - OUT OF MEMORY\n",
str8(s), ptr, uid);
return -1;
}
si->ptr = ptr;
si->len = len;
memcpy(si->name, s, (len + 1) * sizeof(uint16_t));
si->name[len] = '\0';
si->death.func = svcinfo_death;
si->death.ptr = si;
si->allow_isolated = allow_isolated;
si->next = svclist;
svclist = si;
}
//通知binder设备有一个service注册进来。
binder_acquire(bs, ptr);
binder_link_to_death(bs, ptr, &si->death);
return 0;
}
在给Binder发送返回值时,构建了data的数据,并把reply放入其中,并标记了数据的大小,最后通过binder_write()函数将数据写到Binder中,而且写的方法仍然是调用ioctl()。
void binder_send_reply(struct binder_state *bs, struct binder_io *reply, void *buffer_to_free, int status) {
struct {
uint32_t cmd_free;
void *buffer;
uint32_t cmd_reply;
struct binder_txn txn;
} __attribute__((packed)) data;
data.cmd_free = BC_FREE_BUFFER;
data.buffer = buffer_to_free;
data.cmd_reply = BC_REPLY;
data.txn.target = 0;
data.txn.cookie = 0;
data.txn.code = 0;
if (status) {
data.txn.flags = TF_STATUS_CODE;
data.txn.data_size = sizeof(int);
data.txn.offs_size = 0;
data.txn.data = &status;
data.txn.offs = 0;
} else {
data.txn.flags = 0;
data.txn.data_size = reply->data - reply->data0;
data.txn.offs_size = ((char*) reply->offs) - ((char*) reply->offs0);
data.txn.data = reply->data0;
data.txn.offs = reply->offs0;
}
//向Binder写回应的数据
binder_write(bs, &data, sizeof(data));
}
int binder_write(struct binder_state *bs, void *data, unsigned len) {
struct binder_write_read bwr;
int res;
bwr.write_size = len;
bwr.write_consumed = 0;
bwr.write_buffer = (unsigned) data;
bwr.read_size = 0;
bwr.read_consumed = 0;
bwr.read_buffer = 0;
//向Binder写数据
res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr);
if (res < 0) {
fprintf(stderr,"binder_write: ioctl failed (%s)\n", strerror(errno));
}
return res;
}