├── README.md ├── external └── binder │ ├── client │ ├── Android.mk │ └── FregClient.cpp │ ├── common │ ├── IFregService.cpp │ └── IFregService.h │ └── server │ ├── Android.mk │ └── FregServer.cpp ├── frameworks └── base │ ├── cmds │ └── servicemanager │ │ ├── binder.c │ │ ├── binder.h │ │ └── service_manager.c │ ├── core │ ├── java │ │ ├── android │ │ │ └── os │ │ │ │ ├── Binder.java │ │ │ │ ├── Parcel.java │ │ │ │ ├── ServiceManager.java │ │ │ │ └── ServiceManagerNative.java │ │ └── com │ │ │ └── android │ │ │ └── internal │ │ │ └── os │ │ │ └── BinderInternal.java │ └── jni │ │ └── android_util_Binder.cpp │ ├── include │ └── binder │ │ ├── Binder.h │ │ ├── BpBinder.h │ │ ├── IBinder.h │ │ ├── IInterface.h │ │ ├── IPCThreadState.h │ │ ├── IPermissionController.h │ │ ├── IServiceManager.h │ │ ├── Parcel.h │ │ └── ProcessState.h │ └── libs │ └── binder │ ├── Binder.cpp │ ├── BpBinder.cpp │ ├── IInterface.cpp │ ├── IPCThreadState.cpp │ ├── IServiceManager.cpp │ ├── Parcel.cpp │ └── ProcessState.cpp ├── kernel └── goldfish │ └── drivers │ └── staging │ └── android │ ├── binder.c │ └── binder.h ├── out └── target │ └── common │ └── obj │ └── JAVA_LIBRARIES │ └── framework_intermediates │ └── src │ └── core │ └── java │ └── android │ └── os │ └── IFregService.java └── system └── core └── rootdir └── init.rc /README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RickAi/Binder_SourceCode/9272e54843c1abceb23938a076079b95317426a9/README.md -------------------------------------------------------------------------------- /external/binder/client/Android.mk: -------------------------------------------------------------------------------- 1 | LOCAL_PATH := $(call my-dir) 2 | 3 | include $(CLEAR_VARS) 4 | 5 | LOCAL_MODULE_TAGS := optional 6 | 7 | LOCAL_SRC_FILES := ../common/IFregService.cpp \ 8 | FregClient.cpp 9 | 10 | LOCAL_SHARED_LIBRARIES:= libcutils libutils libbinder 11 | 12 | LOCAL_MODULE := FregClient 13 | 14 | include $(BUILD_EXECUTABLE) 15 | -------------------------------------------------------------------------------- /external/binder/client/FregClient.cpp: -------------------------------------------------------------------------------- 1 | #define LOG_TAG "FregClient" 2 | 3 | #include 4 | #include 5 | 6 | #include "../common/IFregService.h" 7 | 8 | // client模块的入口函数 9 | int main() 10 | { 11 | // 获取一个类型为BpBinder的代理对象 12 | sp binder = defaultServiceManager()->getService(String16(FREG_SERVICE)); 13 | if(binder == NULL) { 14 | LOGE("Failed to get freg service: %s.\n", FREG_SERVICE); 15 | return -1; 16 | } 17 | 18 | // 获得IFregService接口 19 | sp service = IFregService::asInterface(binder); 20 | if(service == NULL) { 21 | LOGE("Failed to get freg service interface.\n"); 22 | return -2; 23 | } 24 | 25 | printf("Read original value from FregService:\n"); 26 | 27 | int32_t val = service->getVal(); 28 | printf(" %d.\n", val); 29 | 30 | printf("Add value 1 to FregService.\n"); 31 | 32 | // 调用接口 33 | val += 1; 34 | service->setVal(val); 35 | 36 | printf("Read the value from FregService again:\n"); 37 | 38 | val = service->getVal(); 39 | printf(" %d.\n", val); 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /external/binder/common/IFregService.cpp: -------------------------------------------------------------------------------- 1 | #define LOG_TAG "IFregService" 2 | 3 | #include 4 | 5 | #include "IFregService.h" 6 | 7 | using namespace android; 8 | 9 | enum 10 | { 11 | // 定义了两个进程间通信代码 12 | GET_VAL = IBinder::FIRST_CALL_TRANSACTION, 13 | SET_VAL 14 | }; 15 | 16 | // 定义代理对象类 17 | // 继承BnInterface 18 | // 实现IFregService接口 19 | class BpFregService: public BpInterface 20 | { 21 | public: 22 | BpFregService(const sp& impl) 23 | : BpInterface(impl) 24 | { 25 | 26 | } 27 | 28 | public: 29 | int32_t getVal() 30 | { 31 | // 将要传递的数据封装到data中 32 | Parcel data; 33 | data.writeInterfaceToken(IFregService::getInterfaceDescriptor()); 34 | 35 | Parcel reply; 36 | // 获取一个代理对象,调用transact函数请求运行在Server进程的一个Binder本地对象 37 | // 执行GET_VAL操作 38 | // 返回的结果是一个整数,封装在reply中 39 | remote()->transact(GET_VAL, data, &reply); 40 | 41 | int32_t val = reply.readInt32(); 42 | 43 | return val; 44 | } 45 | 46 | void setVal(int32_t val) 47 | { 48 | Parcel data; 49 | data.writeInterfaceToken(IFregService::getInterfaceDescriptor()); 50 | data.writeInt32(val); 51 | 52 | Parcel reply; 53 | remote()->transact(SET_VAL, data, &reply); 54 | } 55 | 56 | }; 57 | 58 | IMPLEMENT_META_INTERFACE(FregService, "shy.luo.IFregService"); 59 | 60 | // 定义了BnFregService成员函数onTransact 61 | // 将GET_VAL和SET_VAL进程间通信请求分发给其子类的成员函数getVal和setVal来处理 62 | status_t BnFregService::onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 63 | { 64 | switch(code) 65 | { 66 | case GET_VAL: 67 | { 68 | // 在进行进程间通信请求分发给其子类处理之前,会首先调用宏CHECK_INTERFACE来检查该进程 69 | // 间通信请求的合法性 70 | // 即检查该请求是否是由FregService组件的代理对象发送过来的 71 | CHECK_INTERFACE(IFregService, data, reply); 72 | 73 | int32_t val = getVal(); 74 | reply->writeInt32(val); 75 | 76 | return NO_ERROR; 77 | } 78 | case SET_VAL: 79 | { 80 | CHECK_INTERFACE(IFregService, data, reply); 81 | 82 | int32_t val = data.readInt32(); 83 | setVal(val); 84 | 85 | return NO_ERROR; 86 | } 87 | default: 88 | { 89 | return BBinder::onTransact(code, data, reply, flags); 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /external/binder/common/IFregService.h: -------------------------------------------------------------------------------- 1 | #ifndef IFREGSERVICE_H_ 2 | #define IFREGSERVICE_H_ 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | // 定义宏FREG_SERVICE来描述Service组件FregService注册到Service Manager的名称 9 | #define FREG_SERVICE "shy.luo.FregService" 10 | 11 | using namespace android; 12 | 13 | // 定义一个硬件访问服务接口 14 | class IFregService: public IInterface 15 | { 16 | public: 17 | DECLARE_META_INTERFACE(FregService); 18 | // 成员函数 19 | virtual int32_t getVal() = 0; 20 | virtual void setVal(int32_t val) = 0; 21 | }; 22 | 23 | // 定义一个Binder本地对象类BnFregService 24 | class BnFregService: public BnInterface 25 | { 26 | public: 27 | virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0); 28 | }; 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /external/binder/server/Android.mk: -------------------------------------------------------------------------------- 1 | LOCAL_PATH := $(call my-dir) 2 | 3 | include $(CLEAR_VARS) 4 | 5 | LOCAL_MODULE_TAGS := optional 6 | 7 | LOCAL_SRC_FILES := ../common/IFregService.cpp \ 8 | FregServer.cpp 9 | 10 | LOCAL_SHARED_LIBRARIES:= libcutils libutils libbinder 11 | 12 | LOCAL_MODULE := FregServer 13 | 14 | include $(BUILD_EXECUTABLE) 15 | -------------------------------------------------------------------------------- /external/binder/server/FregServer.cpp: -------------------------------------------------------------------------------- 1 | #define LOG_TAG "FregServer" 2 | 3 | #include 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | #include "../common/IFregService.h" 11 | 12 | #define FREG_DEVICE_NAME "/dev/freg" 13 | 14 | // server模块的源代码 15 | // 继承自BnFregService,实现了IFregService接口 16 | class FregService : public BnFregService 17 | { 18 | public: 19 | // 在析造函数中会调用open来打开设备文件 20 | FregService() 21 | { 22 | fd = open(FREG_DEVICE_NAME, O_RDWR); 23 | if(fd == -1) { 24 | LOGE("Failed to open device %s.\n", FREG_DEVICE_NAME); 25 | } 26 | } 27 | 28 | virtual ~FregService() 29 | { 30 | if(fd != -1) { 31 | close(fd); 32 | } 33 | } 34 | 35 | public: 36 | static void instantiate() 37 | { 38 | // 获取service manager对象,注册service 39 | defaultServiceManager()->addService(String16(FREG_SERVICE), new FregService()); 40 | } 41 | 42 | int32_t getVal() 43 | { 44 | int32_t val = 0; 45 | 46 | if(fd != -1) { 47 | read(fd, &val, sizeof(val)); 48 | } 49 | 50 | return val; 51 | } 52 | 53 | void setVal(int32_t val) 54 | { 55 | if(fd != -1) { 56 | write(fd, &val, sizeof(val)); 57 | } 58 | } 59 | 60 | private: 61 | int fd; 62 | }; 63 | 64 | int main(int argc, char** argv) 65 | { 66 | // 首先调用静态成员函数将FregService组件注册到Service Manager中 67 | FregService::instantiate(); 68 | 69 | // 启动一个Binder线程池 70 | ProcessState::self()->startThreadPool(); 71 | // 调用主线程的IPCThreadState对象的成员函数添加到进程的Binder线程池中,用来处理来自Client进程通信 72 | IPCThreadState::self()->joinThreadPool(); 73 | 74 | return 0; 75 | } 76 | -------------------------------------------------------------------------------- /frameworks/base/cmds/servicemanager/binder.c: -------------------------------------------------------------------------------- 1 | /* Copyright 2008 The Android Open Source Project 2 | */ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include "binder.h" 12 | 13 | #define MAX_BIO_SIZE (1 << 30) 14 | 15 | #define TRACE 0 16 | 17 | #define LOG_TAG "Binder" 18 | #include 19 | 20 | void bio_init_from_txn(struct binder_io *io, struct binder_txn *txn); 21 | 22 | #if TRACE 23 | void hexdump(void *_data, unsigned len) 24 | { 25 | unsigned char *data = _data; 26 | unsigned count; 27 | 28 | for (count = 0; count < len; count++) { 29 | if ((count & 15) == 0) 30 | fprintf(stderr,"%04x:", count); 31 | fprintf(stderr," %02x %c", *data, 32 | (*data < 32) || (*data > 126) ? '.' : *data); 33 | data++; 34 | if ((count & 15) == 15) 35 | fprintf(stderr,"\n"); 36 | } 37 | if ((count & 15) != 0) 38 | fprintf(stderr,"\n"); 39 | } 40 | 41 | void binder_dump_txn(struct binder_txn *txn) 42 | { 43 | struct binder_object *obj; 44 | unsigned *offs = txn->offs; 45 | unsigned count = txn->offs_size / 4; 46 | 47 | fprintf(stderr," target %p cookie %p code %08x flags %08x\n", 48 | txn->target, txn->cookie, txn->code, txn->flags); 49 | fprintf(stderr," pid %8d uid %8d data %8d offs %8d\n", 50 | txn->sender_pid, txn->sender_euid, txn->data_size, txn->offs_size); 51 | hexdump(txn->data, txn->data_size); 52 | while (count--) { 53 | obj = (void*) (((char*) txn->data) + *offs++); 54 | fprintf(stderr," - type %08x flags %08x ptr %p cookie %p\n", 55 | obj->type, obj->flags, obj->pointer, obj->cookie); 56 | } 57 | } 58 | 59 | #define NAME(n) case n: return #n 60 | const char *cmd_name(uint32_t cmd) 61 | { 62 | switch(cmd) { 63 | NAME(BR_NOOP); 64 | NAME(BR_TRANSACTION_COMPLETE); 65 | NAME(BR_INCREFS); 66 | NAME(BR_ACQUIRE); 67 | NAME(BR_RELEASE); 68 | NAME(BR_DECREFS); 69 | NAME(BR_TRANSACTION); 70 | NAME(BR_REPLY); 71 | NAME(BR_FAILED_REPLY); 72 | NAME(BR_DEAD_REPLY); 73 | NAME(BR_DEAD_BINDER); 74 | default: return "???"; 75 | } 76 | } 77 | #else 78 | #define hexdump(a,b) do{} while (0) 79 | #define binder_dump_txn(txn) do{} while (0) 80 | #endif 81 | 82 | // 表示结构体binder_io内部的数据缓冲区是一块在内核空间分配的内核缓冲区 83 | // 可以通过用户空间地址来共享访问 84 | // 当使用完成这个数据缓冲区之后,它就可以使用BC_FREE_BUFFER命令协议来通知Binder驱动释放相应的内核缓冲区 85 | #define BIO_F_SHARED 0x01 /* needs to be buffer freed */ 86 | // 表示两个错误码 87 | // 88 | // 表示数据溢出,上次读出的数据大小超出了其内部的数据缓冲区大小 89 | #define BIO_F_OVERFLOW 0x02 /* ran out of space */ 90 | // 上次从结构体binder_io读数据时发生了IO错误 91 | #define BIO_F_IOERROR 0x04 92 | // binder_io内部的数据缓冲区是通过malloc来分配的 93 | // 它指的是一块在用户空间分配的缓冲区 94 | // 当进程完成这个数据缓冲区后,可以直接调用函数free释放 95 | #define BIO_F_MALLOCED 0x08 /* needs to be free()'d */ 96 | 97 | // Service Manager打开了设备文件/dev/binder之后,就会得到文件描述符 98 | struct binder_state 99 | { 100 | // 文件描述符保存在变量fd中 101 | int fd; 102 | // 打开设备文件后,需要将设备文件映射到进程的地址空间,以便可以为驱动分配内核缓冲区来保存进程通信数据 103 | // servicemanager需要将设备文件/dev/binder映射到自己的进程地址空间 104 | // 105 | // 映射后的起始地址 106 | void *mapped; 107 | // 映射后的地址空间大小 108 | unsigned mapsize; 109 | }; 110 | 111 | struct binder_state *binder_open(unsigned mapsize) 112 | { 113 | struct binder_state *bs; 114 | 115 | bs = malloc(sizeof(*bs)); 116 | if (!bs) { 117 | errno = ENOMEM; 118 | return 0; 119 | } 120 | 121 | // 打开设备文件 122 | bs->fd = open("/dev/binder", O_RDWR); 123 | if (bs->fd < 0) { 124 | fprintf(stderr,"binder: cannot open device (%s)\n", 125 | strerror(errno)); 126 | goto fail_open; 127 | } 128 | 129 | // mapsize是128*1024=128K 130 | bs->mapsize = mapsize; 131 | // 请求分配128K的内核缓冲区 132 | // 映射后得到的地址空间起始地址和大小分别保存在binder_state->mapped和mapsize中 133 | bs->mapped = mmap(NULL, mapsize, PROT_READ, MAP_PRIVATE, bs->fd, 0); 134 | if (bs->mapped == MAP_FAILED) { 135 | fprintf(stderr,"binder: cannot map device (%s)\n", 136 | strerror(errno)); 137 | goto fail_map; 138 | } 139 | 140 | /* TODO: check version */ 141 | 142 | return bs; 143 | 144 | fail_map: 145 | close(bs->fd); 146 | fail_open: 147 | free(bs); 148 | return 0; 149 | } 150 | 151 | void binder_close(struct binder_state *bs) 152 | { 153 | munmap(bs->mapped, bs->mapsize); 154 | close(bs->fd); 155 | free(bs); 156 | } 157 | 158 | int binder_become_context_manager(struct binder_state *bs) 159 | { 160 | return ioctl(bs->fd, BINDER_SET_CONTEXT_MGR, 0); 161 | } 162 | 163 | int binder_write(struct binder_state *bs, void *data, unsigned len) 164 | { 165 | struct binder_write_read bwr; 166 | int res; 167 | bwr.write_size = len; 168 | bwr.write_consumed = 0; 169 | bwr.write_buffer = (unsigned) data; 170 | // 输出缓冲区设置为空,当前线程将自己注册到Binder驱动后,就会马上返回用户空间 171 | // 不会在Binder驱动程序中等待Client 172 | bwr.read_size = 0; 173 | bwr.read_consumed = 0; 174 | bwr.read_buffer = 0; 175 | // 进行注册 176 | res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr); 177 | if (res < 0) { 178 | fprintf(stderr,"binder_write: ioctl failed (%s)\n", 179 | strerror(errno)); 180 | } 181 | return res; 182 | } 183 | 184 | // reply: binder_io结构体,内部包含了进程间通信结果数据 185 | // buffer_to_free:用户空间地址,指向了一块用来传输进程间通信数据的内核缓冲区 186 | // status: 用来描述servicemanager是否成功处理了一个进程间通信请求,即是否成功注册了service组件 187 | void binder_send_reply(struct binder_state *bs, 188 | struct binder_io *reply, 189 | void *buffer_to_free, 190 | int status) 191 | { 192 | // 匿名结构体 193 | // 用来描述一个BC_FREE_BUFFER和一个BC_REPLY命令协议 194 | struct { 195 | uint32_t cmd_free; 196 | void *buffer; 197 | uint32_t cmd_reply; 198 | struct binder_txn txn; 199 | } __attribute__((packed)) data; 200 | 201 | // 设置匿名结构体data中的BC_FREE_BUFFER命令协议内容 202 | data.cmd_free = BC_FREE_BUFFER; 203 | data.buffer = buffer_to_free; 204 | data.cmd_reply = BC_REPLY; 205 | data.txn.target = 0; 206 | data.txn.cookie = 0; 207 | data.txn.code = 0; 208 | if (status) { 209 | data.txn.flags = TF_STATUS_CODE; 210 | data.txn.data_size = sizeof(int); 211 | data.txn.offs_size = 0; 212 | data.txn.data = &status; 213 | data.txn.offs = 0; 214 | } else { 215 | data.txn.flags = 0; 216 | data.txn.data_size = reply->data - reply->data0; 217 | data.txn.offs_size = ((char*) reply->offs) - ((char*) reply->offs0); 218 | data.txn.data = reply->data0; 219 | data.txn.offs = reply->offs0; 220 | } 221 | // 将BC_FREE_BUFFER和BC_REPLY命令协议发送给Binder驱动程序 222 | binder_write(bs, &data, sizeof(data)); 223 | } 224 | 225 | // 处理从驱动接收到的返回协议 226 | int binder_parse(struct binder_state *bs, struct binder_io *bio, 227 | uint32_t *ptr, uint32_t size, binder_handler func) 228 | { 229 | int r = 1; 230 | uint32_t *end = ptr + (size / 4); 231 | 232 | while (ptr < end) { 233 | // 读出返回协议码 234 | uint32_t cmd = *ptr++; 235 | #if TRACE 236 | fprintf(stderr,"%s:\n", cmd_name(cmd)); 237 | #endif 238 | switch(cmd) { 239 | case BR_NOOP: 240 | break; 241 | case BR_TRANSACTION_COMPLETE: 242 | break; 243 | case BR_INCREFS: 244 | case BR_ACQUIRE: 245 | case BR_RELEASE: 246 | case BR_DECREFS: 247 | #if TRACE 248 | fprintf(stderr," %08x %08x\n", ptr[0], ptr[1]); 249 | #endif 250 | ptr += 2; 251 | break; 252 | case BR_TRANSACTION: { 253 | // 获取通信的数据 254 | struct binder_txn *txn = (void *) ptr; 255 | if ((end - ptr) * sizeof(uint32_t) < sizeof(struct binder_txn)) { 256 | LOGE("parse: txn too small!\n"); 257 | return -1; 258 | } 259 | binder_dump_txn(txn); 260 | if (func) { 261 | unsigned rdata[256/4]; 262 | // 定义两个binder_io结构体 263 | // 264 | // 用来解析从Binder驱动程序读取回来的进程间通信数据 265 | struct binder_io msg; 266 | // 用来将进程间通信结果数据保存到缓冲区rdata中,以便后面可以将它返回给Binder驱动程序 267 | struct binder_io reply; 268 | int res; 269 | 270 | // 分别使用函数bio_init, bio_init_from_txn来初始化 271 | bio_init(&reply, rdata, sizeof(rdata), 4); 272 | bio_init_from_txn(&msg, txn); 273 | // 调用func来处理保存在binder_io结构体msg中的BR_TRANSACTION返回协议 274 | // 将处理结果保存在binder_io结构体reply中 275 | // 276 | // func函数指针指向的是service manager进程中的函数svcmgr_handler 277 | res = func(bs, txn, &msg, &reply); 278 | // 将进程间的通信结果返回给Binder驱动 279 | binder_send_reply(bs, &reply, txn->data, res); 280 | } 281 | ptr += sizeof(*txn) / sizeof(uint32_t); 282 | break; 283 | } 284 | case BR_REPLY: { 285 | struct binder_txn *txn = (void*) ptr; 286 | if ((end - ptr) * sizeof(uint32_t) < sizeof(struct binder_txn)) { 287 | LOGE("parse: reply too small!\n"); 288 | return -1; 289 | } 290 | binder_dump_txn(txn); 291 | if (bio) { 292 | bio_init_from_txn(bio, txn); 293 | bio = 0; 294 | } else { 295 | /* todo FREE BUFFER */ 296 | } 297 | ptr += (sizeof(*txn) / sizeof(uint32_t)); 298 | r = 0; 299 | break; 300 | } 301 | case BR_DEAD_BINDER: { 302 | struct binder_death *death = (void*) *ptr++; 303 | death->func(bs, death->ptr); 304 | break; 305 | } 306 | case BR_FAILED_REPLY: 307 | r = -1; 308 | break; 309 | case BR_DEAD_REPLY: 310 | r = -1; 311 | break; 312 | default: 313 | LOGE("parse: OOPS %d\n", cmd); 314 | return -1; 315 | } 316 | } 317 | 318 | return r; 319 | } 320 | 321 | void binder_acquire(struct binder_state *bs, void *ptr) 322 | { 323 | uint32_t cmd[2]; 324 | cmd[0] = BC_ACQUIRE; 325 | cmd[1] = (uint32_t) ptr; 326 | binder_write(bs, cmd, sizeof(cmd)); 327 | } 328 | 329 | void binder_release(struct binder_state *bs, void *ptr) 330 | { 331 | uint32_t cmd[2]; 332 | cmd[0] = BC_RELEASE; 333 | cmd[1] = (uint32_t) ptr; 334 | binder_write(bs, cmd, sizeof(cmd)); 335 | } 336 | 337 | void binder_link_to_death(struct binder_state *bs, void *ptr, struct binder_death *death) 338 | { 339 | uint32_t cmd[3]; 340 | cmd[0] = BC_REQUEST_DEATH_NOTIFICATION; 341 | cmd[1] = (uint32_t) ptr; 342 | cmd[2] = (uint32_t) death; 343 | binder_write(bs, cmd, sizeof(cmd)); 344 | } 345 | 346 | 347 | int binder_call(struct binder_state *bs, 348 | struct binder_io *msg, struct binder_io *reply, 349 | void *target, uint32_t code) 350 | { 351 | int res; 352 | struct binder_write_read bwr; 353 | struct { 354 | uint32_t cmd; 355 | struct binder_txn txn; 356 | } writebuf; 357 | unsigned readbuf[32]; 358 | 359 | if (msg->flags & BIO_F_OVERFLOW) { 360 | fprintf(stderr,"binder: txn buffer overflow\n"); 361 | goto fail; 362 | } 363 | 364 | writebuf.cmd = BC_TRANSACTION; 365 | writebuf.txn.target = target; 366 | writebuf.txn.code = code; 367 | writebuf.txn.flags = 0; 368 | writebuf.txn.data_size = msg->data - msg->data0; 369 | writebuf.txn.offs_size = ((char*) msg->offs) - ((char*) msg->offs0); 370 | writebuf.txn.data = msg->data0; 371 | writebuf.txn.offs = msg->offs0; 372 | 373 | bwr.write_size = sizeof(writebuf); 374 | bwr.write_consumed = 0; 375 | bwr.write_buffer = (unsigned) &writebuf; 376 | 377 | hexdump(msg->data0, msg->data - msg->data0); 378 | for (;;) { 379 | bwr.read_size = sizeof(readbuf); 380 | bwr.read_consumed = 0; 381 | bwr.read_buffer = (unsigned) readbuf; 382 | 383 | res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr); 384 | 385 | if (res < 0) { 386 | fprintf(stderr,"binder: ioctl failed (%s)\n", strerror(errno)); 387 | goto fail; 388 | } 389 | 390 | res = binder_parse(bs, reply, readbuf, bwr.read_consumed, 0); 391 | if (res == 0) return 0; 392 | if (res < 0) goto fail; 393 | } 394 | 395 | fail: 396 | memset(reply, 0, sizeof(*reply)); 397 | reply->flags |= BIO_F_IOERROR; 398 | return -1; 399 | } 400 | 401 | // 由于service manager需要在系统运行期间为Service组件和Client组件提供服务 402 | // 它就需要通过一个无限循环来等待和处理service和client的进程间通信请求 403 | // 404 | // bs: binder_open中创建的一个binder_state结构体 405 | // func: 指向servicemanger函数svcmgr_handler, 用来处理service组件和client组件进程间通信请求 406 | void binder_loop(struct binder_state *bs, binder_handler func) 407 | { 408 | int res; 409 | struct binder_write_read bwr; 410 | unsigned readbuf[32]; 411 | 412 | bwr.write_size = 0; 413 | bwr.write_consumed = 0; 414 | bwr.write_buffer = 0; 415 | 416 | // 通过BC_ENTER_LOOPER将自己注册到Binder驱动程序中 417 | readbuf[0] = BC_ENTER_LOOPER; 418 | // 调用binder_write将它发送到Binder驱动程序中 419 | binder_write(bs, readbuf, sizeof(unsigned)); 420 | 421 | for (;;) { 422 | bwr.read_size = sizeof(readbuf); 423 | bwr.read_consumed = 0; 424 | bwr.read_buffer = (unsigned) readbuf; 425 | 426 | res = ioctl(bs->fd, BINDER_WRITE_READ, &bwr); 427 | 428 | if (res < 0) { 429 | LOGE("binder_loop: ioctl failed (%s)\n", strerror(errno)); 430 | break; 431 | } 432 | 433 | // 如果有请求处理,会交给binder_parse来处理 434 | // 否则睡眠等待,直到有进程间通信请求来到为止 435 | res = binder_parse(bs, 0, readbuf, bwr.read_consumed, func); 436 | if (res == 0) { 437 | LOGE("binder_loop: unexpected reply?!\n"); 438 | break; 439 | } 440 | if (res < 0) { 441 | LOGE("binder_loop: io error %d %s\n", res, strerror(errno)); 442 | break; 443 | } 444 | } 445 | } 446 | 447 | // io: 要初始化的binder_io结构体 448 | // txn: 包含了binder_io结构体要解析的数据缓冲区和偏移数组 449 | void bio_init_from_txn(struct binder_io *bio, struct binder_txn *txn) 450 | { 451 | bio->data = bio->data0 = txn->data; 452 | bio->offs = bio->offs0 = txn->offs; 453 | bio->data_avail = txn->data_size; 454 | bio->offs_avail = txn->offs_size / 4; 455 | // 设置flag, 表示内部的数据缓冲区和偏移数组是在内核空间分配的 456 | bio->flags = BIO_F_SHARED; 457 | } 458 | 459 | // bio: 要初始化的binder_io结构体 460 | // data: bio内部所用的缓冲区 461 | // maxdata: 用来描述缓冲区data的大小 462 | // maxoffs: 描述bio内部的偏移数组大小 463 | void bio_init(struct binder_io *bio, void *data, 464 | uint32_t maxdata, uint32_t maxoffs) 465 | { 466 | uint32_t n = maxoffs * sizeof(uint32_t); 467 | 468 | // 判断是否大于缓冲区data的大小 469 | if (n > maxdata) { 470 | bio->flags = BIO_F_OVERFLOW; 471 | bio->data_avail = 0; 472 | bio->offs_avail = 0; 473 | return; 474 | } 475 | 476 | // 将data分成了两部分 477 | // 478 | // 一部分用于binder_io结构体bio的数据缓冲区 479 | // 另一部分用户binder_io结构体的bio偏移数组 480 | bio->data = bio->data0 = data + n; 481 | bio->offs = bio->offs0 = data; 482 | // 设置可用的数据缓冲区和偏移数组的大小 483 | bio->data_avail = maxdata - n; 484 | bio->offs_avail = maxoffs; 485 | bio->flags = 0; 486 | } 487 | 488 | static void *bio_alloc(struct binder_io *bio, uint32_t size) 489 | { 490 | size = (size + 3) & (~3); 491 | if (size > bio->data_avail) { 492 | bio->flags |= BIO_F_OVERFLOW; 493 | return 0; 494 | } else { 495 | void *ptr = bio->data; 496 | bio->data += size; 497 | bio->data_avail -= size; 498 | return ptr; 499 | } 500 | } 501 | 502 | void binder_done(struct binder_state *bs, 503 | struct binder_io *msg, 504 | struct binder_io *reply) 505 | { 506 | if (reply->flags & BIO_F_SHARED) { 507 | uint32_t cmd[2]; 508 | cmd[0] = BC_FREE_BUFFER; 509 | cmd[1] = (uint32_t) reply->data0; 510 | binder_write(bs, cmd, sizeof(cmd)); 511 | reply->flags = 0; 512 | } 513 | } 514 | 515 | static struct binder_object *bio_alloc_obj(struct binder_io *bio) 516 | { 517 | struct binder_object *obj; 518 | 519 | obj = bio_alloc(bio, sizeof(*obj)); 520 | 521 | if (obj && bio->offs_avail) { 522 | bio->offs_avail--; 523 | *bio->offs++ = ((char*) obj) - ((char*) bio->data0); 524 | return obj; 525 | } 526 | 527 | bio->flags |= BIO_F_OVERFLOW; 528 | return 0; 529 | } 530 | 531 | void bio_put_uint32(struct binder_io *bio, uint32_t n) 532 | { 533 | uint32_t *ptr = bio_alloc(bio, sizeof(n)); 534 | if (ptr) 535 | *ptr = n; 536 | } 537 | 538 | void bio_put_obj(struct binder_io *bio, void *ptr) 539 | { 540 | struct binder_object *obj; 541 | 542 | obj = bio_alloc_obj(bio); 543 | if (!obj) 544 | return; 545 | 546 | obj->flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS; 547 | obj->type = BINDER_TYPE_BINDER; 548 | obj->pointer = ptr; 549 | obj->cookie = 0; 550 | } 551 | 552 | void bio_put_ref(struct binder_io *bio, void *ptr) 553 | { 554 | struct binder_object *obj; 555 | 556 | if (ptr) 557 | obj = bio_alloc_obj(bio); 558 | else 559 | obj = bio_alloc(bio, sizeof(*obj)); 560 | 561 | if (!obj) 562 | return; 563 | 564 | obj->flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS; 565 | obj->type = BINDER_TYPE_HANDLE; 566 | obj->pointer = ptr; 567 | obj->cookie = 0; 568 | } 569 | 570 | void bio_put_string16(struct binder_io *bio, const uint16_t *str) 571 | { 572 | uint32_t len; 573 | uint16_t *ptr; 574 | 575 | if (!str) { 576 | bio_put_uint32(bio, 0xffffffff); 577 | return; 578 | } 579 | 580 | len = 0; 581 | while (str[len]) len++; 582 | 583 | if (len >= (MAX_BIO_SIZE / sizeof(uint16_t))) { 584 | bio_put_uint32(bio, 0xffffffff); 585 | return; 586 | } 587 | 588 | bio_put_uint32(bio, len); 589 | len = (len + 1) * sizeof(uint16_t); 590 | ptr = bio_alloc(bio, len); 591 | if (ptr) 592 | memcpy(ptr, str, len); 593 | } 594 | 595 | void bio_put_string16_x(struct binder_io *bio, const char *_str) 596 | { 597 | unsigned char *str = (unsigned char*) _str; 598 | uint32_t len; 599 | uint16_t *ptr; 600 | 601 | if (!str) { 602 | bio_put_uint32(bio, 0xffffffff); 603 | return; 604 | } 605 | 606 | len = strlen(_str); 607 | 608 | if (len >= (MAX_BIO_SIZE / sizeof(uint16_t))) { 609 | bio_put_uint32(bio, 0xffffffff); 610 | return; 611 | } 612 | 613 | bio_put_uint32(bio, len); 614 | ptr = bio_alloc(bio, (len + 1) * sizeof(uint16_t)); 615 | if (!ptr) 616 | return; 617 | 618 | while (*str) 619 | *ptr++ = *str++; 620 | *ptr++ = 0; 621 | } 622 | 623 | static void *bio_get(struct binder_io *bio, uint32_t size) 624 | { 625 | // 将它对齐到4个字节边界 626 | size = (size + 3) & (~3); 627 | 628 | // 剩余的为解析字节数data_avail是否小于要求读取的字节数size 629 | if (bio->data_avail < size){ 630 | bio->data_avail = 0; 631 | // 如果是,那么就是溢出了 632 | bio->flags |= BIO_F_OVERFLOW; 633 | return 0; 634 | } else { 635 | // 如果否,将data当前的位置保存在ptr中 636 | void *ptr = bio->data; 637 | // 往前推进size个字节 638 | bio->data += size; 639 | // 未读取的字节数减少size个字节 640 | bio->data_avail -= size; 641 | return ptr; 642 | } 643 | } 644 | 645 | uint32_t bio_get_uint32(struct binder_io *bio) 646 | { 647 | uint32_t *ptr = bio_get(bio, sizeof(*ptr)); 648 | return ptr ? *ptr : 0; 649 | } 650 | 651 | uint16_t *bio_get_string16(struct binder_io *bio, unsigned *sz) 652 | { 653 | unsigned len; 654 | len = bio_get_uint32(bio); 655 | if (sz) 656 | *sz = len; 657 | return bio_get(bio, (len + 1) * sizeof(uint16_t)); 658 | } 659 | 660 | static struct binder_object *_bio_get_obj(struct binder_io *bio) 661 | { 662 | unsigned n; 663 | unsigned off = bio->data - bio->data0; 664 | 665 | /* TODO: be smarter about this? */ 666 | // 循环检查binder_io结构体的数据缓冲区当前位置是否保存了一个binder_object结构体 667 | for (n = 0; n < bio->offs_avail; n++) { 668 | if (bio->offs[n] == off) 669 | return bio_get(bio, sizeof(struct binder_object)); 670 | } 671 | 672 | bio->data_avail = 0; 673 | bio->flags |= BIO_F_OVERFLOW; 674 | return 0; 675 | } 676 | 677 | void *bio_get_ref(struct binder_io *bio) 678 | { 679 | // 从binder_io结构体取出一个binder_object结构体 680 | struct binder_object *obj; 681 | 682 | obj = _bio_get_obj(bio); 683 | if (!obj) 684 | return 0; 685 | 686 | if (obj->type == BINDER_TYPE_HANDLE) 687 | // 将成员变量pointer返回,pointer保存的是一个由Binder驱动程序创建的引用对象的句柄值 688 | // 这个引用对象引用了即将要注册的Service组件 689 | return obj->pointer; 690 | 691 | return 0; 692 | } 693 | -------------------------------------------------------------------------------- /frameworks/base/cmds/servicemanager/binder.h: -------------------------------------------------------------------------------- 1 | /* Copyright 2008 The Android Open Source Project 2 | */ 3 | 4 | #ifndef _BINDER_H_ 5 | #define _BINDER_H_ 6 | 7 | #include 8 | #include 9 | 10 | struct binder_state; 11 | 12 | // 描述一个Binder对象 13 | // 等同于结构体flat_binder_object 14 | struct binder_object 15 | { 16 | uint32_t type; 17 | uint32_t flags; 18 | void *pointer; 19 | void *cookie; 20 | }; 21 | 22 | // 用来描述进程间通信数据 23 | // 等同于binder_transaction_data 24 | struct binder_txn 25 | { 26 | void *target; 27 | void *cookie; 28 | uint32_t code; 29 | uint32_t flags; 30 | 31 | uint32_t sender_pid; 32 | uint32_t sender_euid; 33 | 34 | uint32_t data_size; 35 | uint32_t offs_size; 36 | void *data; 37 | void *offs; 38 | }; 39 | 40 | // 用来解析进程间通信数据 41 | // 作用类似于Binder库中的Parcel类 42 | struct binder_io 43 | { 44 | // 数据缓冲区 45 | char *data; /* pointer to read/write from */ 46 | // 偏移数组 47 | uint32_t *offs; /* array of offsets */ 48 | // 描述数据缓冲区data0,offs0还有多少内容还没有被解析 49 | uint32_t data_avail; /* bytes available in data buffer */ 50 | uint32_t offs_avail; /* entries available in offsets array */ 51 | 52 | // 在解析进程间通信数据的过程中 53 | // binder_io的成员变量data0, offs0是中指向数据缓冲区和偏移数组的起始地址 54 | // 成员变量data和offs指向当前正在解析的数据缓冲区和偏移数组的状态 55 | char *data0; /* start of data buffer */ 56 | uint32_t *offs0; /* start of offsets buffer */ 57 | // 描述数据缓冲区的属性 58 | uint32_t flags; 59 | // 保留给以后使用 60 | uint32_t unused; 61 | }; 62 | 63 | struct binder_death { 64 | void (*func)(struct binder_state *bs, void *ptr); 65 | void *ptr; 66 | }; 67 | 68 | /* the one magic object */ 69 | #define BINDER_SERVICE_MANAGER ((void*) 0) 70 | 71 | #define SVC_MGR_NAME "android.os.IServiceManager" 72 | 73 | enum { 74 | SVC_MGR_GET_SERVICE = 1, 75 | SVC_MGR_CHECK_SERVICE, 76 | SVC_MGR_ADD_SERVICE, 77 | SVC_MGR_LIST_SERVICES, 78 | }; 79 | 80 | typedef int (*binder_handler)(struct binder_state *bs, 81 | struct binder_txn *txn, 82 | struct binder_io *msg, 83 | struct binder_io *reply); 84 | 85 | struct binder_state *binder_open(unsigned mapsize); 86 | void binder_close(struct binder_state *bs); 87 | 88 | /* initiate a blocking binder call 89 | * - returns zero on success 90 | */ 91 | int binder_call(struct binder_state *bs, 92 | struct binder_io *msg, struct binder_io *reply, 93 | void *target, uint32_t code); 94 | 95 | /* release any state associate with the binder_io 96 | * - call once any necessary data has been extracted from the 97 | * binder_io after binder_call() returns 98 | * - can safely be called even if binder_call() fails 99 | */ 100 | void binder_done(struct binder_state *bs, 101 | struct binder_io *msg, struct binder_io *reply); 102 | 103 | /* manipulate strong references */ 104 | void binder_acquire(struct binder_state *bs, void *ptr); 105 | void binder_release(struct binder_state *bs, void *ptr); 106 | 107 | void binder_link_to_death(struct binder_state *bs, void *ptr, struct binder_death *death); 108 | 109 | void binder_loop(struct binder_state *bs, binder_handler func); 110 | 111 | int binder_become_context_manager(struct binder_state *bs); 112 | 113 | /* allocate a binder_io, providing a stack-allocated working 114 | * buffer, size of the working buffer, and how many object 115 | * offset entries to reserve from the buffer 116 | */ 117 | void bio_init(struct binder_io *bio, void *data, 118 | uint32_t maxdata, uint32_t maxobjects); 119 | 120 | void bio_destroy(struct binder_io *bio); 121 | 122 | void bio_put_obj(struct binder_io *bio, void *ptr); 123 | void bio_put_ref(struct binder_io *bio, void *ptr); 124 | void bio_put_uint32(struct binder_io *bio, uint32_t n); 125 | void bio_put_string16(struct binder_io *bio, const uint16_t *str); 126 | void bio_put_string16_x(struct binder_io *bio, const char *_str); 127 | 128 | uint32_t bio_get_uint32(struct binder_io *bio); 129 | uint16_t *bio_get_string16(struct binder_io *bio, uint32_t *sz); 130 | void *bio_get_obj(struct binder_io *bio); 131 | void *bio_get_ref(struct binder_io *bio); 132 | 133 | #endif 134 | -------------------------------------------------------------------------------- /frameworks/base/cmds/servicemanager/service_manager.c: -------------------------------------------------------------------------------- 1 | /* Copyright 2008 The Android Open Source Project 2 | */ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include 10 | 11 | #include "binder.h" 12 | 13 | #if 0 14 | #define LOGI(x...) fprintf(stderr, "svcmgr: " x) 15 | #define LOGE(x...) fprintf(stderr, "svcmgr: " x) 16 | #else 17 | #define LOG_TAG "ServiceManager" 18 | #include 19 | #endif 20 | 21 | /* TODO: 22 | * These should come from a config file or perhaps be 23 | * based on some namespace rules of some sort (media 24 | * uid can register media.*, etc) 25 | */ 26 | static struct { 27 | unsigned uid; 28 | const char *name; 29 | } allowed[] = { 30 | #ifdef LVMX 31 | // 用户名为uid的进程才能注册名为xxx的service组件 32 | { AID_MEDIA, "com.lifevibes.mx.ipc" }, 33 | #endif 34 | { AID_MEDIA, "media.audio_flinger" }, 35 | { AID_MEDIA, "media.player" }, 36 | { AID_MEDIA, "media.camera" }, 37 | { AID_MEDIA, "media.audio_policy" }, 38 | { AID_DRMIO, "drm.drmIOService" }, 39 | { AID_DRM, "drm.drmManager" }, 40 | { AID_NFC, "nfc" }, 41 | { AID_RADIO, "radio.phone" }, 42 | { AID_RADIO, "radio.sms" }, 43 | { AID_RADIO, "radio.phonesubinfo" }, 44 | { AID_RADIO, "radio.simphonebook" }, 45 | /* TODO: remove after phone services are updated: */ 46 | { AID_RADIO, "phone" }, 47 | { AID_RADIO, "sip" }, 48 | { AID_RADIO, "isms" }, 49 | { AID_RADIO, "iphonesubinfo" }, 50 | { AID_RADIO, "simphonebook" }, 51 | }; 52 | 53 | void *svcmgr_handle; 54 | 55 | const char *str8(uint16_t *x) 56 | { 57 | static char buf[128]; 58 | unsigned max = 127; 59 | char *p = buf; 60 | 61 | if (x) { 62 | while (*x && max--) { 63 | *p++ = *x++; 64 | } 65 | } 66 | *p++ = 0; 67 | return buf; 68 | } 69 | 70 | int str16eq(uint16_t *a, const char *b) 71 | { 72 | while (*a && *b) 73 | if (*a++ != *b++) return 0; 74 | if (*a || *b) 75 | return 0; 76 | return 1; 77 | } 78 | 79 | // 注册service是一种特权,不是所有进程都可以将service组件注册到service manager中 80 | int svc_can_register(unsigned uid, uint16_t *name) 81 | { 82 | unsigned n; 83 | 84 | // 如果发现用户id是系统进程或是AID_SYSTEM进程,将不受限制 85 | if ((uid == 0) || (uid == AID_SYSTEM)) 86 | return 1; 87 | 88 | // allowed是一个全局的数组,定义了可以注册什么名称的service组件 89 | for (n = 0; n < sizeof(allowed) / sizeof(allowed[0]); n++) 90 | if ((uid == allowed[n].uid) && str16eq(name, allowed[n].name)) 91 | return 1; 92 | 93 | return 0; 94 | } 95 | 96 | struct svcinfo 97 | { 98 | // 描述下一个svcinfo结构体 99 | struct svcinfo *next; 100 | // 句柄值,描述注册了的service组件 101 | void *ptr; 102 | // 死亡通知 103 | struct binder_death death; 104 | // 长度 105 | unsigned len; 106 | // 已经注册了的service组件名称 107 | uint16_t name[0]; 108 | }; 109 | 110 | // 每一个被注册了的service组件都使用了svcinfo结构体来描述 111 | // 保存在一个全局队列svclist中 112 | struct svcinfo *svclist = 0; 113 | 114 | struct svcinfo *find_svc(uint16_t *s16, unsigned len) 115 | { 116 | struct svcinfo *si; 117 | 118 | // 循环检查全局队列svclist中已注册service组件列表 119 | for (si = svclist; si; si = si->next) { 120 | if ((len == si->len) && 121 | // 发现已经存在的话会将s16对应的svcinfo结构体返回给调用者 122 | !memcmp(s16, si->name, len * sizeof(uint16_t))) { 123 | return si; 124 | } 125 | } 126 | return 0; 127 | } 128 | 129 | void svcinfo_death(struct binder_state *bs, void *ptr) 130 | { 131 | struct svcinfo *si = ptr; 132 | LOGI("service '%s' died\n", str8(si->name)); 133 | if (si->ptr) { 134 | binder_release(bs, si->ptr); 135 | si->ptr = 0; 136 | } 137 | } 138 | 139 | uint16_t svcmgr_id[] = { 140 | 'a','n','d','r','o','i','d','.','o','s','.', 141 | 'I','S','e','r','v','i','c','e','M','a','n','a','g','e','r' 142 | }; 143 | 144 | 145 | void *do_find_service(struct binder_state *bs, uint16_t *s, unsigned len) 146 | { 147 | struct svcinfo *si; 148 | si = find_svc(s, len); 149 | 150 | // LOGI("check_service('%s') ptr = %p\n", str8(s), si ? si->ptr : 0); 151 | if (si && si->ptr) { 152 | return si->ptr; 153 | } else { 154 | return 0; 155 | } 156 | } 157 | 158 | int do_add_service(struct binder_state *bs, 159 | uint16_t *s, unsigned len, 160 | void *ptr, unsigned uid) 161 | { 162 | struct svcinfo *si; 163 | // LOGI("add_service('%s',%p) uid=%d\n", str8(s), ptr, uid); 164 | 165 | if (!ptr || (len == 0) || (len > 127)) 166 | return -1; 167 | 168 | // s: 要注册的service组件名称 169 | // uid: 注册service组件的进程的用户id 170 | // 171 | // 检查权限 172 | if (!svc_can_register(uid, s)) { 173 | LOGE("add_service('%s',%p) uid=%d - PERMISSION DENIED\n", 174 | str8(s), ptr, uid); 175 | return -1; 176 | } 177 | 178 | // 检查是否已经注册过 179 | si = find_svc(s, len); 180 | if (si) { 181 | if (si->ptr) { 182 | // 已经被使用过 183 | LOGE("add_service('%s',%p) uid=%d - ALREADY REGISTERED\n", 184 | str8(s), ptr, uid); 185 | return -1; 186 | } 187 | // 修改ptr参数 188 | si->ptr = ptr; 189 | } else { 190 | // 如果没有被引用,就会创建一个svcinfo结构体来描述要注册的service组件 191 | si = malloc(sizeof(*si) + (len + 1) * sizeof(uint16_t)); 192 | if (!si) { 193 | LOGE("add_service('%s',%p) uid=%d - OUT OF MEMORY\n", 194 | str8(s), ptr, uid); 195 | return -1; 196 | } 197 | si->ptr = ptr; 198 | si->len = len; 199 | memcpy(si->name, s, (len + 1) * sizeof(uint16_t)); 200 | si->name[len] = '\0'; 201 | si->death.func = svcinfo_death; 202 | si->death.ptr = si; 203 | si->next = svclist; 204 | // 添加到全局的svclist中 205 | svclist = si; 206 | } 207 | 208 | // 因为引用了新注册的service组件,因此需要调用binder_acquire来增加相应的binder引用对象的引用计数值 209 | binder_acquire(bs, ptr); 210 | // 注册一个Binder本地对象的死亡接收通知,以便service manager在该service组件死亡时采取相应的处理措施 211 | binder_link_to_death(bs, ptr, &si->death); 212 | return 0; 213 | } 214 | 215 | int svcmgr_handler(struct binder_state *bs, 216 | struct binder_txn *txn, 217 | struct binder_io *msg, 218 | struct binder_io *reply) 219 | { 220 | struct svcinfo *si; 221 | uint16_t *s; 222 | unsigned len; 223 | void *ptr; 224 | uint32_t strict_policy; 225 | 226 | // LOGI("target=%p code=%d pid=%d uid=%d\n", 227 | // txn->target, txn->code, txn->sender_pid, txn->sender_euid); 228 | 229 | // 检查从驱动传进来的目标Binder本地对象是否指向在service manager中定义的虚拟Binder本地对象svcmgr_handle 230 | if (txn->target != svcmgr_handle) 231 | return -1; 232 | 233 | // Equivalent to Parcel::enforceInterface(), reading the RPC 234 | // header with the strict mode policy mask and the interface name. 235 | // Note that we ignore the strict_policy and don't propagate it 236 | // further (since we do no outbound RPCs anyway). 237 | // 检查Binder进程间通信请求头是否合法 238 | strict_policy = bio_get_uint32(msg); 239 | s = bio_get_string16(msg, &len); 240 | // 验证传递过来的服务接口描述符是否等于svcmgr_id 241 | if ((len != (sizeof(svcmgr_id) / 2)) || 242 | memcmp(svcmgr_id, s, sizeof(svcmgr_id))) { 243 | // 如果不相等,说明这是一个非法的进程间通信请求 244 | fprintf(stderr,"invalid id %s\n", str8(s)); 245 | return -1; 246 | } 247 | 248 | switch(txn->code) { 249 | case SVC_MGR_GET_SERVICE: 250 | case SVC_MGR_CHECK_SERVICE: 251 | s = bio_get_string16(msg, &len); 252 | ptr = do_find_service(bs, s, len); 253 | if (!ptr) 254 | break; 255 | bio_put_ref(reply, ptr); 256 | return 0; 257 | 258 | case SVC_MGR_ADD_SERVICE: 259 | s = bio_get_string16(msg, &len); 260 | // 从binder_io结构体中的数据缓冲区获取一个Binder引用对象的句柄值 261 | // 它引用了要注册的Service组件 262 | ptr = bio_get_ref(msg); 263 | if (do_add_service(bs, s, len, ptr, txn->sender_euid)) 264 | return -1; 265 | break; 266 | 267 | case SVC_MGR_LIST_SERVICES: { 268 | unsigned n = bio_get_uint32(msg); 269 | 270 | si = svclist; 271 | while ((n-- > 0) && si) 272 | si = si->next; 273 | if (si) { 274 | bio_put_string16(reply, si->name); 275 | return 0; 276 | } 277 | return -1; 278 | } 279 | default: 280 | LOGE("unknown code %d\n", txn->code); 281 | return -1; 282 | } 283 | 284 | // 将注册成功的代码0写入到reply中 285 | // 返回给请求注册service组件的进程 286 | bio_put_uint32(reply, 0); 287 | return 0; 288 | } 289 | 290 | // Service Manager 是Binder进程间通信机制的核心组件之一,它扮演着进程间机制上下文管理者的角色 291 | // 负责管理系统中Service组件,并且向Client组件提供获取Service代理对象的服务 292 | // Service Manager运行在一个独立的进程中 293 | // Service组件通常和Client组件也需要通过进程间通信机制来和它交互 294 | // 采用的进程间通信机制正好也是Binder进程间通信机制 295 | // ServiceManager是由init进程负责启动的 296 | // 因此,ServiceManager也是在系统启动时启动的 297 | int main(int argc, char **argv) 298 | { 299 | struct binder_state *bs; 300 | void *svcmgr = BINDER_SERVICE_MANAGER; 301 | 302 | // 调用函数打开设备文件/dev/binder,将它映射到本进程的地址空间 303 | bs = binder_open(128*1024); 304 | 305 | // 将自己注册为Binder进程间通信机制的上下文管理者 306 | if (binder_become_context_manager(bs)) { 307 | LOGE("cannot become context manager (%s)\n", strerror(errno)); 308 | return -1; 309 | } 310 | 311 | svcmgr_handle = svcmgr; 312 | // 循环等待和处理Client进程的通信 313 | binder_loop(bs, svcmgr_handler); 314 | return 0; 315 | } 316 | -------------------------------------------------------------------------------- /frameworks/base/core/java/android/os/Binder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2006 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package android.os; 18 | 19 | import android.util.Config; 20 | import android.util.Log; 21 | 22 | import java.io.FileDescriptor; 23 | import java.io.FileOutputStream; 24 | import java.io.IOException; 25 | import java.io.PrintWriter; 26 | import java.lang.ref.WeakReference; 27 | import java.lang.reflect.Modifier; 28 | 29 | /** 30 | * Base class for a remotable object, the core part of a lightweight 31 | * remote procedure call mechanism defined by {@link IBinder}. 32 | * This class is an implementation of IBinder that provides 33 | * the standard support creating a local implementation of such an object. 34 | * 35 | *

