Binder進(jìn)程間通信(Android9.0)

Android使用的Linux內(nèi)核擁有著非常多的跨進(jìn)程通信機(jī)制,比如管道,Socket等;為什么還需要單獨(dú)搞一個(gè)Binder出來呢?主要有兩點(diǎn),性能和安全。在移動(dòng)設(shè)備上,廣泛地使用跨進(jìn)程通信肯定對(duì)通信機(jī)制本身提出了嚴(yán)格的要求;Binder相對(duì)出傳統(tǒng)的Socket方式,更加高效;另外,傳統(tǒng)的進(jìn)程通信方式對(duì)于通信雙方的身份并沒有做出嚴(yán)格的驗(yàn)證,只有在上層協(xié)議上進(jìn)行架設(shè);比如Socket通信ip地址是客戶端手動(dòng)填入的,都可以進(jìn)行偽造;而Binder機(jī)制從協(xié)議本身就支持對(duì)通信雙方做身份校檢,因而大大提升了安全性。這個(gè)也是Android權(quán)限模型的基礎(chǔ)。

一、Binder通信模型

對(duì)于跨進(jìn)程通信的雙方分別叫做Server進(jìn)程(簡(jiǎn)稱Server),Client進(jìn)程(簡(jiǎn)稱Client);由于進(jìn)程隔離的存在,它們之間沒辦法通過簡(jiǎn)單的方式進(jìn)行通信,那么Binder機(jī)制是如何進(jìn)行的呢?

Binder通信模型.png

整個(gè)通信步驟如下:

  1. ServiceManager建立:首先有一個(gè)進(jìn)程向驅(qū)動(dòng)提出申請(qǐng)為ServiceManager;驅(qū)動(dòng)同意之后,ServiceManager進(jìn)程負(fù)責(zé)管理Service。
  2. 各個(gè)Server向ServiceManager注冊(cè):每個(gè)Server端進(jìn)程啟動(dòng)之后,向ServiceManager報(bào)告,我是xxxx。
  3. Client與Server通信:首先詢問ServiceManager;請(qǐng)告訴我如何聯(lián)系xxx,SMServiceManager后給他proxy;Client收到之后就開始通信了。

Binder機(jī)制跨進(jìn)程原理

首先,Server進(jìn)程要向ServiceManager注冊(cè);告訴自己是誰,自己有什么能力;

然后Client向ServiceManager查詢:它并不會(huì)給Client進(jìn)程返回一個(gè)真正的object對(duì)象,而是返回一個(gè)看起來跟object一模一樣的代理對(duì)象objectProxy,這個(gè)objectProxy也有同樣方法,但是這個(gè)方法沒有Server進(jìn)程里面object對(duì)象中方法的能力;objectProxy的方法只是一個(gè)傀儡,它唯一做的事情就是把參數(shù)包裝然后交給驅(qū)動(dòng)。

但是Client進(jìn)程并不知道驅(qū)動(dòng)返回給它的對(duì)象動(dòng)過手腳,Client拿著objectProxy對(duì)象然后調(diào)用方法;這個(gè)方法什么也不做,直接把參數(shù)做一些包裝然后直接轉(zhuǎn)發(fā)給Binder驅(qū)動(dòng)。

驅(qū)動(dòng)收到這個(gè)消息,發(fā)現(xiàn)是這個(gè)objectProxy;一查表就明白了:我之前用objectProxy替換了object發(fā)送給Client了,它真正應(yīng)該要訪問的是object對(duì)象的方法;于是Binder驅(qū)動(dòng)通知Server進(jìn)程,Sever進(jìn)程收到這個(gè)消息,照做之后將結(jié)果返回驅(qū)動(dòng),驅(qū)動(dòng)然后把結(jié)果返回給Client進(jìn)程;于是整個(gè)過程就完成了。

Client進(jìn)程只不過是持有了Server端的代理;代理對(duì)象協(xié)助驅(qū)動(dòng)完成了跨進(jìn)程通信。

二、AIDL使用

  1. 定義AIDL接口
interface ICompute {
     int add(int a, int b);
}

編譯工具編譯之后,可以得到對(duì)應(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;
}
  1. Server端實(shí)現(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;
            }
        };
    }
}
  1. 客戶端調(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流程

bindService流程.png
  1. 調(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時(shí)通過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();
        }
    }
  1. 調(diào)用ActivityManagerServicebindService
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是一個(gè)ActiveServices類型的實(shí)例

  1. 調(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類型

  1. 調(diào)用ActivityThreadscheduleBindService
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會(huì)通過sendMessage發(fā)送一個(gè)BIND_SERVICE類型的消息,最終會(huì)調(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) {
                        //這里會(huì)調(diào)用重寫的service中的onbind方法獲取到一個(gè)stub對(duì)象
                        IBinder binder = s.onBind(data.intent);
                        //publishService 最終會(huì)通過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);
                }
            }
        }
    }
  1. 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,他的實(shí)現(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)程的方法

  1. 獲取server的proxy對(duì)象
   ICompute compute= ICompute.Stub.asInterface(service);

這里會(huì)調(diào)用AIDL文件自動(dòng)生成的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);
        }

如果是同一個(gè)進(jìn)程直接返回本進(jìn)程的Stub對(duì)象,如果是不同的進(jìn)程會(huì)new一個(gè)Proxy

  1. 調(diào)用server進(jìn)程中的方法
    從上一步可以知道,不同的進(jìn)程會(huì)調(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()會(huì)從一個(gè)Parcel池中獲取一個(gè)對(duì)象,然后將調(diào)用方法的參數(shù)寫入Parcel

調(diào)用transact將數(shù)據(jù)寫入binder驅(qū)動(dòng)中

    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ū)動(dòng)后,binder驅(qū)動(dòng)會(huì)找到對(duì)用的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);
}

這里會(huì)調(diào)用Stub中重寫的add方法,并將結(jié)果寫入reply

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容