Android Binder 之 ServiceManager (基于android 12.0/S)
Binder 原理整理:
因為Linux中的進程的用戶空間是不共享的,內核空間是共享的,所以IPC通信是兩個用戶空間(APP 進程)通過共享的內核空間(Binder驅動)進行數據交互。
Binder 整體框架:
?Binder 通信框架:
ServiceManager :
ServiceManager 可執行文件的生成:
ServiceManager 在android系統中是一個可執行文件,位于/system/bin/servicemanager下面
?Servicemanager 是在init.rc中啟動的
在android 10.0.0.R47 及以前 servicemanager是由以下目錄結構編譯生成的,
?在android 10.0.0.R47 及以前 控制編譯的相關bp文件:
在android 11.0.0_r21后面原先的service_manager.c變成了ServiceManager.cpp,binder.c變成了main.cpp,同時添加了Access.cpp和Access.h,bctest 變成了 test_sm。
Android 11.0.0_r21 以后的bp如圖,先是將ServiceManager.cpp和Access.cpp一起生成了servicemanager_defaults,然后通過servicemanager_defaults編譯生成可運行的servicemanager。
?
再簡單看下目前android 12中的代碼目錄結構和 android 13的代碼結構:
?
Android T(13.0)中添加了servicemanager.microdroid.rc 和servicemanager.recovery.rc 兩個rc文件。
ServiceManager的代碼分析:
總入口:
Android S 中將android 10.0.0.R47 及以前 在service_manager.c中的 main 方法提取到了main.cpp中。main.cpp中除了main 方法外還額外有ClientCallbackCallback和BinderCallback兩個callback.
int main(int argc, char** argv) { if (argc > 2) {LOG(FATAL) << "usage: " << argv[0] << " [binder driver]";}const char* driver = argc == 2 ? argv[1] : "/dev/binder";//第二個參數可以缺省sp<ProcessState> ps = ProcessState::initWithDriver(driver);//打開binder驅動ps->setThreadPoolMaxThreadCount(0);ps->setCallRestriction(ProcessState::CallRestriction::FATAL_IF_NOT_ONEWAY);// 實例化ServiceManagersp<ServiceManager> manager = sp<ServiceManager>::make(std::make_unique<Access>());// 將自身注冊到ServiceManager當中if (!manager->addService("manager", manager, false /*allowIsolated*/, IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT).isOk()) {LOG(ERROR) << "Could not self register servicemanager";}// 將ServiceManager設置給IPCThreadState的全局變量IPCThreadState::self()->setTheContextObject(manager);ps->becomeContextManager();//注冊成為binder服務的大管家// 準備Loopersp<Looper> looper = Looper::prepare(false /*allowNonCallbacks*/);//給Looper設置callback BinderCallback::setupTo(looper);ClientCallbackCallback::setupTo(looper, manager);//進入無限循環,處理client端發來的請求while(true) {looper->pollAll(-1);}// should not be reachedreturn EXIT_FAILURE; }?下圖為android 10.0.0.R47 及以前 在service_manager.c中的 main 方法(因為頁面截圖空間限制沒有截全 可以自行查看 http://aospxref.com/android-10.0.0_r47/xref/frameworks/native/cmds/servicemanager/service_manager.c#382),相關代碼講解可以參考http://gityuan.com/2015/11/07/binder-start-sm/
其中main方法中主要干了四件事:
1)初始化binder驅動
2)將自身以“manager” 注冊到servicemanager中
3)注冊成為binder服務的大管家
4) 給Looper設置callback,進入無限循環,處理client端發來的請求
這里面著重講后三個代碼塊
1)第一個代碼塊中,android 10.0.0.R47 之前是通過binder_open 直接操作binder驅動,沒有借助libbinder,Android 11.0.0_r21 以后是通過initWithDriver 對于binder進行操作的,在編譯servicemanager的時候,添加了libbinder的庫依賴進去。
2)第二個代碼塊,將自身以“manager” 注冊到servicemanager中:
Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) { auto ctx = mAccess->getCallingContext();//獲取到調用的Context// apps cannot add services (AID_APP =10000)if (multiuser_get_app_id(ctx.uid) >= AID_APP) {return Status::fromExceptionCode(Status::EX_SECURITY);}if (!mAccess->canAdd(ctx, name)) {return Status::fromExceptionCode(Status::EX_SECURITY);}if (binder == nullptr) {return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);}if (!isValidServiceName(name)) {LOG(ERROR) << "Invalid service name: " << name;return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);}#ifndef VENDORSERVICEMANAGERif (!meetsDeclarationRequirements(binder, name)) {// already loggedreturn Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);} #endif // !VENDORSERVICEMANAGER// implicitly unlinked when the binder is removed if (binder->remoteBinder() != nullptr &&binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {LOG(ERROR) << "Could not linkToDeath when adding " << name;return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);}//以上代碼多是異常情況處理 // Overwrite the old service if it exists//將service的相關信息寫入到 servicemanager的 map中mNameToService[name] = Service {.binder = binder,.allowIsolated = allowIsolated,.dumpPriority = dumpPriority,.debugPid = ctx.debugPid,};auto it = mNameToRegistrationCallback.find(name);if (it != mNameToRegistrationCallback.end()) {for (const sp<IServiceCallback>& cb : it->second) {mNameToService[name].guaranteeClient = true;// permission checked in registerForNotificationscb->onRegistration(name, binder);}}return Status::ok(); }上面的addService 涉及到 Binder的報錯類型枚舉類:
?servicemanager中維護注冊服務的map:
?分解看service類和ServiceMap:
?這里可以看到servicemanager是用map維護注冊的服務的,android 10.0.0.R47 及以前是通過鏈表進行維護的。這里面猜測數據結構的變化是隨著手機代碼的內存增大和性能指標的增強,鏈表省空間但是查詢較慢的特性已經不能滿足需求,于是改用了查詢更快的 map進行存儲。下圖是 android 10.0.0.R47 的注冊方法:?
3)第三個代碼塊,servicemanager 成為binder服務的大管家。此處通過ioctl往binder驅動發了#define BINDER_SET_CONTEXT_MGR_EXT _IOW('b', 13, struct flat_binder_object) 的命令,如果不好用則按照android 10.0.0.R47的方式發 #define BINDER_SET_CONTEXT_MGR _IOW('b', 7, __s32)。后續流程的拆解歡迎大家幫忙補充下。
?4)第四個代碼塊,給Looper設置callback,進入無限循環,處理client端發來的請求
給Looper 設置了BinderCallback 和 ClientCallbackCallback,兩個callback 都是Loopercallback的子類。
?
?
class BinderCallback : public LooperCallback { public:static sp<BinderCallback> setupTo(const sp<Looper>& looper) { // 實例化BinderCallback sp<BinderCallback> cb = sp<BinderCallback>::make();int binder_fd = -1;//通過IPCThreadState獲取binder_fd,這里面的IPCThreadState待補充IPCThreadState::self()->setupPolling(&binder_fd);LOG_ALWAYS_FATAL_IF(binder_fd < 0, "Failed to setupPolling: %d", binder_fd);//添加監聽目標int ret = looper->addFd(binder_fd,Looper::POLL_CALLBACK,Looper::EVENT_INPUT,cb,nullptr /*data*/);LOG_ALWAYS_FATAL_IF(ret != 1, "Failed to add binder FD to Looper");return cb;}int handleEvent(int /* fd */, int /* events */, void* /* data */) override { //處理回調IPCThreadState::self()->handlePolledCommands();return 1; // Continue receiving callbacks.} };?
Looper會監聽ServiceManager 進程中打開的binder_fd,有消息上來了會調用handlePolledCommands處理。
核心是getAndExecuteCommand方法:?
status_t IPCThreadState::getAndExecuteCommand(){status_t result;int32_t cmd;//從binder driver獲取mIn數據result = talkWithDriver();if (result >= NO_ERROR) {size_t IN = mIn.dataAvail();if (IN < sizeof(int32_t)) return result;cmd = mIn.readInt32();IF_LOG_COMMANDS() {alog << "Processing top-level Command: "<< getReturnString(cmd) << endl;}pthread_mutex_lock(&mProcess->mThreadCountLock);mProcess->mExecutingThreadsCount++;if (mProcess->mExecutingThreadsCount >= mProcess->mMaxThreads &&mProcess->mStarvationStartTimeMs == 0) {mProcess->mStarvationStartTimeMs = uptimeMillis();}pthread_mutex_unlock(&mProcess->mThreadCountLock);// 解析出對應的cmd,執行cmdresult = executeCommand(cmd);pthread_mutex_lock(&mProcess->mThreadCountLock);mProcess->mExecutingThreadsCount--;if (mProcess->mExecutingThreadsCount < mProcess->mMaxThreads &&mProcess->mStarvationStartTimeMs != 0) {int64_t starvationTimeMs = uptimeMillis() - mProcess->mStarvationStartTimeMs;if (starvationTimeMs > 100) {ALOGE("binder thread pool (%zu threads) starved for %" PRId64 " ms",mProcess->mMaxThreads, starvationTimeMs);}mProcess->mStarvationStartTimeMs = 0;}// Cond broadcast can be expensive, so don't send it every time a binder// call is processed. b/168806193if (mProcess->mWaitingForThreads > 0) {pthread_cond_broadcast(&mProcess->mThreadCountDecrement);}pthread_mutex_unlock(&mProcess->mThreadCountLock);}return result; } status_t IPCThreadState::executeCommand(int32_t cmd){BBinder* obj;RefBase::weakref_type* refs;status_t result = NO_ERROR;switch ((uint32_t)cmd) {case BR_ERROR:result = mIn.readInt32();break;case BR_OK:break;case BR_ACQUIRE:refs = (RefBase::weakref_type*)mIn.readPointer();obj = (BBinder*)mIn.readPointer();ALOG_ASSERT(refs->refBase() == obj,"BR_ACQUIRE: object %p does not match cookie %p (expected %p)",refs, obj, refs->refBase());obj->incStrong(mProcess.get());IF_LOG_REMOTEREFS() {LOG_REMOTEREFS("BR_ACQUIRE from driver on %p", obj);obj->printRefs();}mOut.writeInt32(BC_ACQUIRE_DONE);mOut.writePointer((uintptr_t)refs);mOut.writePointer((uintptr_t)obj);break;case BR_RELEASE:refs = (RefBase::weakref_type*)mIn.readPointer();obj = (BBinder*)mIn.readPointer();ALOG_ASSERT(refs->refBase() == obj,"BR_RELEASE: object %p does not match cookie %p (expected %p)",refs, obj, refs->refBase());IF_LOG_REMOTEREFS() {LOG_REMOTEREFS("BR_RELEASE from driver on %p", obj);obj->printRefs();}mPendingStrongDerefs.push(obj);break;case BR_INCREFS:refs = (RefBase::weakref_type*)mIn.readPointer();obj = (BBinder*)mIn.readPointer();refs->incWeak(mProcess.get());mOut.writeInt32(BC_INCREFS_DONE);mOut.writePointer((uintptr_t)refs);mOut.writePointer((uintptr_t)obj);break;case BR_DECREFS:refs = (RefBase::weakref_type*)mIn.readPointer();obj = (BBinder*)mIn.readPointer();// NOTE: This assertion is not valid, because the object may no// longer exist (thus the (BBinder*)cast above resulting in a different// memory address).//ALOG_ASSERT(refs->refBase() == obj,// "BR_DECREFS: object %p does not match cookie %p (expected %p)",// refs, obj, refs->refBase());mPendingWeakDerefs.push(refs);break;case BR_ATTEMPT_ACQUIRE:refs = (RefBase::weakref_type*)mIn.readPointer();obj = (BBinder*)mIn.readPointer();{const bool success = refs->attemptIncStrong(mProcess.get());ALOG_ASSERT(success && refs->refBase() == obj,"BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)",refs, obj, refs->refBase());mOut.writeInt32(BC_ACQUIRE_RESULT);mOut.writeInt32((int32_t)success);}break;case BR_TRANSACTION_SEC_CTX:case BR_TRANSACTION:{//讀取mIn中的數據到一個binder_transaction_data中binder_transaction_data_secctx tr_secctx;binder_transaction_data& tr = tr_secctx.transaction_data;if (cmd == (int) BR_TRANSACTION_SEC_CTX) {result = mIn.read(&tr_secctx, sizeof(tr_secctx));} else {result = mIn.read(&tr, sizeof(tr));tr_secctx.secctx = 0;}ALOG_ASSERT(result == NO_ERROR,"Not enough command data for brTRANSACTION");if (result != NO_ERROR) break;Parcel buffer;buffer.ipcSetDataReference(reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer),tr.data_size,reinterpret_cast<const binder_size_t*>(tr.data.ptr.offsets),tr.offsets_size/sizeof(binder_size_t), freeBuffer);const void* origServingStackPointer = mServingStackPointer;mServingStackPointer = &origServingStackPointer; // anything on the stackconst pid_t origPid = mCallingPid;const char* origSid = mCallingSid;const uid_t origUid = mCallingUid;const int32_t origStrictModePolicy = mStrictModePolicy;const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags;const int32_t origWorkSource = mWorkSource;const bool origPropagateWorkSet = mPropagateWorkSource;// Calling work source will be set by Parcel#enforceInterface. Parcel#enforceInterface// is only guaranteed to be called for AIDL-generated stubs so we reset the work source// here to never propagate it.clearCallingWorkSource();clearPropagateWorkSource();mCallingPid = tr.sender_pid;mCallingSid = reinterpret_cast<const char*>(tr_secctx.secctx);mCallingUid = tr.sender_euid;mLastTransactionBinderFlags = tr.flags;// ALOGI(">>>> TRANSACT from pid %d sid %s uid %d\n", mCallingPid,// (mCallingSid ? mCallingSid : "<N/A>"), mCallingUid);Parcel reply;status_t error;IF_LOG_TRANSACTIONS() {TextOutput::Bundle _b(alog);alog << "BR_TRANSACTION thr " << (void*)pthread_self()<< " / obj " << tr.target.ptr << " / code "<< TypeCode(tr.code) << ": " << indent << buffer<< dedent << endl<< "Data addr = "<< reinterpret_cast<const uint8_t*>(tr.data.ptr.buffer)<< ", offsets addr="<< reinterpret_cast<const size_t*>(tr.data.ptr.offsets) << endl;}if (tr.target.ptr) {// We only have a weak reference on the target object, so we must first try to// safely acquire a strong reference before doing anything else with it.if (reinterpret_cast<RefBase::weakref_type*>(tr.target.ptr)->attemptIncStrong(this)) {error = reinterpret_cast<BBinder*>(tr.cookie)->transact(tr.code, buffer,&reply, tr.flags);reinterpret_cast<BBinder*>(tr.cookie)->decStrong(this);} else {error = UNKNOWN_TRANSACTION;}} else {//調用BBinder的transact方法error = the_context_object->transact(tr.code, buffer, &reply, tr.flags);}//打開該處log可以用來調試//ALOGI("<<<< TRANSACT from pid %d restore pid %d sid %s uid %d\n",// mCallingPid, origPid, (origSid ? origSid : "<N/A>"), origUid);if ((tr.flags & TF_ONE_WAY) == 0) {LOG_ONEWAY("Sending reply to %d!", mCallingPid);if (error < NO_ERROR) reply.setError(error);constexpr uint32_t kForwardReplyFlags = TF_CLEAR_BUF;//將返回的結果重新發給bindersendReply(reply, (tr.flags & kForwardReplyFlags));} else {if (error != OK) {alog << "oneway function results for code " << tr.code<< " on binder at "<< reinterpret_cast<void*>(tr.target.ptr)<< " will be dropped but finished with status "<< statusToString(error);// ideally we could log this even when error == OK, but it// causes too much logspam because some manually-written// interfaces have clients that call methods which always// write results, sometimes as oneway methods.if (reply.dataSize() != 0) {alog << " and reply parcel size " << reply.dataSize();}alog << endl;}LOG_ONEWAY("NOT sending reply to %d!", mCallingPid);}mServingStackPointer = origServingStackPointer;mCallingPid = origPid;mCallingSid = origSid;mCallingUid = origUid;mStrictModePolicy = origStrictModePolicy;mLastTransactionBinderFlags = origTransactionBinderFlags;mWorkSource = origWorkSource;mPropagateWorkSource = origPropagateWorkSet;IF_LOG_TRANSACTIONS() {TextOutput::Bundle _b(alog);alog << "BC_REPLY thr " << (void*)pthread_self() << " / obj "<< tr.target.ptr << ": " << indent << reply << dedent << endl;}}break;case BR_DEAD_BINDER:{BpBinder *proxy = (BpBinder*)mIn.readPointer();proxy->sendObituary();mOut.writeInt32(BC_DEAD_BINDER_DONE);mOut.writePointer((uintptr_t)proxy);} break;case BR_CLEAR_DEATH_NOTIFICATION_DONE:{BpBinder *proxy = (BpBinder*)mIn.readPointer();proxy->getWeakRefs()->decWeak(proxy);} break;case BR_FINISHED:result = TIMED_OUT;break;case BR_NOOP:break;case BR_SPAWN_LOOPER:mProcess->spawnPooledThread(false);break;default:ALOGE("*** BAD COMMAND %d received from Binder driver\n", cmd);result = UNKNOWN_ERROR;break;}if (result != NO_ERROR) {mLastError = result;}return result; }ClientCallbackCallback:
// LooperCallback for IClientCallbackclass ClientCallbackCallback : public LooperCallback { public:static sp<ClientCallbackCallback> setupTo(const sp<Looper>& looper, const sp<ServiceManager>& manager) { sp<ClientCallbackCallback> cb = sp<ClientCallbackCallback>::make(manager);//創建一個定時器描述符timerfdint fdTimer = timerfd_create(CLOCK_MONOTONIC, 0 /*flags*/);LOG_ALWAYS_FATAL_IF(fdTimer < 0, "Failed to timerfd_create: fd: %d err: %d", fdTimer, errno);itimerspec timespec {.it_interval = {.tv_sec = 5,.tv_nsec = 0,},.it_value = {.tv_sec = 5,.tv_nsec = 0,},};//啟動所有的定時器int timeRes = timerfd_settime(fdTimer, 0 /*flags*/, ×pec, nullptr);LOG_ALWAYS_FATAL_IF(timeRes < 0, "Failed to timerfd_settime: res: %d err: %d", timeRes, errno);//以時間為描述符注冊到Looper中int addRes = looper->addFd(fdTimer,Looper::POLL_CALLBACK,Looper::EVENT_INPUT,cb,nullptr);LOG_ALWAYS_FATAL_IF(addRes != 1, "Failed to add client callback FD to Looper");return cb;}int handleEvent(int fd, int /*events*/, void* /*data*/) override { uint64_t expirations;int ret = read(fd, &expirations, sizeof(expirations));if (ret != sizeof(expirations)) {ALOGE("Read failed to callback FD: ret: %d err: %d", ret, errno);}mManager->handleClientCallbacks();return 1; // Continue receiving callbacks.} private:friend sp<ClientCallbackCallback>;ClientCallbackCallback(const sp<ServiceManager>& manager) : mManager(manager) {}sp<ServiceManager> mManager; };當looper接收到消息時候,調用servicemanager的 handleClientCallbacks進行處理。
?主要調用handleServiceClientCallback進行處理:
ssize_t ServiceManager::handleServiceClientCallback(const std::string& serviceName, bool isCalledOnInterval) {auto serviceIt = mNameToService.find(serviceName);if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {return -1;}Service& service = serviceIt->second;ssize_t count = service.getNodeStrongRefCount();// binder driver doesn't support this featureif (count == -1) return count;bool hasClients = count > 1; // this process holds a strong countif (service.guaranteeClient) {// we have no record of this clientif (!service.hasClients && !hasClients) {sendClientCallbackNotifications(serviceName, true);}// guarantee is temporaryservice.guaranteeClient = false;}// only send notifications if this was called via the interval checking workflowif (isCalledOnInterval) {if (hasClients && !service.hasClients) {// client was retrieved in some other waysendClientCallbackNotifications(serviceName, true);}// there are no more clients, but the callback has not been called yetif (!hasClients && service.hasClients) {sendClientCallbackNotifications(serviceName, false);}}return count; }?最后通過Looper.pollAll進入無限循環,如果Looper收到消息則觸發callback。
servicemanager的主要功能:
1)注冊服務
其中注冊服務主要是通過addService 方法實現的,在講解總入口第二個代碼塊的時候已經做過拆解,不再贅余。
2)查詢服務
sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) { auto ctx = mAccess->getCallingContext();sp<IBinder> out;Service* service = nullptr;if (auto it = mNameToService.find(name); it != mNameToService.end()) {service = &(it->second);if (!service->allowIsolated) {uid_t appid = multiuser_get_app_id(ctx.uid);bool isIsolated = appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;if (isIsolated) {return nullptr;}}//將map中的信息賦值out = service->binder;}if (!mAccess->canFind(ctx, name)) {return nullptr;}//如果找不到對應的service,則嘗試以AIDL的方式啟動該serviceif (!out && startIfNotFound) {tryStartService(name);}if (out) {// Setting this guarantee each time we hand out a binder ensures that the client-checking// loop knows about the event even if the client immediately drops the serviceservice->guaranteeClient = true;}return out; }3)獲取servicemanager
不論是注冊服務或者查詢服務,都需要先獲得servicemanager的實例,servicemanager是通過defaultServiceManager 獲取的,
[[clang::no_destroy]] static std::once_flag gSmOnce; sp<IServiceManager> defaultServiceManager(){std::call_once(gSmOnce, []() {//AidlServiceManager?就是IServiceManagersp<AidlServiceManager> sm = nullptr;while (sm == nullptr) {sm = interface_cast<AidlServiceManager>(ProcessState::self()->getContextObject(nullptr));if (sm == nullptr) {ALOGE("Waiting 1s on context object on %s.", ProcessState::self()->getDriverName().c_str());sleep(1);}}gDefaultServiceManager = sp<ServiceManagerShim>::make(sm);});return gDefaultServiceManager; }這里面的gSmOnce和call_once 從名字看是只調用一次的意思,這里先不求甚解。類比android 10.0之前是使用的單例模式,此處的功能應該是類似的。
如圖,AidlServiceManager 就是IServiceManager。
這里與一般的單例模式不太一樣,里面多了一層while循環,這是google在2013年1月Todd Poynor提交的修改。當嘗試創建或獲取ServiceManager時,ServiceManager可能尚未準備就緒,這時通過sleep 1秒后,循環嘗試獲取直到成功。gDefaultServiceManager的創建過程,可分解為以下3個步驟:
-
ProcessState::self():用于獲取ProcessState對象(也是單例模式),每個進程有且只有一個ProcessState對象,存在則直接返回,不存在則創建;
-
getContextObject(): 用于獲取BpBinder對象,對于handle=0的BpBinder對象,存在則直接返回,不存在才創建;
-
interface_cast<AidlServiceManager>():用于獲取BpServiceManager對象;
分開講三個流程:
1)ProcessState::self() 獲取ProcessState對象
sp<ProcessState> ProcessState::init(const char *driver, bool requireDefault){[[clang::no_destroy]] static sp<ProcessState> gProcess;[[clang::no_destroy]] static std::mutex gProcessMutex;if (driver == nullptr) {std::lock_guard<std::mutex> l(gProcessMutex);return gProcess;}[[clang::no_destroy]] static std::once_flag gProcessOnce;std::call_once(gProcessOnce, [&](){if (access(driver, R_OK) == -1) {ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);driver = "/dev/binder";}std::lock_guard<std::mutex> l(gProcessMutex);//ProcessState調用構造方法進行初始化gProcess = sp<ProcessState>::make(driver);});if (requireDefault) {// Detect if we are trying to initialize with a different driver, and// consider that an error. ProcessState will only be initialized once above.LOG_ALWAYS_FATAL_IF(gProcess->getDriverName() != driver,"ProcessState was already initialized with %s,"" can't initialize with %s.",gProcess->getDriverName().c_str(), driver);}return gProcess; } ProcessState::ProcessState(const char *driver) : mDriverName(String8(driver)), mDriverFD(open_driver(driver))//打開Binder驅動, mVMStart(MAP_FAILED), mThreadCountLock(PTHREAD_MUTEX_INITIALIZER), mThreadCountDecrement(PTHREAD_COND_INITIALIZER), mExecutingThreadsCount(0), mWaitingForThreads(0), mMaxThreads(DEFAULT_MAX_BINDER_THREADS), mStarvationStartTimeMs(0), mThreadPoolStarted(false), mThreadPoolSeq(1), mCallRestriction(CallRestriction::NONE) {if (mDriverFD >= 0) {// mmap the binder, providing a chunk of virtual address space to receive transactions. //mmap binder驅動,提供一個虛擬內存空間地址用于收到事務//#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)mVMStart = mmap(nullptr, BINDER_VM_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, mDriverFD, 0);if (mVMStart == MAP_FAILED) {// *sigh*ALOGE("Using %s failed: unable to mmap transaction memory.\n", mDriverName.c_str());close(mDriverFD);mDriverFD = -1;mDriverName.clear();}}#ifdef __ANDROID__LOG_ALWAYS_FATAL_IF(mDriverFD < 0, "Binder driver '%s' could not be opened. Terminating.", driver); #endif }?打開binder驅動代碼塊:
static int open_driver(const char *driver){// 打開/dev/binder設備,建立與內核的Binder驅動的交互通道int fd = open(driver, O_RDWR | O_CLOEXEC);if (fd >= 0) {int vers = 0;status_t result = ioctl(fd, BINDER_VERSION, &vers);if (result == -1) {ALOGE("Binder ioctl to obtain version failed: %s", strerror(errno));close(fd);fd = -1;}if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) {ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)! ioctl() return value: %d",vers, BINDER_CURRENT_PROTOCOL_VERSION, result);close(fd);fd = -1;}size_t maxThreads = DEFAULT_MAX_BINDER_THREADS;// 通過ioctl設置binder驅動,能支持的最大線程數//#define DEFAULT_MAX_BINDER_THREADS 15 默認是15個線程result = ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads);if (result == -1) {ALOGE("Binder ioctl to set max threads failed: %s", strerror(errno));}uint32_t enable = DEFAULT_ENABLE_ONEWAY_SPAM_DETECTION;result = ioctl(fd, BINDER_ENABLE_ONEWAY_SPAM_DETECTION, &enable);if (result == -1) {ALOGD("Binder ioctl to enable oneway spam detection failed: %s", strerror(errno));}} else {ALOGW("Opening '%s' failed: %s\n", driver, strerror(errno));}return fd; }2)getContextObject(): 獲取BpBinder對象
獲取handle=0的IBinder
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle){sp<IBinder> result;AutoMutex _l(mLock);//查找handle對應的資源項handle_entry* e = lookupHandleLocked(handle);if (e != nullptr) {// We need to create a new BpBinder if there isn't currently one, OR we// are unable to acquire a weak reference on this current one. The// attemptIncWeak() is safe because we know the BpBinder destructor will always// call expungeHandle(), which acquires the same lock we are holding now.// We need to do this because there is a race condition between someone// releasing a reference on this BpBinder, and a new reference on its handle// arriving from the driver.IBinder* b = e->binder;if (b == nullptr || !e->refs->attemptIncWeak(this)) {if (handle == 0) {// Special case for context manager...// The context manager is the only object for which we create// a BpBinder proxy without already holding a reference.// Perform a dummy transaction to ensure the context manager// is registered before we create the first local reference// to it (which will occur when creating the BpBinder).// If a local reference is created for the BpBinder when the// context manager is not present, the driver will fail to// provide a reference to the context manager, but the// driver API does not return status. Note that this is not race-free if the context manager// dies while this code runs. TODO: add a driver API to wait for context manager, or// stop special casing handle 0 for context manager and add// a driver API to get a handle to the context manager with// proper reference counting.IPCThreadState* ipc = IPCThreadState::self();CallRestriction originalCallRestriction = ipc->getCallRestriction();ipc->setCallRestriction(CallRestriction::NONE);Parcel data;status_t status = ipc->transact(0, IBinder::PING_TRANSACTION, data, nullptr, 0);//通過ping操作測試binder是否準備就緒ipc->setCallRestriction(originalCallRestriction);if (status == DEAD_OBJECT)return nullptr;}//當handle值所對應的IBinder不存在或弱引用無效時,則創建BpBinder對象sp<BpBinder> b = BpBinder::create(handle);e->binder = b.get();if (b) e->refs = b->getWeakRefs();result = b;} else {// This little bit of nastyness is to allow us to add a primary// reference to the remote proxy when this team doesn't have one// but another team is sending the handle to us.result.force_set(b);e->refs->decWeak(this);}}return result; }如果handle 為0的Ibinder存在且通過Ping 測試已經準備好了,則返回該Ibinder,當handle值所對應的IBinder不存在或弱引用無效時,則創建BpBinder對象。
ProcessState::handle_entry* ProcessState::lookupHandleLocked(int32_t handle){const size_t N=mHandleToObject.size();//當handle大于mHandleToObject的長度時,進入該分支if (N <= (size_t)handle) {handle_entry e;e.binder = nullptr;e.refs = nullptr;//從mHandleToObject的第N個位置開始,插入(handle+1-N)個e到隊列中status_t err = mHandleToObject.insertAt(e, N, handle+1-N);if (err < NO_ERROR) return nullptr;}return &mHandleToObject.editItemAt(handle); }(下面模板函數部分文案出自GitYuan,非原創)根據handle值來查找對應的handle_entry,handle_entry是一個結構體,里面記錄IBinder和weakref_type兩個指針。當handle大于mHandleToObject的Vector長度時,則向該Vector中添加(handle+1-N)個handle_entry結構體,然后再返回handle向對應位置的handle_entry結構體指針。
當handle值所對應的IBinder不存在或弱引用無效時,創建BpBinder并延長對象的生命時間,創建BpBinder對象中會將handle相對應Binder的弱引用增加1:
?3)interface_cast<AidlServiceManager>():獲取BpServiceManager對象
AidlServiceManager就是IServiceManager,所以主要拆解 interface_cast:
?(interface_cast<IServiceManager>() 等價于 IServiceManager::asInterface(),asInterface是通過模板函數來定義的,
主要由以下兩個部分構成:
① DECLARE_META_INTERFACE(IServiceManager)
② IMPLEMENT_META_INTERFACE(IServiceManager,"android.os.IServiceManager")
?對于IServiceManager來說只需要換INTERFACE=IServiceManager即可,
DECLARE_META_INTERFACE 過程主要是聲明asInterface(),getInterfaceDescriptor()方法。
IMPLEMENT_META_INTERFACE 過程:
?對于IServiceManager來說 INTERFACE=IServiceManager, NAME=”android.os.IServiceManager”,可以看到DECLARE_META_INTERFACE 中的IServiceManager::asInterface() 等價于 BpIServiceManager()::make(obj)。在這里,更確切地說應該是BpIServiceManager::make(BpBinder)。
BpIServiceManager/BpServiceManager 的構造暫時未找到,能力有限,模板函數并不是很熟悉,此處文大家可以參考GitYuan的博客http://gityuan.com/2015/11/08/binder-get-sm/ 先看下android 11.0之前的講解。后續會補上android 12部分的拆解
?總結來看,defaultServiceManager 幾近 等于BpIServiceManager::make(BpBinder),這樣就獲得到了serviceManager的proxy,類似systemServer 中調用PackageManagerService的方法要拿到PackageManager 一樣,后續就可以調用serviceManager中的addService和getService方法了。
?從網上找到的 Android 11 之前的 啟動流程圖,可以先借助理解下,后面會更新最新的圖示:
?權限控制模塊:
Access 主要是通過Selinux來進行權限控制的
1)注冊服務的時候的校驗:
由于manager在service_contexts中注冊了,所以這塊Selinux可以順利通過。?
2)在查詢服務的時候通過canFind對于權限進行校驗。?
最后和 addService一樣也會通過actionAllowedFromLookup 進行校驗。
?對外接口:
在android 11之前對外接口只有四個:
在android 12中擴充為14個:?(這里將binderDied和handleClientCallbacks計算在內了)
?相關面試題:
servicemanager映射的虛擬內存有多大?現在的答案是和普通應用一樣大:1M-2頁。
frameworks/native/libs/binder/ProcessState.cpp
#define BINDER_VM_SIZE ((1 * 1024 * 1024) - sysconf(_SC_PAGE_SIZE) * 2)
參考資料:
Android 12 系統源碼分析 | Native Binder 代碼變遷 - 秋城 - 博客園
Android 12(S) Binder(一) - 青山渺渺 - 博客園
www.jb51.net
Binder系列-開篇 - Gityuan博客 | 袁輝輝的技術博客
Binder系列3-啟動ServiceManager - Gityuan博客 | 袁輝輝的技術博客
總結
以上是生活随笔為你收集整理的Android Binder 之 ServiceManager (基于android 12.0/S)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Python】使用31条规则编写高质量
- 下一篇: 网页爬虫1--正则表达式