binder調用流程分析

binder是一個非常好的跨進程通信工具,Android對其進行了各種封裝,雖然我們用起來簡單,但是理解起來卻比較困難。

1.自己設計一個跨進程通信機制

在理解binder之前呢,首先我們想一下,如果我們自己設計一個跨進程通信的機制,那我們會怎麼設計呢?
如果是我的話,我可能會按照下圖設計。
在這裏插入圖片描述
圖中左邊是客戶端,右邊是服務端,客戶端想要調用服務端的call函數,首先我們需要先將函數名稱以及參數值進行序列化,然後再使用linux系統所提供的跨進程通信方式,例如socket或者是管道,將這些序列化過後的數據傳遞給服務端,然後服務端拿到這些數據之後,首先進行反序列化,然後再調用相應的函數,將返回值返回給客戶端。
其實和我們使用網絡訪問服務器的結構很像。
接着我們來看下binder的通信流程。

2.跨進程通信流程

1.生成AIDL文件

首先我們新建一個AIDL文件,

interface IFile {
     Bitmap getBitmap(String path);
}

然後build過後,系統會自動幫我們生成一個IFile.java文件

public interface IFile extends android.os.IInterface {
    /**
     *繼承binder,實現IFile接口,運行於服務端
     */
    public static abstract class Stub extends android.os.Binder implements com.android.hdemo.IFile {
        private static final java.lang.String DESCRIPTOR = "com.android.hdemo.IFile";

        /**
         * Construct the stub at attach it to the interface.
         */
        public Stub() {
            this.attachInterface(this, DESCRIPTOR);
        }

        /**
         * Cast an IBinder object into an com.android.hdemo.IFile interface,
         * generating a proxy if needed.
         */
        public static com.android.hdemo.IFile asInterface(android.os.IBinder obj) {
            if ((obj == null)) {
                return null;
            }
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (((iin != null) && (iin instanceof com.android.hdemo.IFile))) {
                return ((com.android.hdemo.IFile) iin);
            }
            return new com.android.hdemo.IFile.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_getBitmap: {
                    data.enforceInterface(DESCRIPTOR);
                    java.lang.String _arg0;
                    _arg0 = data.readString();
                    android.graphics.Bitmap _result = this.getBitmap(_arg0);
                    reply.writeNoException();
                    if ((_result != null)) {
                        reply.writeInt(1);
                        _result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
                    } else {
                        reply.writeInt(0);
                    }
                    return true;
                }
            }
            return super.onTransact(code, data, reply, flags);
        }

        //實現IFile接口,運行於客戶端
        private static class Proxy implements com.android.hdemo.IFile {
            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;
            }

            @Override
            public android.graphics.Bitmap getBitmap(java.lang.String path) throws android.os.RemoteException {
                android.os.Parcel _data = android.os.Parcel.obtain();
                android.os.Parcel _reply = android.os.Parcel.obtain();
                android.graphics.Bitmap _result;
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    _data.writeString(path);
                    mRemote.transact(Stub.TRANSACTION_getBitmap, _data, _reply, 0);
                    _reply.readException();
                    if ((0 != _reply.readInt())) {
                        _result = android.graphics.Bitmap.CREATOR.createFromParcel(_reply);
                    } else {
                        _result = null;
                    }
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }
        }

        static final int TRANSACTION_getBitmap = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
    }

    public android.graphics.Bitmap getBitmap(java.lang.String path) throws android.os.RemoteException;
}

生成的代碼結構並不複雜,IFile是一個接口,繼承了android.os.IInterface,並加入了我們自定義的接口方法getBitmap,IFile中包含一個靜態抽象類Stub,Stub又包含一個靜態內部類Proxy。Stub繼承binder,實現IFile接口,運行於服務端,Proxy實現IFile接口,運行於客戶端。
接着我們來看一下從客戶端到服務端的整個流程

2.從客戶端到服務端

客戶端
首先來看下我們是如何來獲取服務的,從註釋1處可以看出,客戶端拿到binder對象之後,調用asInterface方法將其轉換成本地的IFile對象。

Intent intent = new Intent(this,TestService.class);
this.bindService(intent, new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        try {
            //1
            IFile iFile = IFile.Stub.asInterface(service);
            iFile.getBitmap("");
        }catch (Exception e){
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    }
}, Service.BIND_AUTO_CREATE);

而asInterface是系統生成的代碼,從下面註釋1處可以看出,如果客戶端和服務端在同一個進程,則直接將binder強轉成本地接口對象,否則返回Proxy對象。如註釋2所示,Proxy的getFile方法會調用mRemote.transact方法,mRemote是一個binder對象,其真正的實現是BinderProxy。

public static com.android.hdemo.IFile asInterface(android.os.IBinder obj) {
    if ((obj == null)) {
        return null;
    }
    //1.如果客戶端和服務端在同一個進程,則直接調用,否則使用Proxy
    android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
    if (((iin != null) && (iin instanceof com.android.hdemo.IFile))) {
        return ((com.android.hdemo.IFile) iin);
    }
    return new com.android.hdemo.IFile.Stub.Proxy(obj);
}

