ServiceManager的对外接口addService和getService。ServiceManager是整个Binder机制的守护进程,它本身也是一个Binder服务。
在Binder IPC通信过程中,ServiceManager扮演着重要的角色,负责处理Client和Server之间的通信请求,确保它们能够正确地找到并通信。
ServiceManager主要负责管理系统中注册的各种服务,并允许应用程序在系统中注册和获取这些服务。ServiceManager可以提供服务注册,允许应用程序或系统服务注册自己到ServiceManager中。注册时,服务会提供一个唯一的服务名称(serviceName)和对应的Binder接口(Binder Service),这样ServiceManager就能够维护一个内部映射表,存储serviceName与其Binder Service的对应关系。
ServiceManager可以提供服务查询与获取,通过ServiceManager,应用程序可以查询并获取系统中已注册的服务。
本文以Android13代码为例,分析ServiceManager的服务添加获取流程。
1,在frameworks/base/core/java/android/os/ServiceManager.java中
public final class ServiceManager {
private static IServiceManager sServiceManager;
public static void addService(String name, IBinder service) {
addService(name, service, false, IServiceManager.DUMP_FLAG_PRIORITY_DEFAULT); //const int DUMP_FLAG_PRIORITY_DEFAULT = 1 << 3;
}
public static void addService(String name, IBinder service, boolean allowIsolated,
int dumpPriority) {
try {
getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
} catch (RemoteException e) {
Log.e(TAG, "error in addService", e);
}
}
private static IServiceManager getIServiceManager() {
if (sServiceManager != null) {
return sServiceManager;
}
// Find the service manager
sServiceManager = ServiceManagerNative
.asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
return sServiceManager;
}
public static IBinder getService(String name) {
try {
IBinder service = sCache.get(name);
if (service != null) {
return service;
} else {
return Binder.allowBlocking(rawGetService(name));
}
} catch (RemoteException e) {
Log.e(TAG, "error in getService", e);
}
return null;
}
private static IBinder rawGetService(String name) throws RemoteException {
final IBinder binder = getIServiceManager().getService(name);
return binder;
}
}
上面的代码中getIServiceManager函数返回IServiceManager接口对象,并在getIServiceManager函数中调用BinderInternal.getContextObject()函数。
首先看下调用的BinderInternal.getContextObject()函数。
2,在frameworks/base/core/java/com/android/internal/os/BinderInternal.java中
public class BinderInternal {
@UnsupportedAppUsage
public static final native IBinder getContextObject();
}
上面的代码会走到android_util_Binder.cpp文件中,因为 getContextObject 对应的JNI函数名为 android_os_BinderInternal_getContextObject。
3,在frameworks/base/core/jni/android_util_Binder.cpp中
static const JNINativeMethod gBinderInternalMethods[] = {
/* name, signature, funcPtr */
{ "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject },
{ "joinThreadPool", "()V", (void*)android_os_BinderInternal_joinThreadPool },
{ "disableBackgroundScheduling", "(Z)V", (void*)android_os_BinderInternal_disableBackgroundScheduling },
{ "setMaxThreads", "(I)V", (void*)android_os_BinderInternal_setMaxThreads },
{ "handleGc", "()V", (void*)android_os_BinderInternal_handleGc },
{ "nSetBinderProxyCountEnabled", "(Z)V", (void*)android_os_BinderInternal_setBinderProxyCountEnabled },
{ "nGetBinderProxyPerUidCounts", "()Landroid/util/SparseIntArray;", (void*)android_os_BinderInternal_getBinderProxyPerUidCounts },
{ "nGetBinderProxyCount", "(I)I", (void*)android_os_BinderInternal_getBinderProxyCount },
{ "nSetBinderProxyCountWatermarks", "(II)V", (void*)android_os_BinderInternal_setBinderProxyCountWatermarks}
};
变量 gBinderInternalMethods 在函数 int_register_android_os_BinderInternal 中调用。
static int int_register_android_os_BinderInternal(JNIEnv* env)
{
jclass clazz = FindClassOrDie(env, kBinderInternalPathName);
gBinderInternalOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
gBinderInternalOffsets.mForceGc = GetStaticMethodIDOrDie(env, clazz, "forceBinderGc", "()V");
gBinderInternalOffsets.mProxyLimitCallback = GetStaticMethodIDOrDie(env, clazz, "binderProxyLimitCallbackFromNative", "(I)V");
jclass SparseIntArrayClass = FindClassOrDie(env, "android/util/SparseIntArray");
gSparseIntArrayOffsets.classObject = MakeGlobalRefOrDie(env, SparseIntArrayClass);
gSparseIntArrayOffsets.constructor = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject,
"<init>", "()V");
gSparseIntArrayOffsets.put = GetMethodIDOrDie(env, gSparseIntArrayOffsets.classObject, "put",
"(II)V");
BpBinder::setLimitCallback(android_os_BinderInternal_proxyLimitcallback);
return RegisterMethodsOrDie(env, kBinderInternalPathName,gBinderInternalMethods, NELEM(gBinderInternalMethods));//调用 gBinderInternalMethods变量
}
函数 int_register_android_os_BinderInternal 在函数 register_android_os_Binder 中调用。
int register_android_os_Binder(JNIEnv* env)
{
if (int_register_android_os_Binder(env) < 0)
return -1;
if (int_register_android_os_BinderInternal(env) < 0) //注册 int_register_android_os_BinderInternal
return -1;
if (int_register_android_os_BinderProxy(env) < 0)
return -1;
jclass clazz = FindClassOrDie(env, "android/util/Log");
gLogOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
gLogOffsets.mLogE = GetStaticMethodIDOrDie(env, clazz, "e",
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I");
clazz = FindClassOrDie(env, "android/os/ParcelFileDescriptor");
gParcelFileDescriptorOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
gParcelFileDescriptorOffsets.mConstructor = GetMethodIDOrDie(env, clazz, "<init>",
"(Ljava/io/FileDescriptor;)V");
clazz = FindClassOrDie(env, "android/os/StrictMode");
gStrictModeCallbackOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
gStrictModeCallbackOffsets.mCallback = GetStaticMethodIDOrDie(env, clazz,
"onBinderStrictModePolicyChange", "(I)V");
clazz = FindClassOrDie(env, "java/lang/Thread");
gThreadDispatchOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
gThreadDispatchOffsets.mDispatchUncaughtException = GetMethodIDOrDie(env, clazz,
"dispatchUncaughtException", "(Ljava/lang/Throwable;)V");
gThreadDispatchOffsets.mCurrentThread = GetStaticMethodIDOrDie(env, clazz, "currentThread",
"()Ljava/lang/Thread;");
return 0;
}
函数register_android_os_Binder是在AndroidRuntime.cpp中调用。
4,在frameworks/base/core/jni/AndroidRuntime.cpp中
extern int register_android_os_Binder(JNIEnv* env);
static const RegJNIRec gRegJNI[] = {
REG_JNI(register_android_os_Binder), //注册JNI
register_android_os_Binder
}
从上面的代码可以看出 getContextObject 已经注册为JNI层的 android_os_BinderInternal_getContextObject 函数。
5,在frameworks/base/core/jni/android_util_Binder.cpp中
static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
{
sp<IBinder> b = ProcessState::self()->getContextObject(NULL); //调用 getContextObject 函数
return javaObjectForIBinder(env, b); //调用 javaObjectForIBinder 转为java 层可以使用的对象
}
6,在frameworks/native/libs/binder/ProcessState.cpp中
#ifdef __ANDROID_VNDK__
const char* kDefaultDriver = "/dev/vndbinder";
#else
const char* kDefaultDriver = "/dev/binder";
#endif
sp<ProcessState> ProcessState::self()
{
return init(kDefaultDriver, false /*requireDefault*/); //kDefaultDriver是宏定义,调用init函数。
}
sp<ProcessState> ProcessState::init(const char *driver, bool requireDefault)
{
if (driver == nullptr) {
std::lock_guard<std::mutex> l(gProcessMutex);
if (gProcess) {
verifyNotForked(gProcess->mForked);
}
return gProcess;
}
// 声明一个带有 [[clang::no_destroy]] 属性的静态 std::once_flag 对象 gProcessOnce。这个属性告诉编译器不要销毁这个对象,因为 std::call_once 需要它在整个程序的生命周期内都保持有效。
[[clang::no_destroy]] static std::once_flag gProcessOnce;
// 调用 std::call_once,确保传入的 lambda 表达式只被执行一次。这是用来确保 ProcessState 的初始化只发生一次。
std::call_once(gProcessOnce, [&](){
if (access(driver, R_OK) == -1) { // 访问指定的 driver 路径,检查它是否可读
ALOGE("Binder driver %s is unavailable. Using /dev/binder instead.", driver);
driver = "/dev/binder";
}
// we must install these before instantiating the gProcess object,
// otherwise this would race with creating it, and there could be the
// possibility of an invalid gProcess object forked by another thread
// before these are installed
int ret = pthread_atfork(ProcessState::onFork, ProcessState::parentPostFork,
ProcessState::childPostFork);
LOG_ALWAYS_FATAL_IF(ret != 0, "pthread_atfork error %s", strerror(ret));
std::lock_guard<std::mutex> l(gProcessMutex); // 再次使用 std::lock_guard<std::mutex> 锁定 gProcessMutex,以确保在创建或修改 gProcess 时没有其他线程同时访问它。
gProcess = sp<ProcessState>::make(driver); // 创建一个新的 ProcessState 实例,并将其智能指针赋值给 gProcess
});
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);
}
verifyNotForked(gProcess->mForked);
return gProcess;
}
上面的代码完成了self()函数的设置,下面调用getContextObject函数。
sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/)
{
// 通过调用getStrongProxyForHandle(0)尝试获取一个IBinder对象的强引用代理。这里的0通常代表Binder驱动中的特殊句柄,用于直接获取Binder通信的根对象。这个根对象是Binder通信机制中的一个核心概念,它是所有Binder对象通信的起点。
//这里直接把参数写死为0,在SM构建的时候,第一个把自己加入进去了 每个进程启动的时候,上来加入的肯定就是SM,这里0 是句柄的意思
sp<IBinder> context = getStrongProxyForHandle(0);
if (context) {
// The root object is special since we get it directly from the driver, it is never
// written by Parcell::writeStrongBinder.
// 记这个根对象所在的编译单元(或组件)为稳定状态。这是为了优化Binder通信的性能,通过标记稳定的对象来减少不必要的通信开销。这里的context.get()用于获取context智能指针指向的原始IBinder对象。
internal::Stability::markCompilationUnit(context.get());
} else {
ALOGW("Not able to get context object on %s.", mDriverName.c_str());
}
return context;
}
上面的getContextObject函数中调用getStrongProxyForHandle函数。
sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)
{
sp<IBinder> result;
AutoMutex _l(mLock); // 自动加锁,mLock是ProcessState类的成员变量,用于保护对内部数据结构的访问,防止并发问题。
handle_entry* e = lookupHandleLocked(handle);
if (e != nullptr) {
IBinder* b = e->binder; //获取handle_entry对象中的IBinder指针
if (b == nullptr || !e->refs->attemptIncWeak(this)) { //如果IBinder指针为空,或者无法为其增加弱引用(可能是因为它已经被销毁)
if (handle == 0) {
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事务来确保上下文管理器已经注册。
ipc->setCallRestriction(originalCallRestriction);
if (status == DEAD_OBJECT)
return nullptr;
}
sp<BpBinder> b = BpBinder::PrivateAccessor::create(handle); //如果无法获取现有的IBinder对象,则创建一个新的BpBinder对象(Binder Proxy)
e->binder = b.get();
if (b) e->refs = b->getWeakRefs();
result = b; //将新创建的BpBinder对象赋值给result
} else {
result.force_set(b); //强制将现有的IBinder对象设置为result的值,即使result之前已经指向了另一个对象
e->refs->decWeak(this); //减少弱引用计数,因为我们之前尝试增加弱引用但未成功创建新的BpBinder对象。
}
}
return result;
}
7,在frameworks/base/core/jni/android_util_Binder.cpp中
jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
{
// N.B. This function is called from a @FastNative JNI method, so don't take locks around
// calls to Java code or block the calling thread for a long time for any reason.
if (val == NULL) return NULL;
// 接着检查这个IBinder对象是否是JavaBBinder的实例
if (val->checkSubclass(&gBinderOffsets)) {
// It's a JavaBBinder created by ibinderForJavaObject. Already has Java object.
// JavaBBinder是专门用于Java层创建的Binder对象与本地层交互的类。如果是,则直接返回这个JavaBBinder对象中保存的Java对象
jobject object = static_cast<JavaBBinder*>(val.get())->object();
LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
return object;
}
// 如果IBinder对象不是JavaBBinder的实例,那么它很可能是一个远程Binder代理(BinderProxy),这种情况下需要创建一个新的BinderProxyNativeData对象来存储与该代理相关的数据
BinderProxyNativeData* nativeData = new BinderProxyNativeData();
nativeData->mOrgue = new DeathRecipientList; // 为这个数据对象分配一个DeathRecipientList,用于处理Binder死亡通知
nativeData->mObject = val;
// 通过JNI调用Java层的一个静态方法(getInstance),传入BinderProxyNativeData和IBinder对象的指针,来创建一个对应的Java层BinderProxy对象
//调用getinstance 方法 把 nativeData 赋值进去 //getInstance(long nativeData, long iBinder)
//构建一个 BinderProxy ,他的构造传入了 nativeData 也就是sm
//其中gBinderProxyOffsets.mGetInstance = GetStaticMethodIDOrDie(env, clazz, "getInstance","(JJ)Landroid/os/BinderProxy;");
jobject object = env->CallStaticObjectMethod(gBinderProxyOffsets.mClass,
gBinderProxyOffsets.mGetInstance, (jlong) nativeData, (jlong) val.get()); //此时会走到BinderProxy.java中的getInstance函数
if (env->ExceptionCheck()) {// 如果调用过程中发生异常,则getInstance方法已经接管了nativeData的所有权,函数返回NULL
// In the exception case, getInstance still took ownership of nativeData.
return NULL;
}
//互相映射 获取 mNativeData 属性
BinderProxyNativeData* actualNativeData = getBPNativeData(env, object); // 通过调用getBPNativeData函数检查创建的Java对象是否正确地与nativeData关联
if (actualNativeData == nativeData) { // 如果是,则增加全局的BinderProxy计数,并在数量超过一定阈值时发出警告;这里为什么判断== 如果相等那就是新建出来的,要设 计计数问题,比如一个服务被多人调用等
// Created a new Proxy
uint32_t numProxies = gNumProxies.fetch_add(1, std::memory_order_relaxed);
uint32_t numLastWarned = gProxiesWarned.load(std::memory_order_relaxed);
if (numProxies >= numLastWarned + PROXY_WARN_INTERVAL) {
// Multiple threads can get here, make sure only one of them gets to
// update the warn counter.
////多线程 只能一个线程到这里
if (gProxiesWarned.compare_exchange_strong(numLastWarned,
numLastWarned + PROXY_WARN_INTERVAL, std::memory_order_relaxed)) {
ALOGW("Unexpectedly many live BinderProxies: %d\n", numProxies);
}
}
} else { // 如果不是,说明创建的Java对象没有使用我们创建的nativeData,那么需要删除这个nativeData
delete nativeData;
}
return object; //将代理返回,可以理解为BinderProxy
}
上面代码展示了如何在Android系统中通过JNI机制,将本地层的IBinder对象转换为Java层的对象,以支持跨进程的通信。同时,它也处理了异常情况和性能监控(通过警告过多的BinderProxy实例)。
8,在frameworks/base/core/java/android/os/BinderProxy.java中
public final class BinderProxy implements IBinder {
private static BinderProxy getInstance(long nativeData, long iBinder) {
BinderProxy result;
synchronized (sProxyMap) {
try {
result = sProxyMap.get(iBinder);
if (result != null) {
return result;
}
result = new BinderProxy(nativeData);
} catch (Throwable e) {
// We're throwing an exception (probably OOME); don't drop nativeData.
NativeAllocationRegistry.applyFreeFunction(NoImagePreloadHolder.sNativeFinalizer,
nativeData);
throw e;
}
NoImagePreloadHolder.sRegistry.registerNativeAllocation(result, nativeData);
// The registry now owns nativeData, even if registration threw an exception.
sProxyMap.set(iBinder, result);
}
return result;
}
}
在获取到IServiceManager对象后,调用addService函数,getIServiceManager().addService(name, service, allowIsolated, dumpPriority);。
9,在frameworks/native/lib/binder/aidl/android/os/IServiceManager.aidl中
interface IServiceManager {
void addService(@utf8InCpp String name, IBinder service,boolean allowIsolated, int dumpPriority);
@nullable IBinder getService(@utf8InCpp String name);
}
上面的接口定义有addService和getService函数。
10,在frameworks/base/core/java/android/os/ServiceManagerNative.java中
public final class ServiceManagerNative {
public static IServiceManager asInterface(IBinder obj) {
if (obj == null) {
return null;
}
// ServiceManager is never local
return new ServiceManagerProxy(obj); //ServiceManagerProxy 是一个实现了 IServiceManager 接口的类
}
// This class should be deleted and replaced with IServiceManager.Stub whenever mRemote is no longer used
class ServiceManagerProxy implements IServiceManager { //ServiceManagerProxy 类实现了 IServiceManager 接口中的所有方法。这些方法内部都是调用 mServiceManager 对象的相应方法,并通过 Binder IPC 机制与远程的 ServiceManager 服务进行通信。
private IBinder mRemote;
private IServiceManager mServiceManager;
public ServiceManagerProxy(IBinder remote) { //构造函数接受一个 IBinder 对象 remote 作为参数,这个对象代表了远程 ServiceManager 服务的 Binder 代理。
mRemote = remote;
mServiceManager = IServiceManager.Stub.asInterface(remote); //使用 IServiceManager.Stub.asInterface(remote) 方法将这个 Binder 代理转换为 IServiceManager 接口的实例,并保存在成员变量 mServiceManager 中
}
public IBinder asBinder() {
return mRemote;
}
@UnsupportedAppUsage
public IBinder getService(String name) throws RemoteException {
// Same as checkService (old versions of servicemanager had both methods).
return mServiceManager.checkService(name);
}
public void addService(String name, IBinder service, boolean allowIsolated, int dumpPriority)
throws RemoteException {
mServiceManager.addService(name, service, allowIsolated, dumpPriority);
}
public String[] listServices(int dumpPriority) throws RemoteException {
return mServiceManager.listServices(dumpPriority);
}
}
}
上面的代码中,ServiceManagerProxy 类是一个代理类,它实现了 IServiceManager 接口(即定义的IServiceManager.aidl文件),用于在 Java 层封装对 Android 系统 ServiceManager 服务的 Binder IPC 调用。 这个类允许 Java 层的代码以面向对象的方式与远程的 ServiceManager 服务进行交互,而不需要直接处理 Binder IPC 的底层细节。
11,在frameworks/native/libs/Binder/aidl/android/os/IServiceManager.aidl中
interface IServiceManager {
/* Allows services to dump sections according to priorities. */
const int DUMP_FLAG_PRIORITY_CRITICAL = 1 << 0;
const int DUMP_FLAG_PRIORITY_HIGH = 1 << 1;
const int DUMP_FLAG_PRIORITY_NORMAL = 1 << 2;
const int DUMP_FLAG_PRIORITY_DEFAULT = 1 << 3;
const int DUMP_FLAG_PRIORITY_ALL =
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_HIGH
| DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PRIORITY_DEFAULT;
@nullable IBinder getService(@utf8InCpp String name);
@utf8InCpp String[] listServices(int dumpPriority);
void addService(@utf8InCpp String name, IBinder service,boolean allowIsolated, int dumpPriority);
}
12,在frameworks/native/libs/binder/include/binder/IServiceManager.h中
//Service manager for C++ services. IInterface is only for legacy ABI compatibility
class IServiceManager : public IInterface {
/**
* Must match values in IServiceManager.aidl
*/
/* Allows services to dump sections according to priorities. */
static const int DUMP_FLAG_PRIORITY_CRITICAL = 1 << 0;
static const int DUMP_FLAG_PRIORITY_HIGH = 1 << 1;
static const int DUMP_FLAG_PRIORITY_NORMAL = 1 << 2;
static const int DUMP_FLAG_PRIORITY_DEFAULT = 1 << 3;
static const int DUMP_FLAG_PRIORITY_ALL = DUMP_FLAG_PRIORITY_CRITICAL |
DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PRIORITY_DEFAULT;
static const int DUMP_FLAG_PROTO = 1 << 4;
virtual sp<IBinder> getService( const String16& name) const = 0;
virtual status_t addService(const String16& name, const sp<IBinder>& service,
bool allowIsolated = false,
int dumpsysFlags = DUMP_FLAG_PRIORITY_DEFAULT) = 0;
virtual Vector<String16> listServices(int dumpsysFlags = DUMP_FLAG_PRIORITY_ALL) = 0;
};
13,在frameworks/native/cmds/servicemanager/ServiceManager.cpp中
Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
auto ctx = mAccess->getCallingContext(); // 获取当前调用者的上下文信息,这通常包括用户ID(UID)和调试进程ID(debugPid)等
if (multiuser_get_app_id(ctx.uid) >= AID_APP) { // 如果调用者的UID是应用UID(即大于等于AID_APP),则不允许添加服务,因为服务通常只能由系统或具有特定权限的进程添加。
return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services");
}
if (!mAccess->canAdd(ctx, name)) { //调用mAccess->canAdd(ctx, name)检查调用者是否有权限添加指定的服务名。如果SELinux策略不允许,则返回安全异常。
return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denial");
}
if (binder == nullptr) {
return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder");
}
if (!isValidServiceName(name)) {
LOG(ERROR) << "Invalid service name: " << name;
return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name");
}
#ifndef VENDORSERVICEMANAGER
if (!meetsDeclarationRequirements(binder, name)) {
// already logged
return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error");
}
#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, "linkToDeath failure");
}
// Overwrite the old service if it exists
mNameToService[name] = Service {
.binder = binder,
.allowIsolated = allowIsolated,
.dumpPriority = dumpPriority,
.debugPid = ctx.debugPid,
}; // 将新的服务信息(包括Binder对象、是否允许隔离、dump优先级和调试进程ID)添加到服务管理器的映射表中。如果服务已存在,则覆盖旧的服务信息。
auto it = mNameToRegistrationCallback.find(name);
if (it != mNameToRegistrationCallback.end()) {// 如果已有服务注册了针对该服务名的回调,则遍历回调列表,并调用每个回调的onRegistration方法,通知它们服务已被添加或更新。
for (const sp<IServiceCallback>& cb : it->second) {
mNameToService[name].guaranteeClient = true;
// permission checked in registerForNotifications
cb->onRegistration(name, binder);
}
}
return Status::ok();
}
在上面的addService函数中,将Service赋值给mNameToService变量。
下面看getService函数。
Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
*outBinder = tryGetService(name, true);
// returns ok regardless of result for legacy reasons
return Status::ok();
}
// 从服务管理器中获取一个指定名称的服务。如果服务存在并且调用者有权访问,它将返回该服务的IBinder接口。如果服务不存在但startIfNotFound参数为true,则尝试启动该服务。
sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
auto ctx = mAccess->getCallingContext();
sp<IBinder> out; // 初始化一个指向IBinder的智能指针,用于存储找到的服务的Binder接口。
Service* service = nullptr;
if (auto it = mNameToService.find(name); it != mNameToService.end()) {
service = &(it->second); // 通过服务名称在mNameToService映射表中查找服务。如果找到了,就将服务对象的指针赋给service变量。
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;
}
}
out = service->binder; // 如果服务存在且调用者有权访问,则将服务的Binder接口赋值给out并继续执行。
}
if (!mAccess->canFind(ctx, name)) { // 检查调用者是否有权限查找指定的服务。如果没有权限,则返回nullptr。
return nullptr;
}
if (!out && startIfNotFound) { // 如果out为nullptr(即服务不存在)且startIfNotFound为true,则调用tryStartService(name)尝试启动该服务
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 service
service->guaranteeClient = true; // 如果找到了服务(out不为nullptr),则将服务的guaranteeClient标志设置为true。这通常用于确保即使客户端立即放弃服务,服务管理器中的客户端检查循环也能知道这一事件。
}
return out;
}
从BinderInternal.getContextObject()开始梳理如下: 先调用到BinderInternal 然后调用到 android_util_Binder中的 android_os_BinderInternal_getContextObject() 这个方法 分两步 ProcessState::self()->getContextObject(NULL) 主要就是 ProcessState 调用getStrongProxyForHandle 因为参数是0 所以返回的肯定是IBinder, 其实是SM 并pin了一下保证联通. 然后执行 javaObjectForIBinder(env, b); 构建了一个BinderProxy ,将构建好的IBinder 也就是SM和IBinder 相互绑定一下, 然后返回 BinderProxy 这里已经有了SM的远端引用。 在实现中比较令人迷惑的是IServiceManager.aidl是在哪里实现的, 它是 native/libs/binder/IServiceManager.cpp 的 ServiceManagerShim 实现的 ,也就是说 远端 是 ServiceManager,服务端是 ServiceManagerShim。
14,在frameworks/native/libs/binder/IServiceManager.cpp中
using AidlServiceManager = android::os::IServiceManager;
class ServiceManagerShim : public IServiceManager
{
sp<IBinder> getService(const String16& name) const override;
status_t addService(const String16& name, const sp<IBinder>& service,bool allowIsolated, int dumpsysPriority) override;
}
status_t ServiceManagerShim::addService(const String16& name, const sp<IBinder>& service,
bool allowIsolated, int dumpsysPriority)
{
Status status = mTheRealServiceManager->addService(
String8(name).c_str(), service, allowIsolated, dumpsysPriority);
return status.exceptionCode();
}
sp<IBinder> ServiceManagerShim::getService(const String16& name) const
{
sp<IBinder> svc = checkService(name);
return nullptr;
}
sp<IBinder> ServiceManagerShim::checkService(const String16& name) const
{
sp<IBinder> ret;
if (!mTheRealServiceManager->checkService(String8(name).c_str(), &ret).isOk()) {
return nullptr;
}
return ret;
}
上面的代码最后调用到了 frameworks/native/cmds/servicemanager/ServiceManager.cpp中的函数。