網上看了很多關於binder的文章,但我還是想把自己的心路歷程記錄下來,有些是跟着別人的腳步領略險峻風景,有些則是自己只身探入代碼深處打撈出的收獲。我不確定是否全部融會貫通,更擔心一兩個月后會完全不記得來時的路。最好的驗證和留存的方法是把他們寫成博文,幾個月后回頭再來讀,看是否還能讀得明白。如果可以,說明我兩個擔心已不復存在;如果又回到雲里霧里,剛好可以帶着新問題繼續探索。文章很多地方會引用Android源碼,我的源碼版本是6.0.1_r11。
當靜態代碼走查遭遇多態、依賴外部數據時,常常會陷入困境,眼前多個岔路口,不知該走哪條路。我就順道把gdb也重新撿起來,動態調一把就知道正確答案了。我盡量詳細地記錄下使用步驟,以便未來可以很方便地重新走入這條路。
我覺得讀代碼也應該是“不求甚解”的,不要一竿子插到底,先在一個層面上把問題分析清楚,再逐步深入到下一個層面,逐層攻破。其實跟寫代碼很像,解決復雜問題的兩大利器——分層、分模塊。當然最終是要達到山高月小,水落石出的境界。文章會一點一點放出,發出的文章可能還會不斷回過頭來再修改,希望最終能夠打磨出一篇精致小品,以后就再也不用追究Binder了。
binder的使用(Java代碼)
Binder是Android系統為進程間通信提供的一種方式,在創建Service的時候會經常用到。創建Service的基本步驟如下:
final Intent intent = new Intent(this, BindMyService.class); private MyServiceConnection conn = new MyServiceConnection(); …… bindService(intent, connection, Service.BIND_AUTO_CREATE); // 創建Service
當Service創建成功,Service會回調ServiceConnection的onServiceCnnected函數:
public void onServiceConnected(ComponentName name, IBinder service);
更神奇的是,Service和Client可以是兩個不同的進程,而且即使跨進程,Client仍然可以把來自Service的binder當做本地對象來使用。Binder對函數調用做了封裝,把函數和參數組裝成數據包發給Service,再由Service調用和執行實際的服務接口,並把執行結果也組裝成數據包返回給客戶端。
Java層的代碼會向下進入native層,通過該層的c++代碼調用frameworks以及更底層的驅動來完成消息的流轉。為了盡快觸摸到Binder的本質,我們現在就潛入到native層,用c++代碼完成Service的編寫和Client端的調用,並以此為起點進入到Binder的實現層。至於從Java到native的橋接,可以留待本質問題水落石出之后再去探究,那只是末枝上的小細節了。
binder的使用(C++代碼)
// Test.h #ifndef __TEST_H__ #define __TEST_H__ #include <stdio.h> #include <binder/IInterface.h> #include <binder/Parcel.h> #include <binder/IBinder.h> #include <binder/Binder.h> #include <binder/ProcessState.h> #include <binder/IPCThreadState.h> #include <binder/IServiceManager.h> using namespace android; namespace android { class ITestService : public IInterface { public: DECLARE_META_INTERFACE(TestService); // declare macro virtual void test()=0; }; enum { TEST = IBinder::FIRST_CALL_TRANSACTION, }; class BpTestService: public BpInterface<ITestService> { public: BpTestService(const sp<IBinder>& impl); virtual void test(); }; } #endif
// ITestService.cpp #include "Test.h" namespace android { IMPLEMENT_META_INTERFACE(TestService, "android.TestServer.ITestService"); }
// TestClient.cpp #include "Test.h" namespace android { BpTestService::BpTestService(const sp<IBinder>& impl) : BpInterface<ITestService>(impl) { } void BpTestService::test() { printf("BpTestService::test()\n"); Parcel data, reply; data.writeInterfaceToken(ITestService::getInterfaceDescriptor()); remote()->transact(TEST, data, &reply); printf("reply: %d\n", reply.readInt32()); } } int main() { sp < IServiceManager > sm = defaultServiceManager(); sp < IBinder > binder = sm->getService(String16("service.testservice")); sp<ITestService> cs = interface_cast < ITestService > (binder); cs->test(); return 0; }
// TestServer.cpp #include "Test.h" namespace android { class BnTestService: public BnInterface<ITestService> { public: virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0); virtual void test() { printf("BnTestService::test()\n"); } }; status_t BnTestService::onTransact(uint_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch (code) { case TEST: { printf("BnTestService::onTransact, code: TEST\n"); CHECK_INTERFACE(ITest, data, reply); test(); reply->writeInt32(100); return NO_ERROR; } break; default: break; } return NO_ERROR; } } int main() { sp < ProcessState > proc(ProcessState::self()); sp < IServiceManager > sm = defaultServiceManager(); sm->addService(String16("service.testservice"), new BnTestService()); ProcessState::self()->startThreadPool(); IPCThreadState::self()->joinThreadPool(); return 0; }
LOCAL_PATH := $(call my-dir) #生成binder service的服務端 include $(CLEAR_VARS) LOCAL_SHARED_LIBRARIES := \ libcutils \ libutils \ libbinder LOCAL_MODULE := TestServer LOCAL_SRC_FILES := \ TestServer.cpp \ ITestService.cpp LOCAL_MODULE_TAGS := optional include $(BUILD_EXECUTABLE) #生成binder service的測試client端 include $(CLEAR_VARS) LOCAL_SHARED_LIBRARIES := \ libcutils \ libutils \ libbinder LOCAL_MODULE := TestClient LOCAL_SRC_FILES := \ TestClient.cpp \ ITestService.cpp LOCAL_MODULE_TAGS := optional include $(BUILD_EXECUTABLE)
在Android源碼external目錄下創建文件夾testservice,並將以上五個文件放到該文件夾下。
執行如下命令,完成編譯:
$ mmm external/testservice
我把Android源碼的build/envsetup.sh內的TARGET_BUILD_TYPE默認值全改成了debug,這樣確保執行以上mmm命令的時候,總會生成debug版。
編譯完成后,執行如下命令
$ adb shell mkdir /data/local/tmp/testservice # 把生成的兩個可執行程序拷貝到模擬器 $ adb push out/debug/target/product/generic/obj/EXECUTABLES/TestServer_intermediates/LINKED/TestServer /data/local/tmp/testservice $ adb push out/debug/target/product/generic/obj/EXECUTABLES/TestClient_intermediates/LINKED/TestClient /data/local/tmp/testservice # 添加可執行權限 $ adb shell chmod 755 /data/local/tmp/testservice/* # 啟動服務端 $ adb shell /data/local/tmp/testservice/TestServer BnTestService::onTransact, code: TEST BnTestService::test()
# 在另一個終端下客戶端: $ adb shell /data/local/tmp/testservice/TestClient BpTestService::test() reply 100
OK,前期准備就這么些,接下來就可以測試代碼為入口深入到binder的內部實現了。