//Proxy
private static class Proxy implements com.android.hdemo.IFile {
    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;
    }

    @Override
    public android.graphics.Bitmap getBitmap(java.lang.String path) throws android.os.RemoteException {
        android.os.Parcel _data = android.os.Parcel.obtain();
        android.os.Parcel _reply = android.os.Parcel.obtain();
        android.graphics.Bitmap _result;
        try {
            _data.writeInterfaceToken(DESCRIPTOR);
            _data.writeString(path);
            //2.調用binder的transact方法
            mRemote.transact(Stub.TRANSACTION_getBitmap, _data, _reply, 0);
            _reply.readException();
            if ((0 != _reply.readInt())) {
                _result = android.graphics.Bitmap.CREATOR.createFromParcel(_reply);
            } else {
                _result = null;
            }
        } finally {
            _reply.recycle();
            _data.recycle();
        }
        return _result;
    }
}

BinderProxy的transact方法會調用transactNative方法,最終會調用native層的BpBinder的transact方法,然後由BpBinder和binder驅動進行交互。

//BinderProxy
public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
    ......
    try {
        return transactNative(code, data, reply, flags);
    } finally {
        ......
    }
}

//Native層BpBinder
status_t BpBinder::transact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
{
    // Once a binder has died, it will never come back to life.
    if (mAlive) {
        bool privateVendor = flags & FLAG_PRIVATE_VENDOR;
        // don't send userspace flags to the kernel
        flags = flags & ~FLAG_PRIVATE_VENDOR;

        // user transactions require a given stability level
        if (code >= FIRST_CALL_TRANSACTION && code <= LAST_CALL_TRANSACTION) {
            using android::internal::Stability;

            auto stability = Stability::get(this);
            auto required = privateVendor ? Stability::VENDOR : Stability::kLocalStability;

            if (CC_UNLIKELY(!Stability::check(stability, required))) {
                ALOGE("Cannot do a user transaction on a %s binder in a %s context.",
                    Stability::stabilityString(stability).c_str(),
                    Stability::stabilityString(required).c_str());
                return BAD_TYPE;
            }
        }

        status_t status = IPCThreadState::self()->transact(
            mHandle, code, data, reply, flags);
        if (status == DEAD_OBJECT) mAlive = 0;

        return status;
    }

    return DEAD_OBJECT;
}

服務端
binder驅動收到請求之後會調用native層BBinder的onTransact方法,

status_t BBinder::onTransact(
    uint32_t code, const Parcel& data, Parcel* reply, uint32_t /*flags*/)
{
    switch (code) {
        case INTERFACE_TRANSACTION:
            reply->writeString16(getInterfaceDescriptor());
            return NO_ERROR;

        case DUMP_TRANSACTION: {
            int fd = data.readFileDescriptor();
            int argc = data.readInt32();
            Vector<String16> args;
            for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
               args.add(data.readString16());
            }
            return dump(fd, args);
        }

        case SHELL_COMMAND_TRANSACTION: {
            int in = data.readFileDescriptor();
            int out = data.readFileDescriptor();
            int err = data.readFileDescriptor();
            int argc = data.readInt32();
            Vector<String16> args;
            for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
               args.add(data.readString16());
            }
            sp<IShellCallback> shellCallback = IShellCallback::asInterface(
                    data.readStrongBinder());
            sp<IResultReceiver> resultReceiver = IResultReceiver::asInterface(
                    data.readStrongBinder());

            // XXX can't add virtuals until binaries are updated.
            //return shellCommand(in, out, err, args, resultReceiver);
            (void)in;
            (void)out;
            (void)err;

            if (resultReceiver != nullptr) {
                resultReceiver->send(INVALID_OPERATION);
            }

            return NO_ERROR;
        }

        case SYSPROPS_TRANSACTION: {
            report_sysprop_change();
            return NO_ERROR;
        }

        default:
            return UNKNOWN_TRANSACTION;
    }
}

接着會回掉到java層的onTransact方法,如下注釋1所示,this.getBitmap(_arg0)爲Stub類的方法,從服務端獲取到圖片,然後在註釋2處,將bitmap寫入到返回值。

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_getBitmap: {
            data.enforceInterface(DESCRIPTOR);
            java.lang.String _arg0;
            _arg0 = data.readString();
            //1.服務端獲取的bitmap
            android.graphics.Bitmap _result = this.getBitmap(_arg0);
            reply.writeNoException();
            if ((_result != null)) {
                reply.writeInt(1);
                //2.將bitmap寫入返回值
                _result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
            } else {
                reply.writeInt(0);
            }
            return true;
        }
    }
    return super.onTransact(code, data, reply, flags);
}

我們再來看下service的定義,當綁定到一個service之後,返回的Stub對象,實現了getBitmap方法,返回了本地的bitmap。

public class TestService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new IFile.Stub() {
            @Override
            public Bitmap getBitmap(String path) throws RemoteException {
                //1.返回本地bitmap
                return mBitmap;
            }
        };
    }
}

這樣從客戶端到服務端的流程就走完了,我們看下它的流程圖
在這裏插入圖片描述

3.binder的優勢

linux本身提供了很多跨進程通信的方式,例如socket,共享內存,管道之類的,那爲啥還要再弄出個binder呢,有以下幾點
方便
binder使用起來對於開發者來說非常的友好,隱藏了底層的實現細節,我們只需要關注於業務邏輯即可。
高效
binder通信過程中,將內存同時映射到內核和應用進程當中,只需要拷貝一次即可。而socket和管道均需要從應用進程拷貝到內核,再從內核拷貝到應用進程,需要兩次拷貝,共享內存不需要數據拷貝,但使用起來比較複雜。
安全
調用方的身份標記由binder機制本身在內核態中添加,調用方不能自己更改。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章