標籤:
網上看了很多關於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 := TestServerLOCAL_SRC_FILES := TestServer.cpp ITestService.cppLOCAL_MODULE_TAGS := optionalinclude $(BUILD_EXECUTABLE) #產生binder service的測試client端include $(CLEAR_VARS)LOCAL_SHARED_LIBRARIES := libcutils libutils libbinder LOCAL_MODULE := TestClientLOCAL_SRC_FILES := TestClient.cpp ITestService.cppLOCAL_MODULE_TAGS := optionalinclude $(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/TestServerBnTestService::onTransact, code: TESTBnTestService::test()
# 在另一個終端下用戶端:$ adb shell /data/local/tmp/testservice/TestClientBpTestService::test()reply 100
OK,前期準備就這麼些,接下來就可以測試代碼為入口深入到binder的內部實現了。
Binder學習筆記(一)