Most developers will not implement this class directly, instead using the 36 | * aidl tool to describe the desired 37 | * interface, having it generate the appropriate Binder subclass. You can, 38 | * however, derive directly from Binder to implement your own custom RPC 39 | * protocol or simply instantiate a raw Binder object directly to use as a 40 | * token that can be shared across processes. 41 | * 42 | * @see IBinder 43 | */ 44 | 45 | // Client进程和Server进程一次通信过程中,涉及了四种类型对象 46 | // Binder实体对象 -> binder_node 47 | // Binder引用对象 -> binder_ref 48 | // Binder本地对象 -> BBinder 49 | // Binder代理对象 -> BpBinder 50 | // 51 | // 1. Client调用BpBinder向驱动发送请求,驱动通过代理对象获取句柄值 52 | // 2. 驱动根据引用对象找到对应的实体对象,并创建一个事务来描述该次通信过程 53 | // 3. 驱动根据实体对象找到运行在Server进程中的Binder本地对象,并且将Client进程传递过来的通信数据进行处理 54 | // 4. Binder本地对象处理完Client进程的请求后,就将通信结果返回给驱动,驱动会找到前面创建的事务 55 | // 5. 驱动根据前面找到的事务相关属性找到发送请求的Client进程,并且通知Client进程将通信结果返回给对应的Binder代理对象处理 56 | public class Binder implements IBinder { 57 | /* 58 | * Set this flag to true to detect anonymous, local or member classes 59 | * that extend this Binder class and that are not static. These kind 60 | * of classes can potentially create leaks. 61 | */ 62 | private static final boolean FIND_POTENTIAL_LEAKS = false; 63 | private static final String TAG = "Binder"; 64 | 65 | private int mObject; 66 | private IInterface mOwner; 67 | private String mDescriptor; 68 | 69 | /** 70 | * Return the ID of the process that sent you the current transaction 71 | * that is being processed. This pid can be used with higher-level 72 | * system services to determine its identity and check permissions. 73 | * If the current thread is not currently executing an incoming transaction, 74 | * then its own pid is returned. 75 | */ 76 | public static final native int getCallingPid(); 77 | 78 | /** 79 | * Return the ID of the user assigned to the process that sent you the 80 | * current transaction that is being processed. This uid can be used with 81 | * higher-level system services to determine its identity and check 82 | * permissions. If the current thread is not currently executing an 83 | * incoming transaction, then its own uid is returned. 84 | */ 85 | public static final native int getCallingUid(); 86 | 87 | /** 88 | * Reset the identity of the incoming IPC on the current thread. This can 89 | * be useful if, while handling an incoming call, you will be calling 90 | * on interfaces of other objects that may be local to your process and 91 | * need to do permission checks on the calls coming into them (so they 92 | * will check the permission of your own local process, and not whatever 93 | * process originally called you). 94 | * 95 | * @return Returns an opaque token that can be used to restore the 96 | * original calling identity by passing it to 97 | * {@link #restoreCallingIdentity(long)}. 98 | * 99 | * @see #getCallingPid() 100 | * @see #getCallingUid() 101 | * @see #restoreCallingIdentity(long) 102 | */ 103 | public static final native long clearCallingIdentity(); 104 | 105 | /** 106 | * Restore the identity of the incoming IPC on the current thread 107 | * back to a previously identity that was returned by {@link 108 | * #clearCallingIdentity}. 109 | * 110 | * @param token The opaque token that was previously returned by 111 | * {@link #clearCallingIdentity}. 112 | * 113 | * @see #clearCallingIdentity 114 | */ 115 | public static final native void restoreCallingIdentity(long token); 116 | 117 | /** 118 | * Sets the native thread-local StrictMode policy mask. 119 | * 120 | *

