Android使用的Linux內(nèi)核擁有著非常多的跨進(jìn)程通信機(jī)制,比如管道,Socket等;為什么還需要單獨搞一個Binder出來呢?主要有兩點,性能和安全。在移動設(shè)備上,廣泛地使用跨進(jìn)程通信肯定對通信機(jī)制本身提出了嚴(yán)格的要求;Binder相對出傳統(tǒng)的Socket方式,更加高效;另外,傳統(tǒng)的進(jìn)程通信方式對于通信雙方的身份并沒有做出嚴(yán)格的驗證,只有在上層協(xié)議上進(jìn)行架設(shè);比如Socket通信ip地址是客戶端手動填入的,都可以進(jìn)行偽造;而Binder機(jī)制從協(xié)議本身就支持對通信雙方做身份校檢,因而大大提升了安全性。這個也是Android權(quán)限模型的基礎(chǔ)。
一、Binder通信模型
對于跨進(jìn)程通信的雙方分別叫做Server進(jìn)程
(簡稱Server),Client進(jìn)程
(簡稱Client);由于進(jìn)程隔離的存在,它們之間沒辦法通過簡單的方式進(jìn)行通信,那么Binder機(jī)制是如何進(jìn)行的呢?
整個通信步驟如下:
- ServiceManager建立:首先有一個進(jìn)程向驅(qū)動提出申請為ServiceManager;驅(qū)動同意之后,ServiceManager進(jìn)程負(fù)責(zé)管理Service。
- 各個Server向ServiceManager注冊:每個Server端進(jìn)程啟動之后,向ServiceManager報告,我是xxxx。
- Client與Server通信:首先詢問ServiceManager;請告訴我如何聯(lián)系xxx,SMServiceManager后給他proxy;Client收到之后就開始通信了。
Binder機(jī)制跨進(jìn)程原理
首先,Server進(jìn)程要向ServiceManager注冊;告訴自己是誰,自己有什么能力;
然后Client向ServiceManager查詢:它并不會給Client進(jìn)程返回一個真正的object對象,而是返回一個看起來跟object一模一樣的代理對象objectProxy,這個objectProxy也有同樣方法,但是這個方法沒有Server進(jìn)程里面object對象中方法的能力;objectProxy的方法只是一個傀儡,它唯一做的事情就是把參數(shù)包裝然后交給驅(qū)動。
但是Client進(jìn)程并不知道驅(qū)動返回給它的對象動過手腳,Client拿著objectProxy對象然后調(diào)用方法;這個方法什么也不做,直接把參數(shù)做一些包裝然后直接轉(zhuǎn)發(fā)給Binder驅(qū)動。
驅(qū)動收到這個消息,發(fā)現(xiàn)是這個objectProxy;一查表就明白了:我之前用objectProxy替換了object發(fā)送給Client了,它真正應(yīng)該要訪問的是object對象的方法;于是Binder驅(qū)動通知Server進(jìn)程,Sever進(jìn)程收到這個消息,照做之后將結(jié)果返回驅(qū)動,驅(qū)動然后把結(jié)果返回給Client進(jìn)程;于是整個過程就完成了。
Client進(jìn)程只不過是持有了Server端的代理;代理對象協(xié)助驅(qū)動完成了跨進(jìn)程通信。
二、AIDL使用
- 定義AIDL接口
interface ICompute {
int add(int a, int b);
}
編譯工具編譯之后,可以得到對應(yīng)的ICompute.java類
public interface ICompute extends android.os.IInterface {
/**
* Local-side IPC implementation stub class.
*/
public static abstract class Stub extends android.os.Binder implements com.example.app.ICompute {
private static final java.lang.String DESCRIPTOR = "com.example.app.ICompute";
/**
* Construct the stub at attach it to the interface.
*/
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an com.example.test.app.ICompute interface,
* generating a proxy if needed.
*/
public static com.example.app.ICompute asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof proxy.ICompute))) {
return ((com.example.app.ICompute) iin);
}
return new com.example.app.ICompute.Stub.Proxy(obj);
}
@Override
public android.os.IBinder asBinder() {
return this;
}
@Override
public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_add: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
int _arg1;
_arg1 = data.readInt();
int _result = this.add(_arg0, _arg1);
reply.writeNoException();
reply.writeInt(_result);
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
private static class Proxy implements com.example.app.ICompute {
private android.os.IBinder mRemote;
Proxy(android.os.IBinder remote) {
mRemote = remote;
}
@Override
public android.os.IBinder asBinder() {
return mRemote;
}
public java.lang.String getInterfaceDescriptor() {
return DESCRIPTOR;
}
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
@Override
public int add(int a, int b) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(a);
_data.writeInt(b);
mRemote.transact(Stub.TRANSACTION_add, _data, _reply, 0);
_reply.readException();
_result = _reply.readInt();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
}
static final int TRANSACTION_add = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
}
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
public int add(int a, int b) throws android.os.RemoteException;
}
- Server端實現(xiàn)接口功能
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new ICompute.Stub() {
@Override
public int add(int a, int b) throws RemoteException {
return a + b;
}
};
}
}
- 客戶端調(diào)用
ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
try {
ICompute.Stub.asInterface(service).add(1, 2);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
三、bindService流程
- 調(diào)用context的
bindService
方法
android/app/ContextImpl.java
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
warnIfCallingFromSystemProcess();
return bindServiceCommon(service, conn, flags, mMainThread.getHandler(), getUser());
}
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, Handler
handler, UserHandle user) {
IServiceConnection sd;
if (conn == null) {
throw new IllegalArgumentException("connection is null");
}
if (mPackageInfo != null) {
// 將ServiceConnection包裝成IServiceConnection,后面獲取到server端的IBinder時通過Dispatcher分發(fā)
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
} else {
throw new RuntimeException("Not supported in system context");
}
validateServiceIntent(service);
try {
IBinder token = getActivityToken();
if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
&& mPackageInfo.getApplicationInfo().targetSdkVersion
< android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
flags |= BIND_WAIVE_PRIORITY;
}
service.prepareToLeaveProcess(this);
int res = ActivityManager.getService().bindService(
mMainThread.getApplicationThread(), getActivityToken(), service,
service.resolveTypeIfNeeded(getContentResolver()),
sd, flags, getOpPackageName(), user.getIdentifier());
if (res < 0) {
throw new SecurityException(
"Not allowed to bind to service " + service);
}
return res != 0;
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
- 調(diào)用
ActivityManagerService
的bindService
com/android/server/am/ActivityManagerService.java
public int bindService(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, IServiceConnection connection, int flags, String callingPackage,
int userId) throws TransactionTooLargeException {
enforceNotIsolatedCaller("bindService");
......
synchronized(this) {
return mServices.bindServiceLocked(caller, token, service,
resolvedType, connection, flags, callingPackage, userId);
}
}
mServices
是一個ActiveServices
類型的實例
- 調(diào)用ActiveServices的bindServiceLocked
com/android/server/am/ActiveServices.java
int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, final IServiceConnection connection, int flags,
String callingPackage, final int userId) throws TransactionTooLargeException {
......
try{
......
if (s.app != null && b.intent.received) {
// Service is already running, so we can immediately
// publish the connection.
try {
c.conn.connected(s.name, b.intent.binder, false);
} catch (Exception e) {
Slog.w(TAG, "Failure sending service " + s.shortName
+ " to connection " + c.conn.asBinder()
+ " (in " + c.binding.client.processName + ")", e);
}
// If this is the first app connected back to this binding,
// and the service had previously asked to be told when
// rebound, then do so.
if (b.intent.apps.size() == 1 && b.intent.doRebind) {
requestServiceBindingLocked(s, b.intent, callerFg, true);
}
} else if (!b.intent.requested) {
requestServiceBindingLocked(s, b.intent, callerFg, false);
}
getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
} finally {
Binder.restoreCallingIdentity(origId);
}
}
private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
boolean execInFg, boolean rebind) throws TransactionTooLargeException {
......
if ((!i.requested || rebind) && i.apps.size() > 0) {
try {
bumpServiceExecutingLocked(r, execInFg, "bind");
r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
r.app.repProcState);
if (!rebind) {
i.requested = true;
}
i.hasBound = true;
i.doRebind = false;
} catch (TransactionTooLargeException e) {
throw e;
} catch (RemoteException e) {
return false;
}
}
return true;
}
r.app.thread是ActivityThread類型
- 調(diào)用
ActivityThread
的scheduleBindService
android/app/ActivityThread.java
public final void scheduleBindService(IBinder token, Intent intent,
boolean rebind, int processState) {
updateProcessState(processState, false);
BindServiceData s = new BindServiceData();
s.token = token;
s.intent = intent;
s.rebind = rebind;
if (DEBUG_SERVICE)
Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
+ Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
sendMessage(H.BIND_SERVICE, s);
}
scheduleBindService會通過sendMessage發(fā)送一個BIND_SERVICE類型的消息,最終會調(diào)handleBindService
android/app/ActivityThread.java
private void handleBindService(BindServiceData data) {
Service s = mServices.get(data.token);
if (DEBUG_SERVICE)
Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
if (s != null) {
try {
data.intent.setExtrasClassLoader(s.getClassLoader());
data.intent.prepareToEnterProcess();
try {
if (!data.rebind) {
//這里會調(diào)用重寫的service中的onbind方法獲取到一個stub對象
IBinder binder = s.onBind(data.intent);
//publishService 最終會通過AMS調(diào)用client端的ServiceDispatcher回調(diào)onServiceConnected
ActivityManager.getService().publishService(
data.token, data.intent, binder);
} else {
s.onRebind(data.intent);
ActivityManager.getService().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
}
ensureJitEnabled();
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
} catch (Exception e) {
if (!mInstrumentation.onException(s, e)) {
throw new RuntimeException(
"Unable to bind to service " + s
+ " with " + data.intent + ": " + e.toString(), e);
}
}
}
}
- AMS 調(diào)用
publishService
通知client綁定結(jié)果
com/android/server/am/ActivityManagerService.java
public void publishService(IBinder token, Intent intent, IBinder service) {
// Refuse possible leaked file descriptors
if (intent != null && intent.hasFileDescriptors() == true) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}
synchronized(this) {
if (!(token instanceof ServiceRecord)) {
throw new IllegalArgumentException("Invalid service token");
}
mServices.publishServiceLocked((ServiceRecord)token, intent, service);
}
}
void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
final long origId = Binder.clearCallingIdentity();
try {
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
+ " " + intent + ": " + service);
if (r != null) {
Intent.FilterComparison filter
= new Intent.FilterComparison(intent);
IntentBindRecord b = r.bindings.get(filter);
if (b != null && !b.received) {
b.binder = service;
b.requested = true;
b.received = true;
for (int conni=r.connections.size()-1; conni>=0; conni--) {
ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
for (int i=0; i<clist.size(); i++) {
ConnectionRecord c = clist.get(i);
if (!filter.equals(c.binding.intent.intent)) {
if (DEBUG_SERVICE) Slog.v(
TAG_SERVICE, "Not publishing to: " + c);
if (DEBUG_SERVICE) Slog.v(
TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
if (DEBUG_SERVICE) Slog.v(
TAG_SERVICE, "Published intent: " + intent);
continue;
}
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
try {
c.conn.connected(r.name, service, false);
} catch (Exception e) {
Slog.w(TAG, "Failure sending service " + r.name +
" to connection " + c.conn.asBinder() +
" (in " + c.binding.client.processName + ")", e);
}
}
}
}
serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
}
} finally {
Binder.restoreCallingIdentity(origId);
}
}
c.conn
是在ContextImpl.bindServiceCommon
中通過mPackageInfo.getServiceDispatcher
獲取到的IServiceConnection
,他的實現(xiàn)類是LoadedApk.ServiceDispatcher.InnerConnection
android/app/LoadedApk.java
public void connected(ComponentName name, IBinder service, boolean dead) {
if (mActivityThread != null) {
mActivityThread.post(new RunConnection(name, service, 0, dead));
} else {
doConnected(name, service, dead);
}
}
public void doConnected(ComponentName name, IBinder service, boolean dead) {
......
if (service != null) {
mConnection.onServiceConnected(name, service);
} else {
// The binding machinery worked, but the remote returned null from onBind().
mConnection.onNullBinding(name);
}
}
四、client調(diào)用server進(jìn)程的方法
- 獲取server的proxy對象
ICompute compute= ICompute.Stub.asInterface(service);
這里會調(diào)用AIDL文件自動生成的java類
public static proxy.ICompute asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof proxy.ICompute))) {
return ((proxy.ICompute) iin);
}
return new ICompute.Stub.Proxy(obj);
}
如果是同一個進(jìn)程直接返回本進(jìn)程的Stub對象,如果是不同的進(jìn)程會new一個Proxy
- 調(diào)用server進(jìn)程中的方法
從上一步可以知道,不同的進(jìn)程會調(diào)用Proxy中的代理方法
public int add(int a, int b) throws android.os.RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
int _result;
try {
_data.writeInterfaceToken(DESCRIPTOR);
_data.writeInt(a);
_data.writeInt(b);
mRemote.transact(Stub.TRANSACTION_add, _data, _reply, 0);
_reply.readException();
_result = _reply.readInt();
} finally {
_reply.recycle();
_data.recycle();
}
return _result;
}
android.os.Parcel.obtain()
會從一個Parcel池中獲取一個對象,然后將調(diào)用方法的參數(shù)寫入Parcel
調(diào)用transact
將數(shù)據(jù)寫入binder驅(qū)動中
public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
Binder.checkParcel(this, code, data, "Unreasonably large binder buffer");
......
try {
return transactNative(code, data, reply, flags);
} finally {
if (tracingEnabled) {
Trace.traceEnd(Trace.TRACE_TAG_ALWAYS);
}
}
}
public native boolean transactNative(int code, Parcel data, Parcel reply,
int flags) throws RemoteException;
五、獲取調(diào)用結(jié)果
客戶端調(diào)用transact
將數(shù)據(jù)寫入binder驅(qū)動后,binder驅(qū)動會找到對用的server并調(diào)用onTransact
public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_add: {
data.enforceInterface(DESCRIPTOR);
int _arg0;
_arg0 = data.readInt();
int _arg1;
_arg1 = data.readInt();
int _result = this.add(_arg0, _arg1);
reply.writeNoException();
reply.writeInt(_result);
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
這里會調(diào)用Stub中重寫的add方法,并將結(jié)果寫入reply