The StrictMode settings are kept in two places: a Java-level 121 | * threadlocal for libcore/Dalvik, and a native threadlocal (set 122 | * here) for propagation via Binder calls. This is a little 123 | * unfortunate, but necessary to break otherwise more unfortunate 124 | * dependencies either of Dalvik on Android, or Android 125 | * native-only code on Dalvik. 126 | * 127 | * @see StrictMode 128 | * @hide 129 | */ 130 | public static final native void setThreadStrictModePolicy(int policyMask); 131 | 132 | /** 133 | * Gets the current native thread-local StrictMode policy mask. 134 | * 135 | * @see #setThreadStrictModePolicy 136 | * @hide 137 | */ 138 | public static final native int getThreadStrictModePolicy(); 139 | 140 | /** 141 | * Flush any Binder commands pending in the current thread to the kernel 142 | * driver. This can be 143 | * useful to call before performing an operation that may block for a long 144 | * time, to ensure that any pending object references have been released 145 | * in order to prevent the process from holding on to objects longer than 146 | * it needs to. 147 | */ 148 | public static final native void flushPendingCommands(); 149 | 150 | /** 151 | * Add the calling thread to the IPC thread pool. This function does 152 | * not return until the current process is exiting. 153 | */ 154 | public static final native void joinThreadPool(); 155 | 156 | /** 157 | * Default constructor initializes the object. 158 | */ 159 | public Binder() { 160 | init(); 161 | 162 | if (FIND_POTENTIAL_LEAKS) { 163 | final Class klass = getClass(); 164 | if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && 165 | (klass.getModifiers() & Modifier.STATIC) == 0) { 166 | Log.w(TAG, "The following Binder class should be static or leaks might occur: " + 167 | klass.getCanonicalName()); 168 | } 169 | } 170 | } 171 | 172 | /** 173 | * Convenience method for associating a specific interface with the Binder. 174 | * After calling, queryLocalInterface() will be implemented for you 175 | * to return the given owner IInterface when the corresponding 176 | * descriptor is requested. 177 | */ 178 | public void attachInterface(IInterface owner, String descriptor) { 179 | mOwner = owner; 180 | mDescriptor = descriptor; 181 | } 182 | 183 | /** 184 | * Default implementation returns an empty interface name. 185 | */ 186 | public String getInterfaceDescriptor() { 187 | return mDescriptor; 188 | } 189 | 190 | /** 191 | * Default implementation always returns true -- if you got here, 192 | * the object is alive. 193 | */ 194 | public boolean pingBinder() { 195 | return true; 196 | } 197 | 198 | /** 199 | * {@inheritDoc} 200 | * 201 | * Note that if you're calling on a local binder, this always returns true 202 | * because your process is alive if you're calling it. 203 | */ 204 | public boolean isBinderAlive() { 205 | return true; 206 | } 207 | 208 | /** 209 | * Use information supplied to attachInterface() to return the 210 | * associated IInterface if it matches the requested 211 | * descriptor. 212 | */ 213 | public IInterface queryLocalInterface(String descriptor) { 214 | if (mDescriptor.equals(descriptor)) { 215 | return mOwner; 216 | } 217 | return null; 218 | } 219 | 220 | /** 221 | * Default implementation is a stub that returns false. You will want 222 | * to override this to do the appropriate unmarshalling of transactions. 223 | * 224 | *

If you want to call this, call transact(). 225 | */ 226 | protected boolean onTransact(int code, Parcel data, Parcel reply, 227 | int flags) throws RemoteException { 228 | if (code == INTERFACE_TRANSACTION) { 229 | reply.writeString(getInterfaceDescriptor()); 230 | return true; 231 | } else if (code == DUMP_TRANSACTION) { 232 | ParcelFileDescriptor fd = data.readFileDescriptor(); 233 | String[] args = data.readStringArray(); 234 | if (fd != null) { 235 | try { 236 | dump(fd.getFileDescriptor(), args); 237 | } finally { 238 | try { 239 | fd.close(); 240 | } catch (IOException e) { 241 | // swallowed, not propagated back to the caller 242 | } 243 | } 244 | } 245 | // Write the StrictMode header. 246 | if (reply != null) { 247 | reply.writeNoException(); 248 | } else { 249 | StrictMode.clearGatheredViolations(); 250 | } 251 | return true; 252 | } 253 | return false; 254 | } 255 | 256 | /** 257 | * Implemented to call the more convenient version 258 | * {@link #dump(FileDescriptor, PrintWriter, String[])}. 259 | */ 260 | public void dump(FileDescriptor fd, String[] args) { 261 | FileOutputStream fout = new FileOutputStream(fd); 262 | PrintWriter pw = new PrintWriter(fout); 263 | try { 264 | dump(fd, pw, args); 265 | } finally { 266 | pw.flush(); 267 | } 268 | } 269 | 270 | /** 271 | * Print the object's state into the given stream. 272 | * 273 | * @param fd The raw file descriptor that the dump is being sent to. 274 | * @param fout The file to which you should dump your state. This will be 275 | * closed for you after you return. 276 | * @param args additional arguments to the dump request. 277 | */ 278 | protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) { 279 | } 280 | 281 | /** 282 | * Default implementation rewinds the parcels and calls onTransact. On 283 | * the remote side, transact calls into the binder to do the IPC. 284 | */ 285 | public final boolean transact(int code, Parcel data, Parcel reply, 286 | int flags) throws RemoteException { 287 | if (Config.LOGV) Log.v("Binder", "Transact: " + code + " to " + this); 288 | if (data != null) { 289 | data.setDataPosition(0); 290 | } 291 | boolean r = onTransact(code, data, reply, flags); 292 | if (reply != null) { 293 | reply.setDataPosition(0); 294 | } 295 | return r; 296 | } 297 | 298 | /** 299 | * Local implementation is a no-op. 300 | */ 301 | public void linkToDeath(DeathRecipient recipient, int flags) { 302 | } 303 | 304 | /** 305 | * Local implementation is a no-op. 306 | */ 307 | public boolean unlinkToDeath(DeathRecipient recipient, int flags) { 308 | return true; 309 | } 310 | 311 | protected void finalize() throws Throwable { 312 | try { 313 | destroy(); 314 | } finally { 315 | super.finalize(); 316 | } 317 | } 318 | 319 | private native final void init(); 320 | private native final void destroy(); 321 | 322 | // Entry point from android_util_Binder.cpp's onTransact 323 | private boolean execTransact(int code, int dataObj, int replyObj, 324 | int flags) { 325 | Parcel data = Parcel.obtain(dataObj); 326 | Parcel reply = Parcel.obtain(replyObj); 327 | // theoretically, we should call transact, which will call onTransact, 328 | // but all that does is rewind it, and we just got these from an IPC, 329 | // so we'll just call it directly. 330 | boolean res; 331 | try { 332 | res = onTransact(code, data, reply, flags); 333 | } catch (RemoteException e) { 334 | reply.writeException(e); 335 | res = true; 336 | } catch (RuntimeException e) { 337 | reply.writeException(e); 338 | res = true; 339 | } catch (OutOfMemoryError e) { 340 | RuntimeException re = new RuntimeException("Out of memory", e); 341 | reply.writeException(re); 342 | res = true; 343 | } 344 | reply.recycle(); 345 | data.recycle(); 346 | return res; 347 | } 348 | } 349 | 350 | final class BinderProxy implements IBinder { 351 | public native boolean pingBinder(); 352 | public native boolean isBinderAlive(); 353 | 354 | public IInterface queryLocalInterface(String descriptor) { 355 | return null; 356 | } 357 | 358 | public native String getInterfaceDescriptor() throws RemoteException; 359 | public native boolean transact(int code, Parcel data, Parcel reply, 360 | int flags) throws RemoteException; 361 | public native void linkToDeath(DeathRecipient recipient, int flags) 362 | throws RemoteException; 363 | public native boolean unlinkToDeath(DeathRecipient recipient, int flags); 364 | 365 | public void dump(FileDescriptor fd, String[] args) throws RemoteException { 366 | Parcel data = Parcel.obtain(); 367 | Parcel reply = Parcel.obtain(); 368 | data.writeFileDescriptor(fd); 369 | data.writeStringArray(args); 370 | try { 371 | transact(DUMP_TRANSACTION, data, reply, 0); 372 | reply.readException(); 373 | } finally { 374 | data.recycle(); 375 | reply.recycle(); 376 | } 377 | } 378 | 379 | BinderProxy() { 380 | mSelf = new WeakReference(this); 381 | } 382 | 383 | @Override 384 | protected void finalize() throws Throwable { 385 | try { 386 | destroy(); 387 | } finally { 388 | super.finalize(); 389 | } 390 | } 391 | 392 | private native final void destroy(); 393 | 394 | private static final void sendDeathNotice(DeathRecipient recipient) { 395 | if (Config.LOGV) Log.v("JavaBinder", "sendDeathNotice to " + recipient); 396 | try { 397 | recipient.binderDied(); 398 | } 399 | catch (RuntimeException exc) { 400 | Log.w("BinderNative", "Uncaught exception from death notification", 401 | exc); 402 | } 403 | } 404 | 405 | final private WeakReference mSelf; 406 | private int mObject; 407 | } 408 | -------------------------------------------------------------------------------- /frameworks/base/core/java/android/os/ServiceManager.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2007 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package android.os; 18 | 19 | import com.android.internal.os.BinderInternal; 20 | 21 | import android.util.Log; 22 | 23 | import java.util.HashMap; 24 | import java.util.Map; 25 | 26 | /** @hide */ 27 | public final class ServiceManager { 28 | private static final String TAG = "ServiceManager"; 29 | 30 | private static IServiceManager sServiceManager; 31 | private static HashMap sCache = new HashMap(); 32 | 33 | private static IServiceManager getIServiceManager() { 34 | if (sServiceManager != null) { 35 | return sServiceManager; 36 | } 37 | 38 | // Find the service manager 39 | sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject()); 40 | return sServiceManager; 41 | } 42 | 43 | /** 44 | * Returns a reference to a service with the given name. 45 | * 46 | * @param name the name of the service to get 47 | * @return a reference to the service, or null if the service doesn't exist 48 | */ 49 | public static IBinder getService(String name) { 50 | try { 51 | IBinder service = sCache.get(name); 52 | if (service != null) { 53 | return service; 54 | } else { 55 | return getIServiceManager().getService(name); 56 | } 57 | } catch (RemoteException e) { 58 | Log.e(TAG, "error in getService", e); 59 | } 60 | return null; 61 | } 62 | 63 | /** 64 | * Place a new @a service called @a name into the service 65 | * manager. 66 | * 67 | * @param name the name of the new service 68 | * @param service the service object 69 | */ 70 | public static void addService(String name, IBinder service) { 71 | try { 72 | getIServiceManager().addService(name, service); 73 | } catch (RemoteException e) { 74 | Log.e(TAG, "error in addService", e); 75 | } 76 | } 77 | 78 | /** 79 | * Retrieve an existing service called @a name from the 80 | * service manager. Non-blocking. 81 | */ 82 | public static IBinder checkService(String name) { 83 | try { 84 | IBinder service = sCache.get(name); 85 | if (service != null) { 86 | return service; 87 | } else { 88 | return getIServiceManager().checkService(name); 89 | } 90 | } catch (RemoteException e) { 91 | Log.e(TAG, "error in checkService", e); 92 | return null; 93 | } 94 | } 95 | 96 | /** 97 | * Return a list of all currently running services. 98 | */ 99 | public static String[] listServices() throws RemoteException { 100 | try { 101 | return getIServiceManager().listServices(); 102 | } catch (RemoteException e) { 103 | Log.e(TAG, "error in listServices", e); 104 | return null; 105 | } 106 | } 107 | 108 | /** 109 | * This is only intended to be called when the process is first being brought 110 | * up and bound by the activity manager. There is only one thread in the process 111 | * at that time, so no locking is done. 112 | * 113 | * @param cache the cache of service references 114 | * @hide 115 | */ 116 | public static void initServiceCache(Map cache) { 117 | if (sCache.size() != 0 && Process.supportsProcesses()) { 118 | throw new IllegalStateException("setServiceCache may only be called once"); 119 | } 120 | sCache.putAll(cache); 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /frameworks/base/core/java/android/os/ServiceManagerNative.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2006 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package android.os; 18 | 19 | 20 | /** 21 | * Native implementation of the service manager. Most clients will only 22 | * care about getDefault() and possibly asInterface(). 23 | * @hide 24 | */ 25 | public abstract class ServiceManagerNative extends Binder implements IServiceManager 26 | { 27 | /** 28 | * Cast a Binder object into a service manager interface, generating 29 | * a proxy if needed. 30 | */ 31 | // obj: 指向一个Java服务代理对象,即BinderProxy对象 32 | static public IServiceManager asInterface(IBinder obj) 33 | { 34 | if (obj == null) { 35 | return null; 36 | } 37 | IServiceManager in = 38 | (IServiceManager)obj.queryLocalInterface(descriptor); 39 | if (in != null) { 40 | return in; 41 | } 42 | 43 | // 创建一个ServiceManagerProxy对象 44 | return new ServiceManagerProxy(obj); 45 | } 46 | 47 | public ServiceManagerNative() 48 | { 49 | attachInterface(this, descriptor); 50 | } 51 | 52 | public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 53 | { 54 | try { 55 | switch (code) { 56 | case IServiceManager.GET_SERVICE_TRANSACTION: { 57 | data.enforceInterface(IServiceManager.descriptor); 58 | String name = data.readString(); 59 | IBinder service = getService(name); 60 | reply.writeStrongBinder(service); 61 | return true; 62 | } 63 | 64 | case IServiceManager.CHECK_SERVICE_TRANSACTION: { 65 | data.enforceInterface(IServiceManager.descriptor); 66 | String name = data.readString(); 67 | IBinder service = checkService(name); 68 | reply.writeStrongBinder(service); 69 | return true; 70 | } 71 | 72 | case IServiceManager.ADD_SERVICE_TRANSACTION: { 73 | data.enforceInterface(IServiceManager.descriptor); 74 | String name = data.readString(); 75 | IBinder service = data.readStrongBinder(); 76 | addService(name, service); 77 | return true; 78 | } 79 | 80 | case IServiceManager.LIST_SERVICES_TRANSACTION: { 81 | data.enforceInterface(IServiceManager.descriptor); 82 | String[] list = listServices(); 83 | reply.writeStringArray(list); 84 | return true; 85 | } 86 | 87 | case IServiceManager.SET_PERMISSION_CONTROLLER_TRANSACTION: { 88 | data.enforceInterface(IServiceManager.descriptor); 89 | IPermissionController controller 90 | = IPermissionController.Stub.asInterface( 91 | data.readStrongBinder()); 92 | setPermissionController(controller); 93 | return true; 94 | } 95 | } 96 | } catch (RemoteException e) { 97 | } 98 | 99 | return false; 100 | } 101 | 102 | public IBinder asBinder() 103 | { 104 | return this; 105 | } 106 | } 107 | 108 | class ServiceManagerProxy implements IServiceManager { 109 | public ServiceManagerProxy(IBinder remote) { 110 | mRemote = remote; 111 | } 112 | 113 | public IBinder asBinder() { 114 | return mRemote; 115 | } 116 | 117 | public IBinder getService(String name) throws RemoteException { 118 | Parcel data = Parcel.obtain(); 119 | Parcel reply = Parcel.obtain(); 120 | data.writeInterfaceToken(IServiceManager.descriptor); 121 | data.writeString(name); 122 | mRemote.transact(GET_SERVICE_TRANSACTION, data, reply, 0); 123 | IBinder binder = reply.readStrongBinder(); 124 | reply.recycle(); 125 | data.recycle(); 126 | return binder; 127 | } 128 | 129 | public IBinder checkService(String name) throws RemoteException { 130 | Parcel data = Parcel.obtain(); 131 | Parcel reply = Parcel.obtain(); 132 | data.writeInterfaceToken(IServiceManager.descriptor); 133 | data.writeString(name); 134 | mRemote.transact(CHECK_SERVICE_TRANSACTION, data, reply, 0); 135 | IBinder binder = reply.readStrongBinder(); 136 | reply.recycle(); 137 | data.recycle(); 138 | return binder; 139 | } 140 | 141 | public void addService(String name, IBinder service) 142 | throws RemoteException { 143 | Parcel data = Parcel.obtain(); 144 | Parcel reply = Parcel.obtain(); 145 | data.writeInterfaceToken(IServiceManager.descriptor); 146 | data.writeString(name); 147 | data.writeStrongBinder(service); 148 | mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0); 149 | reply.recycle(); 150 | data.recycle(); 151 | } 152 | 153 | public String[] listServices() throws RemoteException { 154 | Parcel data = Parcel.obtain(); 155 | Parcel reply = Parcel.obtain(); 156 | data.writeInterfaceToken(IServiceManager.descriptor); 157 | mRemote.transact(LIST_SERVICES_TRANSACTION, data, reply, 0); 158 | String[] list = reply.readStringArray(); 159 | reply.recycle(); 160 | data.recycle(); 161 | return list; 162 | } 163 | 164 | public void setPermissionController(IPermissionController controller) 165 | throws RemoteException { 166 | Parcel data = Parcel.obtain(); 167 | Parcel reply = Parcel.obtain(); 168 | data.writeInterfaceToken(IServiceManager.descriptor); 169 | data.writeStrongBinder(controller.asBinder()); 170 | mRemote.transact(SET_PERMISSION_CONTROLLER_TRANSACTION, data, reply, 0); 171 | reply.recycle(); 172 | data.recycle(); 173 | } 174 | 175 | private IBinder mRemote; 176 | } 177 | -------------------------------------------------------------------------------- /frameworks/base/core/java/com/android/internal/os/BinderInternal.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.android.internal.os; 18 | 19 | import android.os.Binder; 20 | import android.os.IBinder; 21 | import android.os.SystemClock; 22 | import android.util.Config; 23 | import android.util.EventLog; 24 | import android.util.Log; 25 | 26 | import java.io.FileDescriptor; 27 | import java.io.FileOutputStream; 28 | import java.io.IOException; 29 | import java.io.PrintWriter; 30 | import java.lang.ref.WeakReference; 31 | import java.lang.reflect.Modifier; 32 | 33 | /** 34 | * Private and debugging Binder APIs. 35 | * 36 | * @see IBinder 37 | */ 38 | public class BinderInternal { 39 | static WeakReference mGcWatcher 40 | = new WeakReference(new GcWatcher()); 41 | static long mLastGcTime; 42 | 43 | static final class GcWatcher { 44 | @Override 45 | protected void finalize() throws Throwable { 46 | handleGc(); 47 | mLastGcTime = SystemClock.uptimeMillis(); 48 | mGcWatcher = new WeakReference(new GcWatcher()); 49 | } 50 | } 51 | 52 | /** 53 | * Add the calling thread to the IPC thread pool. This function does 54 | * not return until the current process is exiting. 55 | */ 56 | public static final native void joinThreadPool(); 57 | 58 | /** 59 | * Return the system time (as reported by {@link SystemClock#uptimeMillis 60 | * SystemClock.uptimeMillis()}) that the last garbage collection occurred 61 | * in this process. This is not for general application use, and the 62 | * meaning of "when a garbage collection occurred" will change as the 63 | * garbage collector evolves. 64 | * 65 | * @return Returns the time as per {@link SystemClock#uptimeMillis 66 | * SystemClock.uptimeMillis()} of the last garbage collection. 67 | */ 68 | public static long getLastGcTime() { 69 | return mLastGcTime; 70 | } 71 | 72 | /** 73 | * Return the global "context object" of the system. This is usually 74 | * an implementation of IServiceManager, which you can use to find 75 | * other services. 76 | */ 77 | public static final native IBinder getContextObject(); 78 | 79 | /** 80 | * Special for system process to not allow incoming calls to run at 81 | * background scheduling priority. 82 | * @hide 83 | */ 84 | public static final native void disableBackgroundScheduling(boolean disable); 85 | 86 | static native final void handleGc(); 87 | 88 | public static void forceGc(String reason) { 89 | EventLog.writeEvent(2741, reason); 90 | Runtime.getRuntime().gc(); 91 | } 92 | 93 | static void forceBinderGc() { 94 | forceGc("Binder"); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /frameworks/base/include/binder/Binder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef ANDROID_BINDER_H 18 | #define ANDROID_BINDER_H 19 | 20 | #include 21 | 22 | // --------------------------------------------------------------------------- 23 | namespace android { 24 | 25 | // 在用户空间中创建 26 | // 运行在Server进程 27 | // 会被运行在Server进程中的其它对象引用,也会被驱动中的Binder实体对象引用 28 | // Binder实体对象运行在内核空间,不能铜鼓只能指针来引用运行在用户空间的Binder本地对象 29 | class BBinder : public IBinder 30 | { 31 | public: 32 | BBinder(); 33 | 34 | virtual const String16& getInterfaceDescriptor() const; 35 | virtual bool isBinderAlive() const; 36 | virtual status_t pingBinder(); 37 | virtual status_t dump(int fd, const Vector& args); 38 | 39 | // 当一个Binder代理对象通过Binder驱动程序向一个Binder本地对象发出一个进程间通信请求时 40 | // Binder驱动会调用Binder本地对象的成员函数transact来处理该请求 41 | virtual status_t transact( uint32_t code, 42 | const Parcel& data, 43 | Parcel* reply, 44 | uint32_t flags = 0); 45 | 46 | virtual status_t linkToDeath(const sp& recipient, 47 | void* cookie = NULL, 48 | uint32_t flags = 0); 49 | 50 | virtual status_t unlinkToDeath( const wp& recipient, 51 | void* cookie = NULL, 52 | uint32_t flags = 0, 53 | wp* outRecipient = NULL); 54 | 55 | virtual void attachObject( const void* objectID, 56 | void* object, 57 | void* cleanupCookie, 58 | object_cleanup_func func); 59 | virtual void* findObject(const void* objectID) const; 60 | virtual void detachObject(const void* objectID); 61 | 62 | virtual BBinder* localBinder(); 63 | 64 | protected: 65 | virtual ~BBinder(); 66 | 67 | // 负责分发与业务相关的进程间通信请求 68 | virtual status_t onTransact( uint32_t code, 69 | const Parcel& data, 70 | Parcel* reply, 71 | uint32_t flags = 0); 72 | 73 | private: 74 | BBinder(const BBinder& o); 75 | BBinder& operator=(const BBinder& o); 76 | 77 | class Extras; 78 | 79 | Extras* mExtras; 80 | void* mReserved0; 81 | }; 82 | 83 | // --------------------------------------------------------------------------- 84 | 85 | // RefBase: 可以通过强指针,弱指针来维护它们的生命周期 86 | // 提供了抽象的进程间通信接口 87 | class BpRefBase : public virtual RefBase 88 | { 89 | protected: 90 | BpRefBase(const sp& o); 91 | virtual ~BpRefBase(); 92 | virtual void onFirstRef(); 93 | virtual void onLastStrongRef(const void* id); 94 | virtual bool onIncStrongAttempted(uint32_t flags, const void* id); 95 | 96 | inline IBinder* remote() { return mRemote; } 97 | inline IBinder* remote() const { return mRemote; } 98 | 99 | private: 100 | BpRefBase(const BpRefBase& o); 101 | BpRefBase& operator=(const BpRefBase& o); 102 | 103 | IBinder* const mRemote; 104 | RefBase::weakref_type* mRefs; 105 | volatile int32_t mState; 106 | }; 107 | 108 | }; // namespace android 109 | 110 | // --------------------------------------------------------------------------- 111 | 112 | #endif // ANDROID_BINDER_H 113 | -------------------------------------------------------------------------------- /frameworks/base/include/binder/BpBinder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2005 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef ANDROID_BPBINDER_H 18 | #define ANDROID_BPBINDER_H 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | // --------------------------------------------------------------------------- 25 | namespace android { 26 | 27 | // BBinder和BpBinder类都是通过IPCThreadState类来和Binder驱动进行交互的 28 | class BpBinder : public IBinder 29 | { 30 | public: 31 | BpBinder(int32_t handle); 32 | 33 | // 获取句柄值 34 | inline int32_t handle() const { return mHandle; } 35 | 36 | virtual const String16& getInterfaceDescriptor() const; 37 | virtual bool isBinderAlive() const; 38 | virtual status_t pingBinder(); 39 | virtual status_t dump(int fd, const Vector& args); 40 | 41 | // 向运行在Server进程中的Service组件发送进程间通信请求 42 | // 通过Binder驱动程序间接实现的 43 | // 将把成员变量mHandle以及进程间通信数据发送给Binder驱动程序 44 | // 这样驱动就能够更具句柄值来找到对应的Binder引用对象,继而找到实体对象 45 | // 最后将通信数据发送给对应的Service组件 46 | virtual status_t transact( uint32_t code, 47 | const Parcel& data, 48 | Parcel* reply, 49 | uint32_t flags = 0); 50 | 51 | virtual status_t linkToDeath(const sp& recipient, 52 | void* cookie = NULL, 53 | uint32_t flags = 0); 54 | virtual status_t unlinkToDeath( const wp& recipient, 55 | void* cookie = NULL, 56 | uint32_t flags = 0, 57 | wp* outRecipient = NULL); 58 | 59 | virtual void attachObject( const void* objectID, 60 | void* object, 61 | void* cleanupCookie, 62 | object_cleanup_func func); 63 | virtual void* findObject(const void* objectID) const; 64 | virtual void detachObject(const void* objectID); 65 | 66 | virtual BpBinder* remoteBinder(); 67 | 68 | status_t setConstantData(const void* data, size_t size); 69 | void sendObituary(); 70 | 71 | class ObjectManager 72 | { 73 | public: 74 | ObjectManager(); 75 | ~ObjectManager(); 76 | 77 | void attach( const void* objectID, 78 | void* object, 79 | void* cleanupCookie, 80 | IBinder::object_cleanup_func func); 81 | void* find(const void* objectID) const; 82 | void detach(const void* objectID); 83 | 84 | void kill(); 85 | 86 | private: 87 | ObjectManager(const ObjectManager&); 88 | ObjectManager& operator=(const ObjectManager&); 89 | 90 | struct entry_t 91 | { 92 | // 指向一个外部对象的弱引用对象 93 | void* object; 94 | // 函数指针,用来清理成员变量object所指向的外部对象 95 | void* cleanupCookie; 96 | // 清理函数的一个调用参数 97 | IBinder::object_cleanup_func func; 98 | }; 99 | 100 | KeyedVector mObjects; 101 | }; 102 | 103 | protected: 104 | virtual ~BpBinder(); 105 | virtual void onFirstRef(); 106 | virtual void onLastStrongRef(const void* id); 107 | virtual bool onIncStrongAttempted(uint32_t flags, const void* id); 108 | 109 | private: 110 | // Client组件的一个句柄值 111 | // 每一个Client组件在Binder驱动都对应有一个Binder引用对象 112 | // 每一个Binder引用对象对应这一个句柄值 113 | // Client组件就是通过这个句柄值来和Binder驱动中的Binder引用对象建立对应的关系 114 | const int32_t mHandle; 115 | 116 | struct Obituary { 117 | wp recipient; 118 | void* cookie; 119 | uint32_t flags; 120 | }; 121 | 122 | void reportOneDeath(const Obituary& obit); 123 | bool isDescriptorCached() const; 124 | 125 | mutable Mutex mLock; 126 | volatile int32_t mAlive; 127 | volatile int32_t mObitsSent; 128 | Vector* mObituaries; 129 | // 用来管理与该Binder代理对象关联的外部对象 130 | ObjectManager mObjects; 131 | Parcel* mConstantData; 132 | mutable String16 mDescriptorCache; 133 | }; 134 | 135 | }; // namespace android 136 | 137 | // --------------------------------------------------------------------------- 138 | 139 | #endif // ANDROID_BPBINDER_H 140 | -------------------------------------------------------------------------------- /frameworks/base/include/binder/IBinder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef ANDROID_IBINDER_H 18 | #define ANDROID_IBINDER_H 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | 26 | #define B_PACK_CHARS(c1, c2, c3, c4) \ 27 | ((((c1)<<24)) | (((c2)<<16)) | (((c3)<<8)) | (c4)) 28 | 29 | // --------------------------------------------------------------------------- 30 | namespace android { 31 | 32 | class BBinder; 33 | class BpBinder; 34 | class IInterface; 35 | class Parcel; 36 | 37 | /** 38 | * Base class and low-level protocol for a remotable object. 39 | * You can derive from this class to create an object for which other 40 | * processes can hold references to it. Communication between processes 41 | * (method calls, property get and set) is down through a low-level 42 | * protocol implemented on top of the transact() API. 43 | */ 44 | class IBinder : public virtual RefBase 45 | { 46 | public: 47 | enum { 48 | FIRST_CALL_TRANSACTION = 0x00000001, 49 | LAST_CALL_TRANSACTION = 0x00ffffff, 50 | 51 | PING_TRANSACTION = B_PACK_CHARS('_','P','N','G'), 52 | DUMP_TRANSACTION = B_PACK_CHARS('_','D','M','P'), 53 | INTERFACE_TRANSACTION = B_PACK_CHARS('_', 'N', 'T', 'F'), 54 | 55 | // Corresponds to TF_ONE_WAY -- an asynchronous call. 56 | FLAG_ONEWAY = 0x00000001 57 | }; 58 | 59 | IBinder(); 60 | 61 | /** 62 | * Check if this IBinder implements the interface named by 63 | * @a descriptor. If it does, the base pointer to it is returned, 64 | * which you can safely static_cast<> to the concrete C++ interface. 65 | */ 66 | virtual sp queryLocalInterface(const String16& descriptor); 67 | 68 | /** 69 | * Return the canonical name of the interface provided by this IBinder 70 | * object. 71 | */ 72 | virtual const String16& getInterfaceDescriptor() const = 0; 73 | 74 | virtual bool isBinderAlive() const = 0; 75 | virtual status_t pingBinder() = 0; 76 | virtual status_t dump(int fd, const Vector& args) = 0; 77 | 78 | virtual status_t transact( uint32_t code, 79 | const Parcel& data, 80 | Parcel* reply, 81 | uint32_t flags = 0) = 0; 82 | 83 | /** 84 | * This method allows you to add data that is transported through 85 | * IPC along with your IBinder pointer. When implementing a Binder 86 | * object, override it to write your desired data in to @a outData. 87 | * You can then call getConstantData() on your IBinder to retrieve 88 | * that data, from any process. You MUST return the number of bytes 89 | * written in to the parcel (including padding). 90 | */ 91 | class DeathRecipient : public virtual RefBase 92 | { 93 | public: 94 | virtual void binderDied(const wp& who) = 0; 95 | }; 96 | 97 | /** 98 | * Register the @a recipient for a notification if this binder 99 | * goes away. If this binder object unexpectedly goes away 100 | * (typically because its hosting process has been killed), 101 | * then DeathRecipient::binderDied() will be called with a referene 102 | * to this. 103 | * 104 | * The @a cookie is optional -- if non-NULL, it should be a 105 | * memory address that you own (that is, you know it is unique). 106 | * 107 | * @note You will only receive death notifications for remote binders, 108 | * as local binders by definition can't die without you dying as well. 109 | * Trying to use this function on a local binder will result in an 110 | * INVALID_OPERATION code being returned and nothing happening. 111 | * 112 | * @note This link always holds a weak reference to its recipient. 113 | * 114 | * @note You will only receive a weak reference to the dead 115 | * binder. You should not try to promote this to a strong reference. 116 | * (Nor should you need to, as there is nothing useful you can 117 | * directly do with it now that it has passed on.) 118 | */ 119 | virtual status_t linkToDeath(const sp& recipient, 120 | void* cookie = NULL, 121 | uint32_t flags = 0) = 0; 122 | 123 | /** 124 | * Remove a previously registered death notification. 125 | * The @a recipient will no longer be called if this object 126 | * dies. The @a cookie is optional. If non-NULL, you can 127 | * supply a NULL @a recipient, and the recipient previously 128 | * added with that cookie will be unlinked. 129 | */ 130 | virtual status_t unlinkToDeath( const wp& recipient, 131 | void* cookie = NULL, 132 | uint32_t flags = 0, 133 | wp* outRecipient = NULL) = 0; 134 | 135 | virtual bool checkSubclass(const void* subclassID) const; 136 | 137 | typedef void (*object_cleanup_func)(const void* id, void* obj, void* cleanupCookie); 138 | 139 | virtual void attachObject( const void* objectID, 140 | void* object, 141 | void* cleanupCookie, 142 | object_cleanup_func func) = 0; 143 | virtual void* findObject(const void* objectID) const = 0; 144 | virtual void detachObject(const void* objectID) = 0; 145 | 146 | virtual BBinder* localBinder(); 147 | virtual BpBinder* remoteBinder(); 148 | 149 | protected: 150 | virtual ~IBinder(); 151 | 152 | private: 153 | }; 154 | 155 | }; // namespace android 156 | 157 | // --------------------------------------------------------------------------- 158 | 159 | #endif // ANDROID_IBINDER_H 160 | -------------------------------------------------------------------------------- /frameworks/base/include/binder/IInterface.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2005 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // 18 | #ifndef ANDROID_IINTERFACE_H 19 | #define ANDROID_IINTERFACE_H 20 | 21 | #include 22 | 23 | namespace android { 24 | 25 | // ---------------------------------------------------------------------- 26 | 27 | class IInterface : public virtual RefBase 28 | { 29 | public: 30 | IInterface(); 31 | sp asBinder(); 32 | sp asBinder() const; 33 | 34 | protected: 35 | virtual ~IInterface(); 36 | virtual IBinder* onAsBinder() = 0; 37 | }; 38 | 39 | // ---------------------------------------------------------------------- 40 | 41 | // 句柄值为0的Binder代理对象封装为一个Service Manager代理对象 42 | template 43 | inline sp interface_cast(const sp& obj) 44 | { 45 | return INTERFACE::asInterface(obj); 46 | } 47 | 48 | // ---------------------------------------------------------------------- 49 | 50 | // Binder本地对象,对应着Binder驱动中的Binder实体对象 51 | // INTERFACE: 模板参数,是一个由进程自定义的Service组件接口 52 | // BBinder: Binder本地类 53 | template 54 | class BnInterface : public INTERFACE, public BBinder 55 | { 56 | public: 57 | virtual sp queryLocalInterface(const String16& _descriptor); 58 | virtual const String16& getInterfaceDescriptor() const; 59 | 60 | protected: 61 | virtual IBinder* onAsBinder(); 62 | }; 63 | 64 | // ---------------------------------------------------------------------- 65 | 66 | // Binder代理对象,对应这Binder驱动中的Binder引用对象 67 | // BpRefBase: Binder代理类 68 | template 69 | class BpInterface : public INTERFACE, public BpRefBase 70 | { 71 | public: 72 | BpInterface(const sp& remote); 73 | 74 | protected: 75 | virtual IBinder* onAsBinder(); 76 | }; 77 | 78 | // ---------------------------------------------------------------------- 79 | 80 | // 定义一个静态成员变量descriptor,通过getInterfaceDescriptor来过去 81 | // 定义一个asInterface,用来将一个IBinder对象转换为IFregService接口 82 | #define DECLARE_META_INTERFACE(INTERFACE) \ 83 | static const android::String16 descriptor; \ 84 | static android::sp asInterface( \ 85 | const android::sp& obj); \ 86 | virtual const android::String16& getInterfaceDescriptor() const; \ 87 | I##INTERFACE(); \ 88 | virtual ~I##INTERFACE(); \ 89 | 90 | // 将descriptor设置为shy.luo.IFregService 91 | // 实现了IFregService的析造函数,析构函数 92 | // asInterface用来将一个IBinder对象转换为一个IFregService接口 93 | #define IMPLEMENT_META_INTERFACE(INTERFACE, NAME) \ 94 | const android::String16 I##INTERFACE::descriptor(NAME); \ 95 | const android::String16& \ 96 | I##INTERFACE::getInterfaceDescriptor() const { \ 97 | return I##INTERFACE::descriptor; \ 98 | } \ 99 | // 参数obj指向一个类型为BnFregService的Binder本地对象 100 | // 或者一个类型为BpBinder的Binder代理对象 101 | // 否则就返回NULL 102 | android::sp I##INTERFACE::asInterface( \ 103 | const android::sp& obj) \ 104 | { \ 105 | android::sp intr; \ 106 | if (obj != NULL) { \ 107 | // 如果参数是一个BnFregService对象,那么就会调用queryLocalInterface返回一个IFregService接口 108 | // 如果obj指向的是一个BpBinder代理对象,那么会返回NULL,接着封装成一个BpFregService对象 109 | intr = static_cast( \ 110 | obj->queryLocalInterface( \ 111 | I##INTERFACE::descriptor).get()); \ 112 | if (intr == NULL) { \ 113 | intr = new Bp##INTERFACE(obj); \ 114 | } \ 115 | } \ 116 | return intr; \ 117 | } \ 118 | I##INTERFACE::I##INTERFACE() { } \ 119 | I##INTERFACE::~I##INTERFACE() { } \ 120 | 121 | 122 | #define CHECK_INTERFACE(interface, data, reply) \ 123 | if (!data.checkInterface(this)) { return PERMISSION_DENIED; } \ 124 | 125 | 126 | // ---------------------------------------------------------------------- 127 | // No user-serviceable parts after this... 128 | 129 | template 130 | inline sp BnInterface::queryLocalInterface( 131 | const String16& _descriptor) 132 | { 133 | if (_descriptor == INTERFACE::descriptor) return this; 134 | return NULL; 135 | } 136 | 137 | template 138 | inline const String16& BnInterface::getInterfaceDescriptor() const 139 | { 140 | return INTERFACE::getInterfaceDescriptor(); 141 | } 142 | 143 | template 144 | IBinder* BnInterface::onAsBinder() 145 | { 146 | return this; 147 | } 148 | 149 | template 150 | inline BpInterface::BpInterface(const sp& remote) 151 | : BpRefBase(remote) 152 | { 153 | } 154 | 155 | template 156 | inline IBinder* BpInterface::onAsBinder() 157 | { 158 | return remote(); 159 | } 160 | 161 | // ---------------------------------------------------------------------- 162 | 163 | }; // namespace android 164 | 165 | #endif // ANDROID_IINTERFACE_H 166 | -------------------------------------------------------------------------------- /frameworks/base/include/binder/IPCThreadState.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2005 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef ANDROID_IPC_THREAD_STATE_H 18 | #define ANDROID_IPC_THREAD_STATE_H 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #ifdef HAVE_WIN32_PROC 26 | typedef int uid_t; 27 | #endif 28 | 29 | // --------------------------------------------------------------------------- 30 | namespace android { 31 | 32 | // 每一个使用了Binder进程间通信机制的进程都有一个Binder线程池,用来处理进程间通信请求 33 | // 对于每一个Binder线程来说,它的内部都有一个IPCThread对象 34 | // 可以通过IPCThreadState类的静态成员函数self来获取,并且调用它的成员函数transact来和 35 | // Binder驱动交互 36 | // 在IPCThreadState类的成员函数transact内部,与Binder驱动的交互又是通过调用talkWithDriver 37 | // 来实现 38 | // 一方面负责向Binder驱动发送进程间通信请求,另一方面又负责接受来自Binder驱动程序的进程间通信请求 39 | class IPCThreadState 40 | { 41 | public: 42 | static IPCThreadState* self(); 43 | 44 | sp process(); 45 | 46 | status_t clearLastError(); 47 | 48 | int getCallingPid(); 49 | int getCallingUid(); 50 | 51 | void setStrictModePolicy(int32_t policy); 52 | int32_t getStrictModePolicy() const; 53 | 54 | void setLastTransactionBinderFlags(int32_t flags); 55 | int32_t getLastTransactionBinderFlags() const; 56 | 57 | int64_t clearCallingIdentity(); 58 | void restoreCallingIdentity(int64_t token); 59 | 60 | void flushCommands(); 61 | 62 | void joinThreadPool(bool isMain = true); 63 | 64 | // Stop the local process. 65 | void stopProcess(bool immediate = true); 66 | 67 | status_t transact(int32_t handle, 68 | uint32_t code, const Parcel& data, 69 | Parcel* reply, uint32_t flags); 70 | 71 | void incStrongHandle(int32_t handle); 72 | void decStrongHandle(int32_t handle); 73 | void incWeakHandle(int32_t handle); 74 | void decWeakHandle(int32_t handle); 75 | status_t attemptIncStrongHandle(int32_t handle); 76 | static void expungeHandle(int32_t handle, IBinder* binder); 77 | status_t requestDeathNotification( int32_t handle, 78 | BpBinder* proxy); 79 | status_t clearDeathNotification( int32_t handle, 80 | BpBinder* proxy); 81 | 82 | static void shutdown(); 83 | 84 | // Call this to disable switching threads to background scheduling when 85 | // receiving incoming IPC calls. This is specifically here for the 86 | // Android system process, since it expects to have background apps calling 87 | // in to it but doesn't want to acquire locks in its services while in 88 | // the background. 89 | static void disableBackgroundScheduling(bool disable); 90 | 91 | private: 92 | IPCThreadState(); 93 | ~IPCThreadState(); 94 | 95 | status_t sendReply(const Parcel& reply, uint32_t flags); 96 | status_t waitForResponse(Parcel *reply, 97 | status_t *acquireResult=NULL); 98 | status_t talkWithDriver(bool doReceive=true); 99 | status_t writeTransactionData(int32_t cmd, 100 | uint32_t binderFlags, 101 | int32_t handle, 102 | uint32_t code, 103 | const Parcel& data, 104 | status_t* statusBuffer); 105 | status_t executeCommand(int32_t command); 106 | 107 | void clearCaller(); 108 | 109 | static void threadDestructor(void *st); 110 | static void freeBuffer(Parcel* parcel, 111 | const uint8_t* data, size_t dataSize, 112 | const size_t* objects, size_t objectsSize, 113 | void* cookie); 114 | // 指向一个ProcessState对象,负责初始化Binder设备 115 | // 打开设备文件/dev/binder,以及将设备文件/dev/binder映射到进程的地址空间 116 | // 由于这个ProcessState对象在进程范围内是唯一的 117 | // 因此,Binder线程池中的每一个线程都可以通过它来和Binder驱动程序建立连接 118 | const sp mProcess; 119 | const pid_t mMyThreadId; 120 | Vector mPendingStrongDerefs; 121 | Vector mPendingWeakDerefs; 122 | 123 | Parcel mIn; 124 | Parcel mOut; 125 | status_t mLastError; 126 | pid_t mCallingPid; 127 | uid_t mCallingUid; 128 | int32_t mStrictModePolicy; 129 | int32_t mLastTransactionBinderFlags; 130 | }; 131 | 132 | }; // namespace android 133 | 134 | // --------------------------------------------------------------------------- 135 | 136 | #endif // ANDROID_IPC_THREAD_STATE_H 137 | -------------------------------------------------------------------------------- /frameworks/base/include/binder/IPermissionController.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2005 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // 18 | #ifndef ANDROID_IPERMISSION_CONTROLLER_H 19 | #define ANDROID_IPERMISSION_CONTROLLER_H 20 | 21 | #include 22 | 23 | namespace android { 24 | 25 | // ---------------------------------------------------------------------- 26 | 27 | class IPermissionController : public IInterface 28 | { 29 | public: 30 | DECLARE_META_INTERFACE(PermissionController); 31 | 32 | virtual bool checkPermission(const String16& permission, 33 | int32_t pid, int32_t uid) = 0; 34 | 35 | enum { 36 | CHECK_PERMISSION_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION 37 | }; 38 | }; 39 | 40 | // ---------------------------------------------------------------------- 41 | 42 | class BnPermissionController : public BnInterface 43 | { 44 | public: 45 | virtual status_t onTransact( uint32_t code, 46 | const Parcel& data, 47 | Parcel* reply, 48 | uint32_t flags = 0); 49 | }; 50 | 51 | // ---------------------------------------------------------------------- 52 | 53 | }; // namespace android 54 | 55 | #endif // ANDROID_IPERMISSION_CONTROLLER_H 56 | 57 | -------------------------------------------------------------------------------- /frameworks/base/include/binder/IServiceManager.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2005 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // 18 | #ifndef ANDROID_ISERVICE_MANAGER_H 19 | #define ANDROID_ISERVICE_MANAGER_H 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | namespace android { 27 | 28 | // ---------------------------------------------------------------------- 29 | 30 | class IServiceManager : public IInterface 31 | { 32 | public: 33 | DECLARE_META_INTERFACE(ServiceManager); 34 | 35 | /** 36 | * Retrieve an existing service, blocking for a few seconds 37 | * if it doesn't yet exist. 38 | */ 39 | virtual sp getService( const String16& name) const = 0; 40 | 41 | /** 42 | * Retrieve an existing service, non-blocking. 43 | */ 44 | virtual sp checkService( const String16& name) const = 0; 45 | 46 | /** 47 | * Register a service. 48 | */ 49 | virtual status_t addService( const String16& name, 50 | const sp& service) = 0; 51 | 52 | /** 53 | * Return list of all existing services. 54 | */ 55 | virtual Vector listServices() = 0; 56 | 57 | enum { 58 | GET_SERVICE_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION, 59 | CHECK_SERVICE_TRANSACTION, 60 | ADD_SERVICE_TRANSACTION, 61 | LIST_SERVICES_TRANSACTION, 62 | }; 63 | }; 64 | 65 | sp defaultServiceManager(); 66 | 67 | template 68 | status_t getService(const String16& name, sp* outService) 69 | { 70 | const sp sm = defaultServiceManager(); 71 | if (sm != NULL) { 72 | *outService = interface_cast(sm->getService(name)); 73 | if ((*outService) != NULL) return NO_ERROR; 74 | } 75 | return NAME_NOT_FOUND; 76 | } 77 | 78 | bool checkCallingPermission(const String16& permission); 79 | bool checkCallingPermission(const String16& permission, 80 | int32_t* outPid, int32_t* outUid); 81 | bool checkPermission(const String16& permission, pid_t pid, uid_t uid); 82 | 83 | 84 | // ---------------------------------------------------------------------- 85 | 86 | class BnServiceManager : public BnInterface 87 | { 88 | public: 89 | virtual status_t onTransact( uint32_t code, 90 | const Parcel& data, 91 | Parcel* reply, 92 | uint32_t flags = 0); 93 | }; 94 | 95 | // ---------------------------------------------------------------------- 96 | 97 | }; // namespace android 98 | 99 | #endif // ANDROID_ISERVICE_MANAGER_H 100 | 101 | -------------------------------------------------------------------------------- /frameworks/base/include/binder/Parcel.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2005 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef ANDROID_PARCEL_H 18 | #define ANDROID_PARCEL_H 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | // --------------------------------------------------------------------------- 27 | namespace android { 28 | 29 | class Flattenable; 30 | class IBinder; 31 | class IPCThreadState; 32 | class ProcessState; 33 | class String8; 34 | class TextOutput; 35 | 36 | struct flat_binder_object; // defined in support_p/binder_module.h 37 | 38 | class Parcel 39 | { 40 | public: 41 | Parcel(); 42 | ~Parcel(); 43 | 44 | const uint8_t* data() const; 45 | size_t dataSize() const; 46 | size_t dataAvail() const; 47 | size_t dataPosition() const; 48 | size_t dataCapacity() const; 49 | 50 | status_t setDataSize(size_t size); 51 | void setDataPosition(size_t pos) const; 52 | status_t setDataCapacity(size_t size); 53 | 54 | status_t setData(const uint8_t* buffer, size_t len); 55 | 56 | status_t appendFrom(Parcel *parcel, size_t start, size_t len); 57 | 58 | bool hasFileDescriptors() const; 59 | 60 | // Writes the RPC header. 61 | status_t writeInterfaceToken(const String16& interface); 62 | 63 | // Parses the RPC header, returning true if the interface name 64 | // in the header matches the expected interface from the caller. 65 | // 66 | // Additionally, enforceInterface does part of the work of 67 | // propagating the StrictMode policy mask, populating the current 68 | // IPCThreadState, which as an optimization may optionally be 69 | // passed in. 70 | bool enforceInterface(const String16& interface, 71 | IPCThreadState* threadState = NULL) const; 72 | bool checkInterface(IBinder*) const; 73 | 74 | void freeData(); 75 | 76 | const size_t* objects() const; 77 | size_t objectsCount() const; 78 | 79 | status_t errorCheck() const; 80 | void setError(status_t err); 81 | 82 | status_t write(const void* data, size_t len); 83 | void* writeInplace(size_t len); 84 | status_t writeUnpadded(const void* data, size_t len); 85 | status_t writeInt32(int32_t val); 86 | status_t writeInt64(int64_t val); 87 | status_t writeFloat(float val); 88 | status_t writeDouble(double val); 89 | status_t writeIntPtr(intptr_t val); 90 | status_t writeCString(const char* str); 91 | status_t writeString8(const String8& str); 92 | status_t writeString16(const String16& str); 93 | status_t writeString16(const char16_t* str, size_t len); 94 | status_t writeStrongBinder(const sp& val); 95 | status_t writeWeakBinder(const wp& val); 96 | status_t write(const Flattenable& val); 97 | 98 | // Place a native_handle into the parcel (the native_handle's file- 99 | // descriptors are dup'ed, so it is safe to delete the native_handle 100 | // when this function returns). 101 | // Doesn't take ownership of the native_handle. 102 | status_t writeNativeHandle(const native_handle* handle); 103 | 104 | // Place a file descriptor into the parcel. The given fd must remain 105 | // valid for the lifetime of the parcel. 106 | status_t writeFileDescriptor(int fd); 107 | 108 | // Place a file descriptor into the parcel. A dup of the fd is made, which 109 | // will be closed once the parcel is destroyed. 110 | status_t writeDupFileDescriptor(int fd); 111 | 112 | status_t writeObject(const flat_binder_object& val, bool nullMetaData); 113 | 114 | // Like Parcel.java's writeNoException(). Just writes a zero int32. 115 | // Currently the native implementation doesn't do any of the StrictMode 116 | // stack gathering and serialization that the Java implementation does. 117 | status_t writeNoException(); 118 | 119 | void remove(size_t start, size_t amt); 120 | 121 | status_t read(void* outData, size_t len) const; 122 | const void* readInplace(size_t len) const; 123 | int32_t readInt32() const; 124 | status_t readInt32(int32_t *pArg) const; 125 | int64_t readInt64() const; 126 | status_t readInt64(int64_t *pArg) const; 127 | float readFloat() const; 128 | status_t readFloat(float *pArg) const; 129 | double readDouble() const; 130 | status_t readDouble(double *pArg) const; 131 | intptr_t readIntPtr() const; 132 | status_t readIntPtr(intptr_t *pArg) const; 133 | 134 | const char* readCString() const; 135 | String8 readString8() const; 136 | String16 readString16() const; 137 | const char16_t* readString16Inplace(size_t* outLen) const; 138 | sp readStrongBinder() const; 139 | wp readWeakBinder() const; 140 | status_t read(Flattenable& val) const; 141 | 142 | // Like Parcel.java's readExceptionCode(). Reads the first int32 143 | // off of a Parcel's header, returning 0 or the negative error 144 | // code on exceptions, but also deals with skipping over rich 145 | // response headers. Callers should use this to read & parse the 146 | // response headers rather than doing it by hand. 147 | int32_t readExceptionCode() const; 148 | 149 | // Retrieve native_handle from the parcel. This returns a copy of the 150 | // parcel's native_handle (the caller takes ownership). The caller 151 | // must free the native_handle with native_handle_close() and 152 | // native_handle_delete(). 153 | native_handle* readNativeHandle() const; 154 | 155 | 156 | // Retrieve a file descriptor from the parcel. This returns the raw fd 157 | // in the parcel, which you do not own -- use dup() to get your own copy. 158 | int readFileDescriptor() const; 159 | 160 | const flat_binder_object* readObject(bool nullMetaData) const; 161 | 162 | // Explicitly close all file descriptors in the parcel. 163 | void closeFileDescriptors(); 164 | 165 | typedef void (*release_func)(Parcel* parcel, 166 | const uint8_t* data, size_t dataSize, 167 | const size_t* objects, size_t objectsSize, 168 | void* cookie); 169 | 170 | const uint8_t* ipcData() const; 171 | size_t ipcDataSize() const; 172 | const size_t* ipcObjects() const; 173 | size_t ipcObjectsCount() const; 174 | void ipcSetDataReference(const uint8_t* data, size_t dataSize, 175 | const size_t* objects, size_t objectsCount, 176 | release_func relFunc, void* relCookie); 177 | 178 | void print(TextOutput& to, uint32_t flags = 0) const; 179 | 180 | private: 181 | Parcel(const Parcel& o); 182 | Parcel& operator=(const Parcel& o); 183 | 184 | status_t finishWrite(size_t len); 185 | void releaseObjects(); 186 | void acquireObjects(); 187 | status_t growData(size_t len); 188 | status_t restartWrite(size_t desired); 189 | status_t continueWrite(size_t desired); 190 | void freeDataNoInit(); 191 | void initState(); 192 | void scanForFds() const; 193 | 194 | template 195 | status_t readAligned(T *pArg) const; 196 | 197 | template T readAligned() const; 198 | 199 | template 200 | status_t writeAligned(T val); 201 | 202 | status_t mError; 203 | uint8_t* mData; 204 | size_t mDataSize; 205 | size_t mDataCapacity; 206 | mutable size_t mDataPos; 207 | size_t* mObjects; 208 | size_t mObjectsSize; 209 | size_t mObjectsCapacity; 210 | mutable size_t mNextObjectHint; 211 | 212 | mutable bool mFdsKnown; 213 | mutable bool mHasFds; 214 | 215 | release_func mOwner; 216 | void* mOwnerCookie; 217 | }; 218 | 219 | // --------------------------------------------------------------------------- 220 | 221 | inline TextOutput& operator<<(TextOutput& to, const Parcel& parcel) 222 | { 223 | parcel.print(to); 224 | return to; 225 | } 226 | 227 | // --------------------------------------------------------------------------- 228 | 229 | // Generic acquire and release of objects. 230 | void acquire_object(const sp& proc, 231 | const flat_binder_object& obj, const void* who); 232 | void release_object(const sp& proc, 233 | const flat_binder_object& obj, const void* who); 234 | 235 | void flatten_binder(const sp& proc, 236 | const sp& binder, flat_binder_object* out); 237 | void flatten_binder(const sp& proc, 238 | const wp& binder, flat_binder_object* out); 239 | status_t unflatten_binder(const sp& proc, 240 | const flat_binder_object& flat, sp* out); 241 | status_t unflatten_binder(const sp& proc, 242 | const flat_binder_object& flat, wp* out); 243 | 244 | }; // namespace android 245 | 246 | // --------------------------------------------------------------------------- 247 | 248 | #endif // ANDROID_PARCEL_H 249 | -------------------------------------------------------------------------------- /frameworks/base/include/binder/ProcessState.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2005 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef ANDROID_PROCESS_STATE_H 18 | #define ANDROID_PROCESS_STATE_H 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #include 26 | 27 | // --------------------------------------------------------------------------- 28 | namespace android { 29 | 30 | // Global variables 31 | extern int mArgC; 32 | extern const char* const* mArgV; 33 | extern int mArgLen; 34 | 35 | class IPCThreadState; 36 | 37 | class ProcessState : public virtual RefBase 38 | { 39 | public: 40 | // 静态对象可以通过self函数来获取 41 | static sp self(); 42 | 43 | static void setSingleProcess(bool singleProcess); 44 | 45 | void setContextObject(const sp& object); 46 | sp getContextObject(const sp& caller); 47 | 48 | void setContextObject(const sp& object, 49 | const String16& name); 50 | sp getContextObject(const String16& name, 51 | const sp& caller); 52 | 53 | bool supportsProcesses() const; 54 | 55 | void startThreadPool(); 56 | 57 | typedef bool (*context_check_func)(const String16& name, 58 | const sp& caller, 59 | void* userData); 60 | 61 | bool isContextManager(void) const; 62 | bool becomeContextManager( 63 | context_check_func checkFunc, 64 | void* userData); 65 | 66 | sp getStrongProxyForHandle(int32_t handle); 67 | wp getWeakProxyForHandle(int32_t handle); 68 | void expungeHandle(int32_t handle, IBinder* binder); 69 | 70 | void setArgs(int argc, const char* const argv[]); 71 | int getArgC() const; 72 | const char* const* getArgV() const; 73 | 74 | void setArgV0(const char* txt); 75 | 76 | void spawnPooledThread(bool isMain); 77 | 78 | private: 79 | friend class IPCThreadState; 80 | 81 | ProcessState(); 82 | ~ProcessState(); 83 | 84 | ProcessState(const ProcessState& o); 85 | ProcessState& operator=(const ProcessState& o); 86 | 87 | struct handle_entry { 88 | IBinder* binder; 89 | RefBase::weakref_type* refs; 90 | }; 91 | 92 | handle_entry* lookupHandleLocked(int32_t handle); 93 | 94 | int mDriverFD; 95 | void* mVMStart; 96 | 97 | mutable Mutex mLock; // protects everything below. 98 | 99 | VectormHandleToObject; 100 | 101 | bool mManagesContexts; 102 | context_check_func mBinderContextCheckFunc; 103 | void* mBinderContextUserData; 104 | 105 | KeyedVector > 106 | mContexts; 107 | 108 | 109 | String8 mRootDir; 110 | bool mThreadPoolStarted; 111 | volatile int32_t mThreadPoolSeq; 112 | }; 113 | 114 | }; // namespace android 115 | 116 | // --------------------------------------------------------------------------- 117 | 118 | #endif // ANDROID_PROCESS_STATE_H 119 | -------------------------------------------------------------------------------- /frameworks/base/libs/binder/Binder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2005 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | #include 25 | 26 | namespace android { 27 | 28 | // --------------------------------------------------------------------------- 29 | 30 | IBinder::IBinder() 31 | : RefBase() 32 | { 33 | } 34 | 35 | IBinder::~IBinder() 36 | { 37 | } 38 | 39 | // --------------------------------------------------------------------------- 40 | 41 | sp IBinder::queryLocalInterface(const String16& descriptor) 42 | { 43 | return NULL; 44 | } 45 | 46 | BBinder* IBinder::localBinder() 47 | { 48 | return NULL; 49 | } 50 | 51 | BpBinder* IBinder::remoteBinder() 52 | { 53 | return NULL; 54 | } 55 | 56 | bool IBinder::checkSubclass(const void* /*subclassID*/) const 57 | { 58 | return false; 59 | } 60 | 61 | // --------------------------------------------------------------------------- 62 | 63 | class BBinder::Extras 64 | { 65 | public: 66 | Mutex mLock; 67 | BpBinder::ObjectManager mObjects; 68 | }; 69 | 70 | // --------------------------------------------------------------------------- 71 | 72 | BBinder::BBinder() 73 | : mExtras(NULL) 74 | { 75 | } 76 | 77 | bool BBinder::isBinderAlive() const 78 | { 79 | return true; 80 | } 81 | 82 | status_t BBinder::pingBinder() 83 | { 84 | return NO_ERROR; 85 | } 86 | 87 | const String16& BBinder::getInterfaceDescriptor() const 88 | { 89 | // This is a local static rather than a global static, 90 | // to avoid static initializer ordering issues. 91 | static String16 sEmptyDescriptor; 92 | LOGW("reached BBinder::getInterfaceDescriptor (this=%p)", this); 93 | return sEmptyDescriptor; 94 | } 95 | 96 | status_t BBinder::transact( 97 | uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 98 | { 99 | data.setDataPosition(0); 100 | 101 | status_t err = NO_ERROR; 102 | switch (code) { 103 | case PING_TRANSACTION: 104 | reply->writeInt32(pingBinder()); 105 | break; 106 | default: 107 | err = onTransact(code, data, reply, flags); 108 | break; 109 | } 110 | 111 | if (reply != NULL) { 112 | reply->setDataPosition(0); 113 | } 114 | 115 | return err; 116 | } 117 | 118 | status_t BBinder::linkToDeath( 119 | const sp& recipient, void* cookie, uint32_t flags) 120 | { 121 | return INVALID_OPERATION; 122 | } 123 | 124 | status_t BBinder::unlinkToDeath( 125 | const wp& recipient, void* cookie, uint32_t flags, 126 | wp* outRecipient) 127 | { 128 | return INVALID_OPERATION; 129 | } 130 | 131 | status_t BBinder::dump(int fd, const Vector& args) 132 | { 133 | return NO_ERROR; 134 | } 135 | 136 | void BBinder::attachObject( 137 | const void* objectID, void* object, void* cleanupCookie, 138 | object_cleanup_func func) 139 | { 140 | Extras* e = mExtras; 141 | 142 | if (!e) { 143 | e = new Extras; 144 | if (android_atomic_cmpxchg(0, reinterpret_cast(e), 145 | reinterpret_cast(&mExtras)) != 0) { 146 | delete e; 147 | e = mExtras; 148 | } 149 | if (e == 0) return; // out of memory 150 | } 151 | 152 | AutoMutex _l(e->mLock); 153 | e->mObjects.attach(objectID, object, cleanupCookie, func); 154 | } 155 | 156 | void* BBinder::findObject(const void* objectID) const 157 | { 158 | Extras* e = mExtras; 159 | if (!e) return NULL; 160 | 161 | AutoMutex _l(e->mLock); 162 | return e->mObjects.find(objectID); 163 | } 164 | 165 | void BBinder::detachObject(const void* objectID) 166 | { 167 | Extras* e = mExtras; 168 | if (!e) return; 169 | 170 | AutoMutex _l(e->mLock); 171 | e->mObjects.detach(objectID); 172 | } 173 | 174 | BBinder* BBinder::localBinder() 175 | { 176 | return this; 177 | } 178 | 179 | BBinder::~BBinder() 180 | { 181 | if (mExtras) delete mExtras; 182 | } 183 | 184 | 185 | status_t BBinder::onTransact( 186 | uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 187 | { 188 | switch (code) { 189 | case INTERFACE_TRANSACTION: 190 | reply->writeString16(getInterfaceDescriptor()); 191 | return NO_ERROR; 192 | 193 | case DUMP_TRANSACTION: { 194 | int fd = data.readFileDescriptor(); 195 | int argc = data.readInt32(); 196 | Vector args; 197 | for (int i = 0; i < argc && data.dataAvail() > 0; i++) { 198 | args.add(data.readString16()); 199 | } 200 | return dump(fd, args); 201 | } 202 | default: 203 | return UNKNOWN_TRANSACTION; 204 | } 205 | } 206 | 207 | // --------------------------------------------------------------------------- 208 | 209 | enum { 210 | // This is used to transfer ownership of the remote binder from 211 | // the BpRefBase object holding it (when it is constructed), to the 212 | // owner of the BpRefBase object when it first acquires that BpRefBase. 213 | kRemoteAcquired = 0x00000001 214 | }; 215 | 216 | BpRefBase::BpRefBase(const sp& o) 217 | : mRemote(o.get()), mRefs(NULL), mState(0) 218 | { 219 | extendObjectLifetime(OBJECT_LIFETIME_WEAK); 220 | 221 | if (mRemote) { 222 | mRemote->incStrong(this); // Removed on first IncStrong(). 223 | mRefs = mRemote->createWeak(this); // Held for our entire lifetime. 224 | } 225 | } 226 | 227 | BpRefBase::~BpRefBase() 228 | { 229 | if (mRemote) { 230 | if (!(mState&kRemoteAcquired)) { 231 | mRemote->decStrong(this); 232 | } 233 | mRefs->decWeak(this); 234 | } 235 | } 236 | 237 | void BpRefBase::onFirstRef() 238 | { 239 | android_atomic_or(kRemoteAcquired, &mState); 240 | } 241 | 242 | void BpRefBase::onLastStrongRef(const void* id) 243 | { 244 | if (mRemote) { 245 | mRemote->decStrong(this); 246 | } 247 | } 248 | 249 | bool BpRefBase::onIncStrongAttempted(uint32_t flags, const void* id) 250 | { 251 | return mRemote ? mRefs->attemptIncStrong(this) : false; 252 | } 253 | 254 | // --------------------------------------------------------------------------- 255 | 256 | }; // namespace android 257 | -------------------------------------------------------------------------------- /frameworks/base/libs/binder/BpBinder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2005 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #define LOG_TAG "BpBinder" 18 | //#define LOG_NDEBUG 0 19 | 20 | #include 21 | 22 | #include 23 | #include 24 | 25 | #include 26 | 27 | //#undef LOGV 28 | //#define LOGV(...) fprintf(stderr, __VA_ARGS__) 29 | 30 | namespace android { 31 | 32 | // --------------------------------------------------------------------------- 33 | 34 | BpBinder::ObjectManager::ObjectManager() 35 | { 36 | } 37 | 38 | BpBinder::ObjectManager::~ObjectManager() 39 | { 40 | kill(); 41 | } 42 | 43 | // 增加外部对象 44 | void BpBinder::ObjectManager::attach( 45 | const void* objectID, void* object, void* cleanupCookie, 46 | IBinder::object_cleanup_func func) 47 | { 48 | // 创建entry_t结构体 49 | entry_t e; 50 | e.object = object; 51 | e.cleanupCookie = cleanupCookie; 52 | e.func = func; 53 | 54 | if (mObjects.indexOfKey(objectID) >= 0) { 55 | LOGE("Trying to attach object ID %p to binder ObjectManager %p with object %p, but object ID already in use", 56 | objectID, this, object); 57 | return; 58 | } 59 | 60 | // 用来标志entry_t 61 | mObjects.add(objectID, e); 62 | } 63 | 64 | void* BpBinder::ObjectManager::find(const void* objectID) const 65 | { 66 | // 获取一个Object 67 | const ssize_t i = mObjects.indexOfKey(objectID); 68 | if (i < 0) return NULL; 69 | return mObjects.valueAt(i).object; 70 | } 71 | 72 | void BpBinder::ObjectManager::detach(const void* objectID) 73 | { 74 | mObjects.removeItem(objectID); 75 | } 76 | 77 | void BpBinder::ObjectManager::kill() 78 | { 79 | const size_t N = mObjects.size(); 80 | LOGV("Killing %d objects in manager %p", N, this); 81 | for (size_t i=0; iincWeakHandle(handle); 127 | } 128 | 129 | bool BpBinder::isDescriptorCached() const { 130 | Mutex::Autolock _l(mLock); 131 | return mDescriptorCache.size() ? true : false; 132 | } 133 | 134 | const String16& BpBinder::getInterfaceDescriptor() const 135 | { 136 | if (isDescriptorCached() == false) { 137 | Parcel send, reply; 138 | // do the IPC without a lock held. 139 | status_t err = const_cast(this)->transact( 140 | INTERFACE_TRANSACTION, send, &reply); 141 | if (err == NO_ERROR) { 142 | String16 res(reply.readString16()); 143 | Mutex::Autolock _l(mLock); 144 | // mDescriptorCache could have been assigned while the lock was 145 | // released. 146 | if (mDescriptorCache.size() == 0) 147 | mDescriptorCache = res; 148 | } 149 | } 150 | 151 | // we're returning a reference to a non-static object here. Usually this 152 | // is not something smart to do, however, with binder objects it is 153 | // (usually) safe because they are reference-counted. 154 | 155 | return mDescriptorCache; 156 | } 157 | 158 | bool BpBinder::isBinderAlive() const 159 | { 160 | return mAlive != 0; 161 | } 162 | 163 | status_t BpBinder::pingBinder() 164 | { 165 | Parcel send; 166 | Parcel reply; 167 | status_t err = transact(PING_TRANSACTION, send, &reply); 168 | if (err != NO_ERROR) return err; 169 | if (reply.dataSize() < sizeof(status_t)) return NOT_ENOUGH_DATA; 170 | return (status_t)reply.readInt32(); 171 | } 172 | 173 | status_t BpBinder::dump(int fd, const Vector& args) 174 | { 175 | Parcel send; 176 | Parcel reply; 177 | send.writeFileDescriptor(fd); 178 | const size_t numArgs = args.size(); 179 | send.writeInt32(numArgs); 180 | for (size_t i = 0; i < numArgs; i++) { 181 | send.writeString16(args[i]); 182 | } 183 | status_t err = transact(DUMP_TRANSACTION, send, &reply); 184 | return err; 185 | } 186 | 187 | status_t BpBinder::transact( 188 | uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 189 | { 190 | // Once a binder has died, it will never come back to life. 191 | if (mAlive) { 192 | status_t status = IPCThreadState::self()->transact( 193 | mHandle, code, data, reply, flags); 194 | if (status == DEAD_OBJECT) mAlive = 0; 195 | return status; 196 | } 197 | 198 | return DEAD_OBJECT; 199 | } 200 | 201 | // 一个Binder代理对象可以注册多个死亡通知接收者,它们保存在Binder代理对象内部的一个obituary列表中 202 | // 每一个死亡通知接收者都可以使用一个Obituary对象来描述 203 | // Binder代理对象内部的成员变脸mObitsSent用来表示Binder驱动程序是否已经向它发送过死亡通知 204 | // 如果是,则它的值为1 205 | // 在这种情况下,Binder代理对象的成员函数linkToDeath就会直接返回一个DEAD_OBJECT的值,表示Binder本地对象已经死亡了 206 | // 如果不是 207 | // 那么它的成员函数linkToDeath首先会将死亡接收者封装成一个Obituary对象,接着将它添加到内部的列表mObituaries中 208 | // 如果是第一次注册死亡通知接受者 209 | // 函数会调用当前线程中的IPCThreadState对象的成员函数requestDeathNotification来向Binder驱动注册一个死亡通知 210 | status_t BpBinder::linkToDeath( 211 | const sp& recipient, void* cookie, uint32_t flags) 212 | { 213 | Obituary ob; 214 | // cookie和flags用来标志一个死亡通知接受者,在注销死亡接受者时会用到 215 | ob.recipient = recipient; 216 | ob.cookie = cookie; 217 | ob.flags = flags; 218 | 219 | LOG_ALWAYS_FATAL_IF(recipient == NULL, 220 | "linkToDeath(): recipient must be non-NULL"); 221 | 222 | { 223 | AutoMutex _l(mLock); 224 | 225 | if (!mObitsSent) { 226 | if (!mObituaries) { 227 | mObituaries = new Vector; 228 | if (!mObituaries) { 229 | return NO_MEMORY; 230 | } 231 | LOGV("Requesting death notification: %p handle %d\n", this, mHandle); 232 | getWeakRefs()->incWeak(this); 233 | IPCThreadState* self = IPCThreadState::self(); 234 | self->requestDeathNotification(mHandle, this); 235 | // 促使当前线程马上通过IO控制命令BINDER_WRITE_READ进入到Binder驱动中 236 | // 以便可以执行注册死亡接受通知的操作 237 | self->flushCommands(); 238 | } 239 | ssize_t res = mObituaries->add(ob); 240 | return res >= (ssize_t)NO_ERROR ? (status_t)NO_ERROR : res; 241 | } 242 | } 243 | 244 | return DEAD_OBJECT; 245 | } 246 | 247 | // recipient: 注册到Binder代理对象内部的一个死亡通知接收者 248 | // cookie, flags: 标志该死亡通知接受者的数据 249 | // outRecipient: 输出参数,返回前面所注册的一个死亡通知接收者 250 | status_t BpBinder::unlinkToDeath( 251 | const wp& recipient, void* cookie, uint32_t flags, 252 | wp* outRecipient) 253 | { 254 | AutoMutex _l(mLock); 255 | 256 | if (mObitsSent) { 257 | return DEAD_OBJECT; 258 | } 259 | 260 | const size_t N = mObituaries ? mObituaries->size() : 0; 261 | for (size_t i=0; iitemAt(i); 263 | // 是否存在与要注销的死亡通知者对应的Obituary 264 | if ((obit.recipient == recipient 265 | || (recipient == NULL && obit.cookie == cookie)) 266 | && obit.flags == flags) { 267 | const uint32_t allFlags = obit.flags|flags; 268 | if (outRecipient != NULL) { 269 | *outRecipient = mObituaries->itemAt(i).recipient; 270 | } 271 | mObituaries->removeAt(i); 272 | if (mObituaries->size() == 0) { 273 | LOGV("Clearing death notification: %p handle %d\n", this, mHandle); 274 | // 获取IPCThreadState对象 275 | IPCThreadState* self = IPCThreadState::self(); 276 | // 注销死亡接受通知操作 277 | self->clearDeathNotification(mHandle, this); 278 | // 调用后发送操作马上执行 279 | self->flushCommands(); 280 | delete mObituaries; 281 | mObituaries = NULL; 282 | } 283 | return NO_ERROR; 284 | } 285 | } 286 | 287 | return NAME_NOT_FOUND; 288 | } 289 | 290 | void BpBinder::sendObituary() 291 | { 292 | LOGV("Sending obituary for proxy %p handle %d, mObitsSent=%s\n", 293 | this, mHandle, mObitsSent ? "true" : "false"); 294 | 295 | mAlive = 0; 296 | if (mObitsSent) return; 297 | 298 | mLock.lock(); 299 | Vector* obits = mObituaries; 300 | // 检查该Binder代理对象内部的列表是否为空 301 | if(obits != NULL) { 302 | LOGV("Clearing sent death notification: %p handle %d\n", this, mHandle); 303 | IPCThreadState* self = IPCThreadState::self(); 304 | // 如果为空,就说明该Binder代理对象之前向Binder驱动程序注册过死亡接收通知 305 | self->clearDeathNotification(mHandle, this); 306 | self->flushCommands(); 307 | mObituaries = NULL; 308 | } 309 | // 已经接收过驱动发送过来的死亡接收通知 310 | mObitsSent = 1; 311 | mLock.unlock(); 312 | 313 | LOGV("Reporting death of proxy %p for %d recipients\n", 314 | this, obits ? obits->size() : 0); 315 | 316 | if (obits != NULL) { 317 | const size_t N = obits->size(); 318 | for (size_t i=0; iitemAt(i)); 321 | } 322 | 323 | delete obits; 324 | } 325 | } 326 | 327 | void BpBinder::reportOneDeath(const Obituary& obit) 328 | { 329 | // 获得死亡通知接收者 330 | sp recipient = obit.recipient.promote(); 331 | LOGV("Reporting death to recipient: %p\n", recipient.get()); 332 | if (recipient == NULL) return; 333 | 334 | // 调用它的成员函数binderDied来处理这个死亡接收通知 335 | recipient->binderDied(this); 336 | } 337 | 338 | 339 | void BpBinder::attachObject( 340 | const void* objectID, void* object, void* cleanupCookie, 341 | object_cleanup_func func) 342 | { 343 | AutoMutex _l(mLock); 344 | LOGV("Attaching object %p to binder %p (manager=%p)", object, this, &mObjects); 345 | mObjects.attach(objectID, object, cleanupCookie, func); 346 | } 347 | 348 | void* BpBinder::findObject(const void* objectID) const 349 | { 350 | AutoMutex _l(mLock); 351 | return mObjects.find(objectID); 352 | } 353 | 354 | void BpBinder::detachObject(const void* objectID) 355 | { 356 | AutoMutex _l(mLock); 357 | mObjects.detach(objectID); 358 | } 359 | 360 | BpBinder* BpBinder::remoteBinder() 361 | { 362 | return this; 363 | } 364 | 365 | BpBinder::~BpBinder() 366 | { 367 | LOGV("Destroying BpBinder %p handle %d\n", this, mHandle); 368 | 369 | IPCThreadState* ipc = IPCThreadState::self(); 370 | 371 | mLock.lock(); 372 | Vector* obits = mObituaries; 373 | if(obits != NULL) { 374 | if (ipc) ipc->clearDeathNotification(mHandle, this); 375 | mObituaries = NULL; 376 | } 377 | mLock.unlock(); 378 | 379 | if (obits != NULL) { 380 | // XXX Should we tell any remaining DeathRecipient 381 | // objects that the last strong ref has gone away, so they 382 | // are no longer linked? 383 | delete obits; 384 | } 385 | 386 | if (ipc) { 387 | ipc->expungeHandle(mHandle, this); 388 | // 当一个Binder代理对象销毁时,当前线程就会调用内部的IPCThreadState对象函数来减少相应的Binder引用对象的弱引用计数 389 | ipc->decWeakHandle(mHandle); 390 | } 391 | } 392 | 393 | // 当一个Binder代理对象不再被任何强指针引用时,Cient进程就会请求Binder驱动减少相应的Binder引用对象的强引用计数 394 | void BpBinder::onFirstRef() 395 | { 396 | LOGV("onFirstRef BpBinder %p handle %d\n", this, mHandle); 397 | IPCThreadState* ipc = IPCThreadState::self(); 398 | // 调用相应的函数以增加相应的Binder引用对象的强引用计数 399 | if (ipc) ipc->incStrongHandle(mHandle); 400 | } 401 | 402 | // Binder代理对象的引用计数与它所引用的Binder引用对象的引用计数是多对一的关系 403 | // 这样做可以减少Client进程和Binder驱动程序之间的交互 404 | // 减少它们之间的协议来往 405 | void BpBinder::onLastStrongRef(const void* id) 406 | { 407 | LOGV("onLastStrongRef BpBinder %p handle %d\n", this, mHandle); 408 | IF_LOGV() { 409 | printRefs(); 410 | } 411 | IPCThreadState* ipc = IPCThreadState::self(); 412 | // 调用函数以减少Binder引用对象的强引用计数 413 | if (ipc) ipc->decStrongHandle(mHandle); 414 | } 415 | 416 | bool BpBinder::onIncStrongAttempted(uint32_t flags, const void* id) 417 | { 418 | LOGV("onIncStrongAttempted BpBinder %p handle %d\n", this, mHandle); 419 | IPCThreadState* ipc = IPCThreadState::self(); 420 | return ipc ? ipc->attemptIncStrongHandle(mHandle) == NO_ERROR : false; 421 | } 422 | 423 | // --------------------------------------------------------------------------- 424 | 425 | }; // namespace android 426 | -------------------------------------------------------------------------------- /frameworks/base/libs/binder/IInterface.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2005 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | namespace android { 20 | 21 | // --------------------------------------------------------------------------- 22 | 23 | IInterface::IInterface() 24 | : RefBase() { 25 | } 26 | 27 | IInterface::~IInterface() { 28 | } 29 | 30 | sp IInterface::asBinder() 31 | { 32 | return this ? onAsBinder() : NULL; 33 | } 34 | 35 | sp IInterface::asBinder() const 36 | { 37 | return this ? const_cast(this)->onAsBinder() : NULL; 38 | } 39 | 40 | // --------------------------------------------------------------------------- 41 | 42 | }; // namespace android 43 | -------------------------------------------------------------------------------- /frameworks/base/libs/binder/IServiceManager.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2005 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #define LOG_TAG "ServiceManager" 18 | 19 | #include 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | #include 29 | 30 | #include 31 | 32 | namespace android { 33 | 34 | // 单例 35 | sp defaultServiceManager() 36 | { 37 | // 全局变量gDefaultServiceManager是一个IServiceManager的强指针 38 | // 指向进程内的一个BpServiceManager对象 39 | if (gDefaultServiceManager != NULL) return gDefaultServiceManager; 40 | 41 | { 42 | AutoMutex _l(gDefaultServiceManagerLock); 43 | if (gDefaultServiceManager == NULL) { 44 | // 获取ProcessState对象,创建一个Binder代理对象,调用模板函数将前面获得的Binder代理对象封装成一个Service Manager代理对象 45 | gDefaultServiceManager = interface_cast( 46 | ProcessState::self()->getContextObject(NULL)); 47 | } 48 | } 49 | 50 | return gDefaultServiceManager; 51 | } 52 | 53 | bool checkCallingPermission(const String16& permission) 54 | { 55 | return checkCallingPermission(permission, NULL, NULL); 56 | } 57 | 58 | static String16 _permission("permission"); 59 | 60 | 61 | bool checkCallingPermission(const String16& permission, int32_t* outPid, int32_t* outUid) 62 | { 63 | IPCThreadState* ipcState = IPCThreadState::self(); 64 | pid_t pid = ipcState->getCallingPid(); 65 | uid_t uid = ipcState->getCallingUid(); 66 | if (outPid) *outPid = pid; 67 | if (outUid) *outUid = uid; 68 | return checkPermission(permission, pid, uid); 69 | } 70 | 71 | bool checkPermission(const String16& permission, pid_t pid, uid_t uid) 72 | { 73 | sp pc; 74 | gDefaultServiceManagerLock.lock(); 75 | pc = gPermissionController; 76 | gDefaultServiceManagerLock.unlock(); 77 | 78 | int64_t startTime = 0; 79 | 80 | while (true) { 81 | if (pc != NULL) { 82 | bool res = pc->checkPermission(permission, pid, uid); 83 | if (res) { 84 | if (startTime != 0) { 85 | LOGI("Check passed after %d seconds for %s from uid=%d pid=%d", 86 | (int)((uptimeMillis()-startTime)/1000), 87 | String8(permission).string(), uid, pid); 88 | } 89 | return res; 90 | } 91 | 92 | // Is this a permission failure, or did the controller go away? 93 | if (pc->asBinder()->isBinderAlive()) { 94 | LOGW("Permission failure: %s from uid=%d pid=%d", 95 | String8(permission).string(), uid, pid); 96 | return false; 97 | } 98 | 99 | // Object is dead! 100 | gDefaultServiceManagerLock.lock(); 101 | if (gPermissionController == pc) { 102 | gPermissionController = NULL; 103 | } 104 | gDefaultServiceManagerLock.unlock(); 105 | } 106 | 107 | // Need to retrieve the permission controller. 108 | sp binder = defaultServiceManager()->checkService(_permission); 109 | if (binder == NULL) { 110 | // Wait for the permission controller to come back... 111 | if (startTime == 0) { 112 | startTime = uptimeMillis(); 113 | LOGI("Waiting to check permission %s from uid=%d pid=%d", 114 | String8(permission).string(), uid, pid); 115 | } 116 | sleep(1); 117 | } else { 118 | pc = interface_cast(binder); 119 | // Install the new permission controller, and try again. 120 | gDefaultServiceManagerLock.lock(); 121 | gPermissionController = pc; 122 | gDefaultServiceManagerLock.unlock(); 123 | } 124 | } 125 | } 126 | 127 | // ---------------------------------------------------------------------- 128 | 129 | class BpServiceManager : public BpInterface 130 | { 131 | public: 132 | BpServiceManager(const sp& impl) 133 | : BpInterface(impl) 134 | { 135 | } 136 | 137 | virtual sp getService(const String16& name) const 138 | { 139 | unsigned n; 140 | for (n = 0; n < 5; n++){ 141 | // 尝试5次来获得代理对象 142 | sp svc = checkService(name); 143 | if (svc != NULL) return svc; 144 | LOGI("Waiting for service %s...\n", String8(name).string()); 145 | sleep(1); 146 | } 147 | return NULL; 148 | } 149 | 150 | virtual sp checkService( const String16& name) const 151 | { 152 | Parcel data, reply; 153 | data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor()); 154 | data.writeString16(name); 155 | remote()->transact(CHECK_SERVICE_TRANSACTION, data, &reply); 156 | return reply.readStrongBinder(); 157 | } 158 | 159 | // 添加service 160 | virtual status_t addService(const String16& name, const sp& service) 161 | { 162 | // 1. 封装成一个Parcel对象 163 | // 2. Client发送BR_TRANSACTION到驱动 164 | // 3. 驱动发送BR_TRANSACTION_COMPLETE返回协议到Client 165 | // 4. Client接受BR_TRANSACTION_COMPLETE返回协议,对它进行处理后,再次进入Binder驱动程序等待Server进程 166 | // 5. 驱动向Server发送BR_TRANSACTION,请求目标server进程处理该进程通信请求 167 | // 6. Server收到Binder驱动BR_TRANSACTION返回协议,并且对它进行处理之后,就会向Binder驱动发送BC_REPLY命令协议 168 | // 7. 驱动程序根据协议内容找到目标Client就会向Server发送BR_TRANSACTION_COMPLETE返回协议 169 | // 8. Server进程接收到驱动发送它的BR_TRANSACTION_COMPLETE返回协议,并且对它进行处理之后,一次进程间通信过程就结束了 170 | // 9. Binder驱动向Server进程发送BR_TRANSACTION_COMPLETE返回协议的同时,也会向Client进程发送BR_REPLY,表示Server进程已经处理完成的进程间通信 171 | Parcel data, reply; 172 | data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor()); 173 | // 写入组件名称 174 | data.writeString16(name); 175 | // 将要注册的service组件封装成一个flat_binder_object,传递个驱动 176 | data.writeStrongBinder(service); 177 | // 调用transact发送BC_TRANSACTION命令协议 178 | status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply); 179 | return err == NO_ERROR ? reply.readExceptionCode() : err; 180 | } 181 | 182 | virtual Vector listServices() 183 | { 184 | Vector res; 185 | int n = 0; 186 | 187 | for (;;) { 188 | Parcel data, reply; 189 | data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor()); 190 | data.writeInt32(n++); 191 | status_t err = remote()->transact(LIST_SERVICES_TRANSACTION, data, &reply); 192 | if (err != NO_ERROR) 193 | break; 194 | res.add(reply.readString16()); 195 | } 196 | return res; 197 | } 198 | }; 199 | 200 | IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager"); 201 | 202 | // ---------------------------------------------------------------------- 203 | 204 | status_t BnServiceManager::onTransact( 205 | uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 206 | { 207 | //printf("ServiceManager received: "); data.print(); 208 | switch(code) { 209 | case GET_SERVICE_TRANSACTION: { 210 | CHECK_INTERFACE(IServiceManager, data, reply); 211 | String16 which = data.readString16(); 212 | sp b = const_cast(this)->getService(which); 213 | reply->writeStrongBinder(b); 214 | return NO_ERROR; 215 | } break; 216 | case CHECK_SERVICE_TRANSACTION: { 217 | CHECK_INTERFACE(IServiceManager, data, reply); 218 | String16 which = data.readString16(); 219 | sp b = const_cast(this)->checkService(which); 220 | reply->writeStrongBinder(b); 221 | return NO_ERROR; 222 | } break; 223 | case ADD_SERVICE_TRANSACTION: { 224 | CHECK_INTERFACE(IServiceManager, data, reply); 225 | String16 which = data.readString16(); 226 | sp b = data.readStrongBinder(); 227 | status_t err = addService(which, b); 228 | reply->writeInt32(err); 229 | return NO_ERROR; 230 | } break; 231 | case LIST_SERVICES_TRANSACTION: { 232 | CHECK_INTERFACE(IServiceManager, data, reply); 233 | Vector list = listServices(); 234 | const size_t N = list.size(); 235 | reply->writeInt32(N); 236 | for (size_t i=0; iwriteString16(list[i]); 238 | } 239 | return NO_ERROR; 240 | } break; 241 | default: 242 | return BBinder::onTransact(code, data, reply, flags); 243 | } 244 | } 245 | 246 | }; // namespace android 247 | -------------------------------------------------------------------------------- /frameworks/base/libs/binder/ProcessState.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2005 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #define LOG_TAG "ProcessState" 18 | 19 | #include 20 | 21 | #include 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | #include 33 | #include 34 | 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | 44 | #define BINDER_VM_SIZE ((1*1024*1024) - (4096 *2)) 45 | 46 | static bool gSingleProcess = false; 47 | 48 | 49 | // --------------------------------------------------------------------------- 50 | 51 | namespace android { 52 | 53 | // Global variables 54 | int mArgC; 55 | const char* const* mArgV; 56 | int mArgLen; 57 | 58 | class PoolThread : public Thread 59 | { 60 | public: 61 | PoolThread(bool isMain) 62 | : mIsMain(isMain) 63 | { 64 | } 65 | 66 | protected: 67 | virtual bool threadLoop() 68 | { 69 | // 调用当前线程中的IPCThreadState对象函数joinThreadPool,将当前线程注册到Binder驱动程序中 70 | // 成为一个Binder线程,以便Binder驱动程序可以分发进程间通信请求给它处理 71 | IPCThreadState::self()->joinThreadPool(mIsMain); 72 | return false; 73 | } 74 | 75 | const bool mIsMain; 76 | }; 77 | 78 | // 单例 79 | sp ProcessState::self() 80 | { 81 | if (gProcess != NULL) return gProcess; 82 | 83 | AutoMutex _l(gProcessMutex); 84 | if (gProcess == NULL) gProcess = new ProcessState; 85 | return gProcess; 86 | } 87 | 88 | void ProcessState::setSingleProcess(bool singleProcess) 89 | { 90 | gSingleProcess = singleProcess; 91 | } 92 | 93 | 94 | void ProcessState::setContextObject(const sp& object) 95 | { 96 | setContextObject(object, String16("default")); 97 | } 98 | 99 | sp ProcessState::getContextObject(const sp& caller) 100 | { 101 | // 检查进程是否打开了设备/dev/binder 102 | if (supportsProcesses()) { 103 | return getStrongProxyForHandle(0); 104 | } else { 105 | return getContextObject(String16("default"), caller); 106 | } 107 | } 108 | 109 | void ProcessState::setContextObject(const sp& object, const String16& name) 110 | { 111 | AutoMutex _l(mLock); 112 | mContexts.add(name, object); 113 | } 114 | 115 | sp ProcessState::getContextObject(const String16& name, const sp& caller) 116 | { 117 | mLock.lock(); 118 | sp object( 119 | mContexts.indexOfKey(name) >= 0 ? mContexts.valueFor(name) : NULL); 120 | mLock.unlock(); 121 | 122 | //printf("Getting context object %s for %p\n", String8(name).string(), caller.get()); 123 | 124 | if (object != NULL) return object; 125 | 126 | // Don't attempt to retrieve contexts if we manage them 127 | if (mManagesContexts) { 128 | LOGE("getContextObject(%s) failed, but we manage the contexts!\n", 129 | String8(name).string()); 130 | return NULL; 131 | } 132 | 133 | IPCThreadState* ipc = IPCThreadState::self(); 134 | { 135 | Parcel data, reply; 136 | // no interface token on this magic transaction 137 | data.writeString16(name); 138 | data.writeStrongBinder(caller); 139 | status_t result = ipc->transact(0 /*magic*/, 0, data, &reply, 0); 140 | if (result == NO_ERROR) { 141 | object = reply.readStrongBinder(); 142 | } 143 | } 144 | 145 | ipc->flushCommands(); 146 | 147 | if (object != NULL) setContextObject(object, name); 148 | return object; 149 | } 150 | 151 | bool ProcessState::supportsProcesses() const 152 | { 153 | return mDriverFD >= 0; 154 | } 155 | 156 | void ProcessState::startThreadPool() 157 | { 158 | AutoMutex _l(mLock); 159 | // 线程池只能启动一次 160 | if (!mThreadPoolStarted) { 161 | mThreadPoolStarted = true; 162 | spawnPooledThread(true); 163 | } 164 | } 165 | 166 | bool ProcessState::isContextManager(void) const 167 | { 168 | return mManagesContexts; 169 | } 170 | 171 | bool ProcessState::becomeContextManager(context_check_func checkFunc, void* userData) 172 | { 173 | if (!mManagesContexts) { 174 | AutoMutex _l(mLock); 175 | mBinderContextCheckFunc = checkFunc; 176 | mBinderContextUserData = userData; 177 | if (mDriverFD >= 0) { 178 | int dummy = 0; 179 | #if defined(HAVE_ANDROID_OS) 180 | status_t result = ioctl(mDriverFD, BINDER_SET_CONTEXT_MGR, &dummy); 181 | #else 182 | status_t result = INVALID_OPERATION; 183 | #endif 184 | if (result == 0) { 185 | mManagesContexts = true; 186 | } else if (result == -1) { 187 | mBinderContextCheckFunc = NULL; 188 | mBinderContextUserData = NULL; 189 | LOGE("Binder ioctl to become context manager failed: %s\n", strerror(errno)); 190 | } 191 | } else { 192 | // If there is no driver, our only world is the local 193 | // process so we can always become the context manager there. 194 | mManagesContexts = true; 195 | } 196 | } 197 | return mManagesContexts; 198 | } 199 | 200 | ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle) 201 | { 202 | const size_t N=mHandleToObject.size(); 203 | if (N <= (size_t)handle) { 204 | // mHanldeToObject不存在这个handle_entry结构体 205 | handle_entry e; 206 | e.binder = NULL; 207 | e.refs = NULL; 208 | // 插入一个结构体 209 | status_t err = mHandleToObject.insertAt(e, N, handle+1-N); 210 | if (err < NO_ERROR) return NULL; 211 | } 212 | // 返回给调用者 213 | return &mHandleToObject.editItemAt(handle); 214 | } 215 | 216 | // 创建一个Binder代理对象 217 | sp ProcessState::getStrongProxyForHandle(int32_t handle) 218 | { 219 | sp result; 220 | 221 | AutoMutex _l(mLock); 222 | 223 | // Binder代理对象的生命周期期间每一个进程维护了一个handle_entry类型的Binder代理对象列表 224 | // 通过句柄值找到对应的handle_entry结构体 225 | handle_entry* e = lookupHandleLocked(handle); 226 | 227 | if (e != NULL) { 228 | // We need to create a new BpBinder if there isn't currently one, OR we 229 | // are unable to acquire a weak reference on this current one. See comment 230 | // in getWeakProxyForHandle() for more info about this. 231 | IBinder* b = e->binder; 232 | if (b == NULL || !e->refs->attemptIncWeak(this)) { 233 | b = new BpBinder(handle); 234 | e->binder = b; 235 | if (b) e->refs = b->getWeakRefs(); 236 | result = b; 237 | } else { 238 | // This little bit of nastyness is to allow us to add a primary 239 | // reference to the remote proxy when this team doesn't have one 240 | // but another team is sending the handle to us. 241 | result.force_set(b); 242 | e->refs->decWeak(this); 243 | } 244 | } 245 | 246 | return result; 247 | } 248 | 249 | wp ProcessState::getWeakProxyForHandle(int32_t handle) 250 | { 251 | wp result; 252 | 253 | AutoMutex _l(mLock); 254 | 255 | handle_entry* e = lookupHandleLocked(handle); 256 | 257 | if (e != NULL) { 258 | // We need to create a new BpBinder if there isn't currently one, OR we 259 | // are unable to acquire a weak reference on this current one. The 260 | // attemptIncWeak() is safe because we know the BpBinder destructor will always 261 | // call expungeHandle(), which acquires the same lock we are holding now. 262 | // We need to do this because there is a race condition between someone 263 | // releasing a reference on this BpBinder, and a new reference on its handle 264 | // arriving from the driver. 265 | IBinder* b = e->binder; 266 | if (b == NULL || !e->refs->attemptIncWeak(this)) { 267 | b = new BpBinder(handle); 268 | result = b; 269 | e->binder = b; 270 | if (b) e->refs = b->getWeakRefs(); 271 | } else { 272 | result = b; 273 | e->refs->decWeak(this); 274 | } 275 | } 276 | 277 | return result; 278 | } 279 | 280 | void ProcessState::expungeHandle(int32_t handle, IBinder* binder) 281 | { 282 | AutoMutex _l(mLock); 283 | 284 | handle_entry* e = lookupHandleLocked(handle); 285 | 286 | // This handle may have already been replaced with a new BpBinder 287 | // (if someone failed the AttemptIncWeak() above); we don't want 288 | // to overwrite it. 289 | if (e && e->binder == binder) e->binder = NULL; 290 | } 291 | 292 | void ProcessState::setArgs(int argc, const char* const argv[]) 293 | { 294 | mArgC = argc; 295 | mArgV = (const char **)argv; 296 | 297 | mArgLen = 0; 298 | for (int i=0; i t = new PoolThread(isMain); 331 | t->run(buf); 332 | } 333 | } 334 | 335 | static int open_driver() 336 | { 337 | if (gSingleProcess) { 338 | return -1; 339 | } 340 | 341 | int fd = open("/dev/binder", O_RDWR); 342 | if (fd >= 0) { 343 | fcntl(fd, F_SETFD, FD_CLOEXEC); 344 | int vers; 345 | #if defined(HAVE_ANDROID_OS) 346 | // 获取Binder版本号 347 | status_t result = ioctl(fd, BINDER_VERSION, &vers); 348 | #else 349 | status_t result = -1; 350 | errno = EPERM; 351 | #endif 352 | if (result == -1) { 353 | LOGE("Binder ioctl to obtain version failed: %s", strerror(errno)); 354 | close(fd); 355 | fd = -1; 356 | } 357 | if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) { 358 | LOGE("Binder driver protocol does not match user space protocol!"); 359 | close(fd); 360 | fd = -1; 361 | } 362 | #if defined(HAVE_ANDROID_OS) 363 | size_t maxThreads = 15; 364 | // 设置最多创建的Binder线程个数 365 | result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads); 366 | if (result == -1) { 367 | LOGE("Binder ioctl to set max threads failed: %s", strerror(errno)); 368 | } 369 | #endif 370 | 371 | } else { 372 | LOGW("Opening '/dev/binder' failed: %s\n", strerror(errno)); 373 | } 374 | return fd; 375 | } 376 | 377 | // 第一次调用ProcessState的静态成员self时,Binder库会为进程创建一个ProcessState对象 378 | // 并且调用函数open来打开设备文件/binder/dev 379 | // 接着调用函数mmap将它映射到进程的地址空间,即请求Binder驱动程序为进程分配内核缓冲区 380 | // 设备文件/dev/binder映射到进程的地址空间后 381 | // 得到的内核缓冲区的用户地址就保存在其成员变量mVMStart中 382 | ProcessState::ProcessState() 383 | : mDriverFD(open_driver()) 384 | , mVMStart(MAP_FAILED) 385 | , mManagesContexts(false) 386 | , mBinderContextCheckFunc(NULL) 387 | , mBinderContextUserData(NULL) 388 | , mThreadPoolStarted(false) 389 | , mThreadPoolSeq(1) 390 | { 391 | if (mDriverFD >= 0) { 392 | // XXX Ideally, there should be a specific define for whether we 393 | // have mmap (or whether we could possibly have the kernel module 394 | // availabla). 395 | #if !defined(HAVE_WIN32_IPC) 396 | // mmap the binder, providing a chunk of virtual address space to receive transactions. 397 | mVMStart = mmap(0, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0); 398 | if (mVMStart == MAP_FAILED) { 399 | // *sigh* 400 | LOGE("Using /dev/binder failed: unable to mmap transaction memory.\n"); 401 | close(mDriverFD); 402 | mDriverFD = -1; 403 | } 404 | #else 405 | mDriverFD = -1; 406 | #endif 407 | } 408 | if (mDriverFD < 0) { 409 | // Need to run without the driver, starting our own thread pool. 410 | } 411 | } 412 | 413 | ProcessState::~ProcessState() 414 | { 415 | } 416 | 417 | }; // namespace android 418 | -------------------------------------------------------------------------------- /kernel/goldfish/drivers/staging/android/binder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google, Inc. 3 | * 4 | * Based on, but no longer compatible with, the original 5 | * OpenBinder.org binder driver interface, which is: 6 | * 7 | * Copyright (c) 2005 Palmsource, Inc. 8 | * 9 | * This software is licensed under the terms of the GNU General Public 10 | * License version 2, as published by the Free Software Foundation, and 11 | * may be copied, distributed, and modified under those terms. 12 | * 13 | * This program is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details. 17 | * 18 | */ 19 | 20 | #ifndef _LINUX_BINDER_H 21 | #define _LINUX_BINDER_H 22 | 23 | #include 24 | 25 | #define B_PACK_CHARS(c1, c2, c3, c4) \ 26 | ((((c1)<<24)) | (((c2)<<16)) | (((c3)<<8)) | (c4)) 27 | #define B_TYPE_LARGE 0x85 28 | 29 | enum { 30 | // 用来描述一个Binder实体对象 31 | // 描述强类型 32 | BINDER_TYPE_BINDER = B_PACK_CHARS('s', 'b', '*', B_TYPE_LARGE), 33 | // 用来描述一个Binder引用对象 34 | // 描述弱类型 35 | BINDER_TYPE_WEAK_BINDER = B_PACK_CHARS('w', 'b', '*', B_TYPE_LARGE), 36 | // 描述强类型 37 | BINDER_TYPE_HANDLE = B_PACK_CHARS('s', 'h', '*', B_TYPE_LARGE), 38 | // 描述弱类型 39 | BINDER_TYPE_WEAK_HANDLE = B_PACK_CHARS('w', 'h', '*', B_TYPE_LARGE), 40 | // 描述一个文件描述符 41 | BINDER_TYPE_FD = B_PACK_CHARS('f', 'd', '*', B_TYPE_LARGE), 42 | }; 43 | 44 | enum { 45 | FLAT_BINDER_FLAG_PRIORITY_MASK = 0xff, 46 | FLAT_BINDER_FLAG_ACCEPTS_FDS = 0x100, 47 | }; 48 | 49 | /* 50 | * This is the flattened representation of a Binder object for transfer 51 | * between processes. The 'offsets' supplied as part of a binder transaction 52 | * contains offsets into the data where these structures occur. The Binder 53 | * driver takes care of re-writing the structure type and data as it moves 54 | * between processes. 55 | */ 56 | // 可以用来描述Binder实体对象,Binder引用对象,文件描述符 57 | // 通过type来区别 58 | struct flat_binder_object { 59 | /* 8 bytes for large_flat_header. */ 60 | unsigned long type; 61 | // 标志值,只有结构体flat_binder_object描述的是一个Binder实体对象时,它才有意义 62 | unsigned long flags; 63 | 64 | /* 8 bytes of data. */ 65 | // 如果描述的是一个Binder实体对象时, 66 | // 那么使用binder来指向该Binder实体对象对应的Service组件内部的一个弱引用对象的地址 67 | // 并且使用cookie来指向该Service组件的地址 68 | // 如果描述的是Binder引用对象时,那么使用handle来描述该Binder引用对象的句柄值 69 | union { 70 | void *binder; /* local object */ 71 | signed long handle; /* remote object */ 72 | }; 73 | 74 | /* extra data associated with local object */ 75 | void *cookie; 76 | }; 77 | 78 | /* 79 | * On 64-bit platforms where user code may run in 32-bits the driver must 80 | * translate the buffer (and local binder) addresses apropriately. 81 | */ 82 | 83 | // 用来描述进程间通信过程中所传输的数据 84 | // 包括输入数据和输出数据 85 | // [write_buffer和read_buffer数据都是一个数组,数组的每一个元素都是由一个通信协议代码及其通信数据组成的 86 | // 协议代码又分两种类型 87 | // 一种是在输入缓冲区write_buffer中使用的,称为命令协议代码 88 | // 另一种是在输出缓冲区read_buffer中使用,又称为返回协议代码] 89 | struct binder_write_read { 90 | // 输入数据,从用户空间传输到Binder驱动程序的数据 91 | signed long write_size; /* bytes to write */ 92 | // 用来描述Binder驱动程序从缓冲区write_buffer中处理了多少个字节的数据 93 | signed long write_consumed; /* bytes consumed by driver */ 94 | // 大小由成员变量write_size来指定,单位是字节 95 | unsigned long write_buffer; 96 | // 输出数据,从驱动返回给用户空间的数据,也是进程间通信的结果数据 97 | signed long read_size; /* bytes to read */ 98 | signed long read_consumed; /* bytes consumed by driver */ 99 | // 指向一个用户空间缓冲区的地址,里面保存的内容即为Binder驱动程序返回给用户空间的进程间通信结果数据 100 | unsigned long read_buffer; 101 | }; 102 | 103 | /* Use with BINDER_VERSION, driver fills in fields. */ 104 | struct binder_version { 105 | /* driver protocol version -- increment with incompatible change */ 106 | signed long protocol_version; 107 | }; 108 | 109 | /* This is the current protocol version. */ 110 | #define BINDER_CURRENT_PROTOCOL_VERSION 7 111 | 112 | #define BINDER_WRITE_READ _IOWR('b', 1, struct binder_write_read) 113 | #define BINDER_SET_IDLE_TIMEOUT _IOW('b', 3, int64_t) 114 | #define BINDER_SET_MAX_THREADS _IOW('b', 5, size_t) 115 | #define BINDER_SET_IDLE_PRIORITY _IOW('b', 6, int) 116 | #define BINDER_SET_CONTEXT_MGR _IOW('b', 7, int) 117 | #define BINDER_THREAD_EXIT _IOW('b', 8, int) 118 | #define BINDER_VERSION _IOWR('b', 9, struct binder_version) 119 | 120 | /* 121 | * NOTE: Two special error codes you should check for when calling 122 | * in to the driver are: 123 | * 124 | * EINTR -- The operation has been interupted. This should be 125 | * handled by retrying the ioctl() until a different error code 126 | * is returned. 127 | * 128 | * ECONNREFUSED -- The driver is no longer accepting operations 129 | * from your process. That is, the process is being destroyed. 130 | * You should handle this by exiting from your process. Note 131 | * that once this error code is returned, all further calls to 132 | * the driver from any thread will return this same code. 133 | */ 134 | 135 | enum transaction_flags { 136 | // 是否是异步通信 137 | TF_ONE_WAY = 0x01, /* this is a one-way call: async, no return */ 138 | TF_ROOT_OBJECT = 0x04, /* contents are the component's root object */ 139 | // 成员变量data所描述的数据缓冲区的内容是否是一个4字节的状态码 140 | TF_STATUS_CODE = 0x08, /* contents are a 32-bit status code */ 141 | // 源进程是否允许目标进程返回的结果数据中包含文件描述符 142 | TF_ACCEPT_FDS = 0x10, /* allow replies with file descriptors */ 143 | }; 144 | 145 | // 用来描述进程间通信过程中所传输的数据 146 | struct binder_transaction_data { 147 | /* The first two are only used for bcTRANSACTION and brTRANSACTION, 148 | * identifying the target and contents of the transaction. 149 | */ 150 | // 用来描述一个目标Binder实体对象或者目标Binder引用对象 151 | // 如果是实体对象,那么成员变量ptr就指向该实体对象对应的Service组件内部的弱引用计数对象的地址 152 | // 如果是引用对象,那么成员变量handle就指向该Binder引用对象的句柄值 153 | union { 154 | size_t handle; /* target descriptor of command transaction */ 155 | void *ptr; /* target descriptor of return transaction */ 156 | } target; 157 | // 由应用程序进程指定的额外参数 158 | // 当Binder驱动使用返回命令协议BR_TRANSACTION向一个Server进程发出一个进程间通信请求时 159 | // 这个变量才有意义,它指向的是目标Service组件的地址 160 | void *cookie; /* target object cookie */ 161 | // 由执行进程间同学你的两个进程互相约定好的一个代码 162 | // 驱动不关心含义 163 | unsigned int code; /* transaction command */ 164 | 165 | /* General information about the transaction. */ 166 | unsigned int flags; 167 | // 发起进程间通信的请求进程的pid和uid 168 | pid_t sender_pid; 169 | uid_t sender_euid; 170 | // 用来描述一个通信数据缓冲区以及一个偏移数组的大小 171 | size_t data_size; /* number of bytes of data */ 172 | size_t offsets_size; /* number of bytes of offsets */ 173 | 174 | /* If this transaction is inline, the data immediately 175 | * follows here; otherwise, it ends with a pointer to 176 | * the data buffer. 177 | */ 178 | // 一个联合体 179 | // 指向一个通信数据缓冲区 180 | // 当通信数据较小时,使用联合体中的静态分配的数组buf来传输数据 181 | // 当通信数据较大时,使用一块动态分配的缓冲区来传输数据 182 | // 这块数据缓冲区通过一个包含两个指针的结构体来描述 183 | // 结构体ptr的成员变量buffer指向一个数据缓冲区,用来保存通信数据,大小根据变量data_size来指定 184 | // 当数据缓冲区中有Binder对象时,紧跟着这个数据缓冲区后面就会有一个偏移数组offsets 185 | // 用来描述缓冲区中每一个Binder对象的位置 186 | // 有了偏移数组,驱动可以正确地维护其内部的Binder实体对象和Binder引用对象的引用计数 187 | union { 188 | struct { 189 | /* transaction data */ 190 | const void *buffer; 191 | /* offsets from buffer to flat_binder_object structs */ 192 | const void *offsets; 193 | } ptr; 194 | uint8_t buf[8]; 195 | } data; 196 | }; 197 | 198 | // 用来描述一个Binder实体对象或者一个Service组件的死亡通知 199 | // 如果用来描述Binder实体对象,ptr、cookie含义等同于前面所介绍的结构体binder_node的ptr和cookie 200 | // 如果用来描述死亡接受通知时,ptr指向一个Binder引用对象的句柄值,而成员变量指向的是一个用来接受死亡通知的对象地址 201 | struct binder_ptr_cookie { 202 | void *ptr; 203 | void *cookie; 204 | }; 205 | 206 | struct binder_pri_desc { 207 | int priority; 208 | int desc; 209 | }; 210 | 211 | struct binder_pri_ptr_cookie { 212 | int priority; 213 | void *ptr; 214 | void *cookie; 215 | }; 216 | 217 | enum BinderDriverReturnProtocol { 218 | // 驱动处理应用数据发出的请求中时,如果发生了异常,就会返回这个代码通知应用进程 219 | BR_ERROR = _IOR('r', 0, int), 220 | /* 221 | * int: error code 222 | */ 223 | 224 | // 驱动处理请求成功,返回代码通知应用进程 225 | BR_OK = _IO('r', 1), 226 | /* No parameters! */ 227 | 228 | // 当Client进程向Server进程发出进程间通信请求时,Binder驱动使用代码来 229 | // 通知Server进程发出进程间通信的请求 230 | BR_TRANSACTION = _IOR('r', 2, struct binder_transaction_data), 231 | // 当Server进程处理完成该进程间通信请求之后,Binder驱动就会使用这个代码将 232 | // 进程间通信请求结果数据返回给Client进程 233 | BR_REPLY = _IOR('r', 3, struct binder_transaction_data), 234 | /* 235 | * binder_transaction_data: the received command. 236 | */ 237 | 238 | BR_ACQUIRE_RESULT = _IOR('r', 4, int), 239 | /* 240 | * not currently supported 241 | * int: 0 if the last bcATTEMPT_ACQUIRE was not successful. 242 | * Else the remote object has acquired a primary reference. 243 | */ 244 | 245 | BR_DEAD_REPLY = _IO('r', 5), 246 | /* 247 | * The target of the last transaction (either a bcTRANSACTION or 248 | * a bcATTEMPT_ACQUIRE) is no longer with us. No parameters. 249 | */ 250 | 251 | // 返回该代码给应用进程,告知该协议代码已经被接受,正在发给目标进程或者目标线程处理 252 | BR_TRANSACTION_COMPLETE = _IO('r', 6), 253 | /* 254 | * No parameters... always refers to the last transaction requested 255 | * (including replies). Note that this will be sent even for 256 | * asynchronous transactions. 257 | */ 258 | 259 | // 用来增加和减少一个Service组件的强引用和弱引用计数 260 | BR_INCREFS = _IOR('r', 7, struct binder_ptr_cookie), 261 | BR_ACQUIRE = _IOR('r', 8, struct binder_ptr_cookie), 262 | BR_RELEASE = _IOR('r', 9, struct binder_ptr_cookie), 263 | BR_DECREFS = _IOR('r', 10, struct binder_ptr_cookie), 264 | /* 265 | * void *: ptr to binder 266 | * void *: cookie for binder 267 | */ 268 | 269 | BR_ATTEMPT_ACQUIRE = _IOR('r', 11, struct binder_pri_ptr_cookie), 270 | /* 271 | * not currently supported 272 | * int: priority 273 | * void *: ptr to binder 274 | * void *: cookie for binder 275 | */ 276 | 277 | BR_NOOP = _IO('r', 12), 278 | /* 279 | * No parameters. Do nothing and examine the next command. It exists 280 | * primarily so that we can replace it with a BR_SPAWN_LOOPER command. 281 | */ 282 | 283 | // 驱动发现没有足够的空闲Binder线程来处理进程间通信请求 284 | // 发送这个代码来通知该进程增加一个新的线程到Binder线程池中 285 | BR_SPAWN_LOOPER = _IO('r', 13), 286 | /* 287 | * No parameters. The driver has determined that a process has no 288 | * threads waiting to service incomming transactions. When a process 289 | * receives this command, it must spawn a new service thread and 290 | * register it via bcENTER_LOOPER. 291 | */ 292 | 293 | BR_FINISHED = _IO('r', 14), 294 | /* 295 | * not currently supported 296 | * stop threadpool thread 297 | */ 298 | 299 | // 指向一个接受Service组件死亡通知的对象的地址 300 | // 当Bindr驱动检测到一个Service组件死亡事件时,使用这个代码来通知相应的Client进程 301 | BR_DEAD_BINDER = _IOR('r', 15, void *), 302 | /* 303 | * void *: cookie 304 | */ 305 | 306 | // 当Client通知驱动注销死亡通知时,驱动使用这个代码表示注销操作已经完成 307 | BR_CLEAR_DEATH_NOTIFICATION_DONE = _IOR('r', 16, void *), 308 | /* 309 | * void *: cookie 310 | */ 311 | 312 | // 当驱动处理一个进程发出的BC_TRANSACTION命令协议时 313 | // 如果出现了异常,它会使用这个代码来通知源进程 314 | BR_FAILED_REPLY = _IO('r', 17), 315 | /* 316 | * The the last transaction (either a bcTRANSACTION or 317 | * a bcATTEMPT_ACQUIRE) failed (e.g. out of memory). No parameters. 318 | */ 319 | }; 320 | 321 | enum BinderDriverCommandProtocol { 322 | // 当一个进程请求另外一个进程执行某一个操作时,源进程就使用命令这个协议来请求Binder驱动程序 323 | // 将通信数据传递到目标进程中 324 | BC_TRANSACTION = _IOW('c', 0, struct binder_transaction_data), 325 | // 当目标进程处理完成源代码所请求的操作之后,就使用命令这个协议来请求驱动将结果传递给源进程 326 | BC_REPLY = _IOW('c', 1, struct binder_transaction_data), 327 | /* 328 | * binder_transaction_data: the sent command. 329 | */ 330 | 331 | BC_ACQUIRE_RESULT = _IOW('c', 2, int), 332 | /* 333 | * not currently supported 334 | * int: 0 if the last BR_ATTEMPT_ACQUIRE was not successful. 335 | * Else you have acquired a primary reference on the object. 336 | */ 337 | // 指向了在Binder驱动程序内部所分配的一块内核缓冲区 338 | // Binder驱动使用这个缓冲区将源进程的通信数据传递到目标进程 339 | // 当目标进程处理完成源进程的通信请求后,会使用这个协议来通知驱动释放这个内核缓冲区 340 | BC_FREE_BUFFER = _IOW('c', 3, int), 341 | /* 342 | * void *: ptr to transaction data received on a read 343 | */ 344 | // 驱动第一次增加一个Binder实体对象的强引用计数或者弱引用计数时 345 | // 就会使用这个协议来请求对应的Server进程增加对应的Service组件的强引用弱引用计数 346 | BC_INCREFS = _IOW('c', 4, int), 347 | BC_ACQUIRE = _IOW('c', 5, int), 348 | BC_RELEASE = _IOW('c', 6, int), 349 | BC_DECREFS = _IOW('c', 7, int), 350 | /* 351 | * int: descriptor 352 | */ 353 | // 当Server进程处理完成这两个请求之后,就会分别使用命令协议代码将结果返回给驱动 354 | BC_INCREFS_DONE = _IOW('c', 8, struct binder_ptr_cookie), 355 | BC_ACQUIRE_DONE = _IOW('c', 9, struct binder_ptr_cookie), 356 | /* 357 | * void *: ptr to binder 358 | * void *: cookie for binder 359 | */ 360 | 361 | BC_ATTEMPT_ACQUIRE = _IOW('c', 10, struct binder_pri_desc), 362 | /* 363 | * not currently supported 364 | * int: priority 365 | * int: descriptor 366 | */ 367 | // 当Binder驱动程序主动请求进程注册一个新的线程到它的Binder线程池中来 368 | // 处理进程间通信请求之后,新创建的线程就会使用这个命令协议代码 369 | // 通知驱动已经准备就绪了 370 | BC_REGISTER_LOOPER = _IO('c', 11), 371 | /* 372 | * No parameters. 373 | * Register a spawned looper thread with the device. 374 | */ 375 | // 当一个线程将自己注册到Binder驱动程序之后,它接着就会使用这个命令协议代码 376 | // 通知驱动,当前线程已经准备就绪处理进程间的通信请求了 377 | BC_ENTER_LOOPER = _IO('c', 12), 378 | // 当线程要退出时,使用这个协议代码从驱动中注销,不会再接受到进程间的通信请求了 379 | BC_EXIT_LOOPER = _IO('c', 13), 380 | /* 381 | * No parameters. 382 | * These two commands are sent as an application-level thread 383 | * enters and exits the binder loop, respectively. They are 384 | * used so the binder can have an accurate count of the number 385 | * of looping threads it has available. 386 | */ 387 | // 如果一个进程希望获得它所引用的Service组件的死亡接受通知,那么它就使用这个敏玲向 388 | // 驱动注册一个死亡接受通知 389 | BC_REQUEST_DEATH_NOTIFICATION = _IOW('c', 14, struct binder_ptr_cookie), 390 | /* 391 | * void *: ptr to binder 392 | * void *: cookie 393 | */ 394 | // 如果进程注销一个死亡通知,使用这个协议代码发送给驱动来进行请求 395 | BC_CLEAR_DEATH_NOTIFICATION = _IOW('c', 15, struct binder_ptr_cookie), 396 | /* 397 | * void *: ptr to binder 398 | * void *: cookie 399 | */ 400 | // 指向了死亡接受通知结构体binder_ref_death 401 | // 当一个进程获得一个Service组件的死亡通知时,它就会使用这个命令协议通知驱动 402 | // 当前已经处理完成该Service组件的死亡通知 403 | BC_DEAD_BINDER_DONE = _IOW('c', 16, void *), 404 | /* 405 | * void *: cookie 406 | */ 407 | }; 408 | 409 | #endif /* _LINUX_BINDER_H */ 410 | 411 | -------------------------------------------------------------------------------- /out/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/os/IFregService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is auto-generated. DO NOT MODIFY. 3 | * Original file: frameworks/base/core/java/android/os/IFregService.aidl 4 | */ 5 | package android.os; 6 | public interface IFregService extends android.os.IInterface 7 | { 8 | /** Local-side IPC implementation stub class. */ 9 | public static abstract class Stub extends android.os.Binder implements android.os.IFregService 10 | { 11 | private static final java.lang.String DESCRIPTOR = "android.os.IFregService"; 12 | /** Construct the stub at attach it to the interface. */ 13 | public Stub() 14 | { 15 | this.attachInterface(this, DESCRIPTOR); 16 | } 17 | /** 18 | * Cast an IBinder object into an android.os.IFregService interface, 19 | * generating a proxy if needed. 20 | */ 21 | public static android.os.IFregService asInterface(android.os.IBinder obj) 22 | { 23 | if ((obj==null)) { 24 | return null; 25 | } 26 | android.os.IInterface iin = (android.os.IInterface)obj.queryLocalInterface(DESCRIPTOR); 27 | if (((iin!=null)&&(iin instanceof android.os.IFregService))) { 28 | return ((android.os.IFregService)iin); 29 | } 30 | return new android.os.IFregService.Stub.Proxy(obj); 31 | } 32 | public android.os.IBinder asBinder() 33 | { 34 | return this; 35 | } 36 | @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException 37 | { 38 | switch (code) 39 | { 40 | case INTERFACE_TRANSACTION: 41 | { 42 | reply.writeString(DESCRIPTOR); 43 | return true; 44 | } 45 | case TRANSACTION_setVal: 46 | { 47 | data.enforceInterface(DESCRIPTOR); 48 | int _arg0; 49 | _arg0 = data.readInt(); 50 | this.setVal(_arg0); 51 | reply.writeNoException(); 52 | return true; 53 | } 54 | case TRANSACTION_getVal: 55 | { 56 | data.enforceInterface(DESCRIPTOR); 57 | int _result = this.getVal(); 58 | reply.writeNoException(); 59 | reply.writeInt(_result); 60 | return true; 61 | } 62 | } 63 | return super.onTransact(code, data, reply, flags); 64 | } 65 | private static class Proxy implements android.os.IFregService 66 | { 67 | private android.os.IBinder mRemote; 68 | Proxy(android.os.IBinder remote) 69 | { 70 | mRemote = remote; 71 | } 72 | public android.os.IBinder asBinder() 73 | { 74 | return mRemote; 75 | } 76 | public java.lang.String getInterfaceDescriptor() 77 | { 78 | return DESCRIPTOR; 79 | } 80 | public void setVal(int val) throws android.os.RemoteException 81 | { 82 | android.os.Parcel _data = android.os.Parcel.obtain(); 83 | android.os.Parcel _reply = android.os.Parcel.obtain(); 84 | try { 85 | _data.writeInterfaceToken(DESCRIPTOR); 86 | _data.writeInt(val); 87 | mRemote.transact(Stub.TRANSACTION_setVal, _data, _reply, 0); 88 | _reply.readException(); 89 | } 90 | finally { 91 | _reply.recycle(); 92 | _data.recycle(); 93 | } 94 | } 95 | public int getVal() throws android.os.RemoteException 96 | { 97 | android.os.Parcel _data = android.os.Parcel.obtain(); 98 | android.os.Parcel _reply = android.os.Parcel.obtain(); 99 | int _result; 100 | try { 101 | _data.writeInterfaceToken(DESCRIPTOR); 102 | mRemote.transact(Stub.TRANSACTION_getVal, _data, _reply, 0); 103 | _reply.readException(); 104 | _result = _reply.readInt(); 105 | } 106 | finally { 107 | _reply.recycle(); 108 | _data.recycle(); 109 | } 110 | return _result; 111 | } 112 | } 113 | static final int TRANSACTION_setVal = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0); 114 | static final int TRANSACTION_getVal = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1); 115 | } 116 | public void setVal(int val) throws android.os.RemoteException; 117 | public int getVal() throws android.os.RemoteException; 118 | } 119 | -------------------------------------------------------------------------------- /system/core/rootdir/init.rc: -------------------------------------------------------------------------------- 1 | on early-init 2 | start ueventd 3 | 4 | on init 5 | 6 | sysclktz 0 7 | 8 | loglevel 3 9 | 10 | # setup the global environment 11 | export PATH /sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin 12 | export LD_LIBRARY_PATH /vendor/lib:/system/lib 13 | export ANDROID_BOOTLOGO 1 14 | export ANDROID_ROOT /system 15 | export ANDROID_ASSETS /system/app 16 | export ANDROID_DATA /data 17 | export EXTERNAL_STORAGE /mnt/sdcard 18 | export ASEC_MOUNTPOINT /mnt/asec 19 | export LOOP_MOUNTPOINT /mnt/obb 20 | export BOOTCLASSPATH /system/framework/core.jar:/system/framework/bouncycastle.jar:/system/framework/ext.jar:/system/framework/framework.jar:/system/framework/android.policy.jar:/system/framework/services.jar:/system/framework/core-junit.jar 21 | 22 | # Backward compatibility 23 | symlink /system/etc /etc 24 | symlink /sys/kernel/debug /d 25 | 26 | # Right now vendor lives on the same filesystem as system, 27 | # but someday that may change. 28 | symlink /system/vendor /vendor 29 | 30 | # create mountpoints 31 | mkdir /mnt 0775 root system 32 | mkdir /mnt/sdcard 0000 system system 33 | 34 | # Create cgroup mount point for cpu accounting 35 | mkdir /acct 36 | mount cgroup none /acct cpuacct 37 | mkdir /acct/uid 38 | 39 | # Backwards Compat - XXX: Going away in G* 40 | symlink /mnt/sdcard /sdcard 41 | 42 | mkdir /system 43 | mkdir /data 0771 system system 44 | mkdir /cache 0770 system cache 45 | mkdir /config 0500 root root 46 | 47 | # Directory for putting things only root should see. 48 | mkdir /mnt/secure 0700 root root 49 | 50 | # Directory for staging bindmounts 51 | mkdir /mnt/secure/staging 0700 root root 52 | 53 | # Directory-target for where the secure container 54 | # imagefile directory will be bind-mounted 55 | mkdir /mnt/secure/asec 0700 root root 56 | 57 | # Secure container public mount points. 58 | mkdir /mnt/asec 0700 root system 59 | mount tmpfs tmpfs /mnt/asec mode=0755,gid=1000 60 | 61 | # Filesystem image public mount points. 62 | mkdir /mnt/obb 0700 root system 63 | mount tmpfs tmpfs /mnt/obb mode=0755,gid=1000 64 | 65 | write /proc/sys/kernel/panic_on_oops 1 66 | write /proc/sys/kernel/hung_task_timeout_secs 0 67 | write /proc/cpu/alignment 4 68 | write /proc/sys/kernel/sched_latency_ns 10000000 69 | write /proc/sys/kernel/sched_wakeup_granularity_ns 2000000 70 | write /proc/sys/kernel/sched_compat_yield 1 71 | write /proc/sys/kernel/sched_child_runs_first 0 72 | 73 | # Create cgroup mount points for process groups 74 | mkdir /dev/cpuctl 75 | mount cgroup none /dev/cpuctl cpu 76 | chown system system /dev/cpuctl 77 | chown system system /dev/cpuctl/tasks 78 | chmod 0777 /dev/cpuctl/tasks 79 | write /dev/cpuctl/cpu.shares 1024 80 | 81 | mkdir /dev/cpuctl/fg_boost 82 | chown system system /dev/cpuctl/fg_boost/tasks 83 | chmod 0777 /dev/cpuctl/fg_boost/tasks 84 | write /dev/cpuctl/fg_boost/cpu.shares 1024 85 | 86 | mkdir /dev/cpuctl/bg_non_interactive 87 | chown system system /dev/cpuctl/bg_non_interactive/tasks 88 | chmod 0777 /dev/cpuctl/bg_non_interactive/tasks 89 | # 5.0 % 90 | write /dev/cpuctl/bg_non_interactive/cpu.shares 52 91 | 92 | on fs 93 | # mount mtd partitions 94 | # Mount /system rw first to give the filesystem a chance to save a checkpoint 95 | mount yaffs2 mtd@system /system 96 | mount yaffs2 mtd@system /system ro remount 97 | mount yaffs2 mtd@userdata /data nosuid nodev 98 | mount yaffs2 mtd@cache /cache nosuid nodev 99 | 100 | on post-fs 101 | # once everything is setup, no need to modify / 102 | mount rootfs rootfs / ro remount 103 | 104 | # We chown/chmod /data again so because mount is run as root + defaults 105 | chown system system /data 106 | chmod 0771 /data 107 | 108 | # Create dump dir and collect dumps. 109 | # Do this before we mount cache so eventually we can use cache for 110 | # storing dumps on platforms which do not have a dedicated dump partition. 111 | 112 | mkdir /data/dontpanic 113 | chown root log /data/dontpanic 114 | chmod 0750 /data/dontpanic 115 | 116 | # Collect apanic data, free resources and re-arm trigger 117 | copy /proc/apanic_console /data/dontpanic/apanic_console 118 | chown root log /data/dontpanic/apanic_console 119 | chmod 0640 /data/dontpanic/apanic_console 120 | 121 | copy /proc/apanic_threads /data/dontpanic/apanic_threads 122 | chown root log /data/dontpanic/apanic_threads 123 | chmod 0640 /data/dontpanic/apanic_threads 124 | 125 | write /proc/apanic_console 1 126 | 127 | # Same reason as /data above 128 | chown system cache /cache 129 | chmod 0770 /cache 130 | 131 | # This may have been created by the recovery system with odd permissions 132 | chown system cache /cache/recovery 133 | chmod 0770 /cache/recovery 134 | 135 | #change permissions on vmallocinfo so we can grab it from bugreports 136 | chown root log /proc/vmallocinfo 137 | chmod 0440 /proc/vmallocinfo 138 | 139 | #change permissions on kmsg & sysrq-trigger so bugreports can grab kthread stacks 140 | chown root system /proc/kmsg 141 | chmod 0440 /proc/kmsg 142 | chown root system /proc/sysrq-trigger 143 | chmod 0220 /proc/sysrq-trigger 144 | 145 | # create basic filesystem structure 146 | mkdir /data/misc 01771 system misc 147 | mkdir /data/misc/bluetoothd 0770 bluetooth bluetooth 148 | mkdir /data/misc/bluetooth 0770 system system 149 | mkdir /data/misc/keystore 0700 keystore keystore 150 | mkdir /data/misc/vpn 0770 system system 151 | mkdir /data/misc/systemkeys 0700 system system 152 | mkdir /data/misc/vpn/profiles 0770 system system 153 | # give system access to wpa_supplicant.conf for backup and restore 154 | mkdir /data/misc/wifi 0770 wifi wifi 155 | chmod 0770 /data/misc/wifi 156 | chmod 0660 /data/misc/wifi/wpa_supplicant.conf 157 | mkdir /data/local 0771 shell shell 158 | mkdir /data/local/tmp 0771 shell shell 159 | mkdir /data/data 0771 system system 160 | mkdir /data/app-private 0771 system system 161 | mkdir /data/app 0771 system system 162 | mkdir /data/property 0700 root root 163 | 164 | # create dalvik-cache and double-check the perms 165 | mkdir /data/dalvik-cache 0771 system system 166 | chown system system /data/dalvik-cache 167 | chmod 0771 /data/dalvik-cache 168 | 169 | # create the lost+found directories, so as to enforce our permissions 170 | mkdir /data/lost+found 0770 171 | mkdir /cache/lost+found 0770 172 | 173 | # double check the perms, in case lost+found already exists, and set owner 174 | chown root root /data/lost+found 175 | chmod 0770 /data/lost+found 176 | chown root root /cache/lost+found 177 | chmod 0770 /cache/lost+found 178 | 179 | # create data/drm directory 180 | mkdir /data/drm 0774 drm drm 181 | chown drm drm /data/drm 182 | chmod 0774 /data/drm 183 | 184 | on boot 185 | # basic network init 186 | ifup lo 187 | hostname localhost 188 | domainname localdomain 189 | 190 | # set RLIMIT_NICE to allow priorities from 19 to -20 191 | setrlimit 13 40 40 192 | 193 | # Define the oom_adj values for the classes of processes that can be 194 | # killed by the kernel. These are used in ActivityManagerService. 195 | setprop ro.FOREGROUND_APP_ADJ 0 196 | setprop ro.VISIBLE_APP_ADJ 1 197 | setprop ro.PERCEPTIBLE_APP_ADJ 2 198 | setprop ro.HEAVY_WEIGHT_APP_ADJ 3 199 | setprop ro.SECONDARY_SERVER_ADJ 4 200 | setprop ro.BACKUP_APP_ADJ 5 201 | setprop ro.HOME_APP_ADJ 6 202 | setprop ro.HIDDEN_APP_MIN_ADJ 7 203 | setprop ro.EMPTY_APP_ADJ 15 204 | 205 | # Define the memory thresholds at which the above process classes will 206 | # be killed. These numbers are in pages (4k). 207 | setprop ro.FOREGROUND_APP_MEM 2048 208 | setprop ro.VISIBLE_APP_MEM 3072 209 | setprop ro.PERCEPTIBLE_APP_MEM 4096 210 | setprop ro.HEAVY_WEIGHT_APP_MEM 4096 211 | setprop ro.SECONDARY_SERVER_MEM 6144 212 | setprop ro.BACKUP_APP_MEM 6144 213 | setprop ro.HOME_APP_MEM 6144 214 | setprop ro.HIDDEN_APP_MEM 7168 215 | setprop ro.EMPTY_APP_MEM 8192 216 | 217 | # Write value must be consistent with the above properties. 218 | # Note that the driver only supports 6 slots, so we have combined some of 219 | # the classes into the same memory level; the associated processes of higher 220 | # classes will still be killed first. 221 | write /sys/module/lowmemorykiller/parameters/adj 0,1,2,4,7,15 222 | 223 | write /proc/sys/vm/overcommit_memory 1 224 | write /proc/sys/vm/min_free_order_shift 4 225 | write /sys/module/lowmemorykiller/parameters/minfree 2048,3072,4096,6144,7168,8192 226 | 227 | # Set init its forked children's oom_adj. 228 | write /proc/1/oom_adj -16 229 | 230 | # Tweak background writeout 231 | write /proc/sys/vm/dirty_expire_centisecs 200 232 | write /proc/sys/vm/dirty_background_ratio 5 233 | 234 | # Permissions for System Server and daemons. 235 | chown radio system /sys/android_power/state 236 | chown radio system /sys/android_power/request_state 237 | chown radio system /sys/android_power/acquire_full_wake_lock 238 | chown radio system /sys/android_power/acquire_partial_wake_lock 239 | chown radio system /sys/android_power/release_wake_lock 240 | chown radio system /sys/power/state 241 | chown radio system /sys/power/wake_lock 242 | chown radio system /sys/power/wake_unlock 243 | chmod 0660 /sys/power/state 244 | chmod 0660 /sys/power/wake_lock 245 | chmod 0660 /sys/power/wake_unlock 246 | chown system system /sys/class/timed_output/vibrator/enable 247 | chown system system /sys/class/leds/keyboard-backlight/brightness 248 | chown system system /sys/class/leds/lcd-backlight/brightness 249 | chown system system /sys/class/leds/button-backlight/brightness 250 | chown system system /sys/class/leds/jogball-backlight/brightness 251 | chown system system /sys/class/leds/red/brightness 252 | chown system system /sys/class/leds/green/brightness 253 | chown system system /sys/class/leds/blue/brightness 254 | chown system system /sys/class/leds/red/device/grpfreq 255 | chown system system /sys/class/leds/red/device/grppwm 256 | chown system system /sys/class/leds/red/device/blink 257 | chown system system /sys/class/leds/red/brightness 258 | chown system system /sys/class/leds/green/brightness 259 | chown system system /sys/class/leds/blue/brightness 260 | chown system system /sys/class/leds/red/device/grpfreq 261 | chown system system /sys/class/leds/red/device/grppwm 262 | chown system system /sys/class/leds/red/device/blink 263 | chown system system /sys/class/timed_output/vibrator/enable 264 | chown system system /sys/module/sco/parameters/disable_esco 265 | chown system system /sys/kernel/ipv4/tcp_wmem_min 266 | chown system system /sys/kernel/ipv4/tcp_wmem_def 267 | chown system system /sys/kernel/ipv4/tcp_wmem_max 268 | chown system system /sys/kernel/ipv4/tcp_rmem_min 269 | chown system system /sys/kernel/ipv4/tcp_rmem_def 270 | chown system system /sys/kernel/ipv4/tcp_rmem_max 271 | chown root radio /proc/cmdline 272 | 273 | # Define TCP buffer sizes for various networks 274 | # ReadMin, ReadInitial, ReadMax, WriteMin, WriteInitial, WriteMax, 275 | setprop net.tcp.buffersize.default 4096,87380,110208,4096,16384,110208 276 | setprop net.tcp.buffersize.wifi 4095,87380,110208,4096,16384,110208 277 | setprop net.tcp.buffersize.umts 4094,87380,110208,4096,16384,110208 278 | setprop net.tcp.buffersize.edge 4093,26280,35040,4096,16384,35040 279 | setprop net.tcp.buffersize.gprs 4092,8760,11680,4096,8760,11680 280 | 281 | class_start default 282 | 283 | ## Daemon processes to be run by init. 284 | ## 285 | service ueventd /sbin/ueventd 286 | critical 287 | 288 | service console /system/bin/sh 289 | console 290 | disabled 291 | user shell 292 | group log 293 | 294 | on property:ro.secure=0 295 | start console 296 | 297 | # adbd is controlled by the persist.service.adb.enable system property 298 | service adbd /sbin/adbd 299 | disabled 300 | 301 | # adbd on at boot in emulator 302 | on property:ro.kernel.qemu=1 303 | start adbd 304 | 305 | on property:persist.service.adb.enable=1 306 | start adbd 307 | 308 | on property:persist.service.adb.enable=0 309 | stop adbd 310 | 311 | service servicemanager /system/bin/servicemanager 312 | user system 313 | critical 314 | onrestart restart zygote 315 | onrestart restart media 316 | 317 | service vold /system/bin/vold 318 | socket vold stream 0660 root mount 319 | ioprio be 2 320 | 321 | service netd /system/bin/netd 322 | socket netd stream 0660 root system 323 | socket dnsproxyd stream 0660 root inet 324 | 325 | service debuggerd /system/bin/debuggerd 326 | 327 | service ril-daemon /system/bin/rild 328 | socket rild stream 660 root radio 329 | socket rild-debug stream 660 radio system 330 | user root 331 | group radio cache inet misc audio sdcard_rw 332 | 333 | service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server 334 | socket zygote stream 666 335 | onrestart write /sys/android_power/request_state wake 336 | onrestart write /sys/power/state on 337 | onrestart restart media 338 | onrestart restart netd 339 | 340 | service drm /system/bin/drmserver 341 | user drm 342 | group system root inet 343 | 344 | service drmio /system/bin/drmioserver 345 | user drmio 346 | 347 | service media /system/bin/mediaserver 348 | user media 349 | group system audio camera graphics inet net_bt net_bt_admin net_raw 350 | ioprio rt 4 351 | 352 | service bootanim /system/bin/bootanimation 353 | user graphics 354 | group graphics 355 | disabled 356 | oneshot 357 | 358 | service dbus /system/bin/dbus-daemon --system --nofork 359 | socket dbus stream 660 bluetooth bluetooth 360 | user bluetooth 361 | group bluetooth net_bt_admin 362 | 363 | service bluetoothd /system/bin/bluetoothd -n 364 | socket bluetooth stream 660 bluetooth bluetooth 365 | socket dbus_bluetooth stream 660 bluetooth bluetooth 366 | # init.rc does not yet support applying capabilities, so run as root and 367 | # let bluetoothd drop uid to bluetooth with the right linux capabilities 368 | group bluetooth net_bt_admin misc 369 | disabled 370 | 371 | service hfag /system/bin/sdptool add --channel=10 HFAG 372 | user bluetooth 373 | group bluetooth net_bt_admin 374 | disabled 375 | oneshot 376 | 377 | service hsag /system/bin/sdptool add --channel=11 HSAG 378 | user bluetooth 379 | group bluetooth net_bt_admin 380 | disabled 381 | oneshot 382 | 383 | service opush /system/bin/sdptool add --channel=12 OPUSH 384 | user bluetooth 385 | group bluetooth net_bt_admin 386 | disabled 387 | oneshot 388 | 389 | service pbap /system/bin/sdptool add --channel=19 PBAP 390 | user bluetooth 391 | group bluetooth net_bt_admin 392 | disabled 393 | oneshot 394 | 395 | service installd /system/bin/installd 396 | socket installd stream 600 system system 397 | 398 | service flash_recovery /system/etc/install-recovery.sh 399 | oneshot 400 | 401 | service racoon /system/bin/racoon 402 | socket racoon stream 600 system system 403 | # racoon will setuid to vpn after getting necessary resources. 404 | group net_admin 405 | disabled 406 | oneshot 407 | 408 | service mtpd /system/bin/mtpd 409 | socket mtpd stream 600 system system 410 | user vpn 411 | group vpn net_admin net_raw 412 | disabled 413 | oneshot 414 | 415 | service keystore /system/bin/keystore /data/misc/keystore 416 | user keystore 417 | group keystore 418 | socket keystore stream 666 419 | 420 | service dumpstate /system/bin/dumpstate -s 421 | socket dumpstate stream 0660 shell log 422 | disabled 423 | oneshot 424 | --------------------------------------------------------------------------------