Android 淺析 Binder機(jī)制 基礎(chǔ)(一)

Android Binder機(jī)制 基礎(chǔ)(一)


前言

Linus Benedict Torvalds : RTFSC – Read The Fucking Source Code

Dianne Hackborn 記住這家伙擂错,這系統(tǒng)他做的。

Binder 簡(jiǎn)要

Binder:用來(lái)實(shí)現(xiàn)不用進(jìn)程間通信袱讹。Binder屬于一個(gè)驅(qū)動(dòng)山孔,工作在linux層糠馆,運(yùn)行在kernel娄涩。服務(wù)端嘲驾,客戶(hù)端處在用戶(hù)空間,binder驅(qū)動(dòng)處在內(nèi)核空間相恃。


binder

Binder機(jī)制有兩個(gè)重要的類(lèi):IBinder和Binder辜纲。通過(guò)分析這兩個(gè)主要的類(lèi)來(lái)淺析Binder的使用。

1拦耐、IBinder

Base interface for a remotable object, the core part of a lightweight remote procedure call mechanism designed for high performance when performing in-process and cross-process calls. This interface describes the abstract protocol for interacting with a remotable object. Do not implement this interface directly, instead extend from Binder.
翻譯:
一個(gè)遠(yuǎn)程對(duì)象的基本接口耕腾,一個(gè)輕量級(jí)的遠(yuǎn)程程序的調(diào)用機(jī)制的核心部分專(zhuān)為高性能設(shè)計(jì)在執(zhí)行程序和跨進(jìn)程調(diào)用。該接口描述了與遠(yuǎn)程對(duì)象交互的抽象協(xié)議杀糯。注意:不要直接實(shí)現(xiàn)這個(gè)接口扫俺,而不是從“Binder”中擴(kuò)展。

IBinder的核心API是transact transact()匹配在Binder類(lèi)的onTransact Binder.onTransact()函數(shù)中固翰。這方法允許你發(fā)送一個(gè)調(diào)用到一個(gè)IBinder對(duì)象和從IBinder對(duì)象中收到一個(gè)調(diào)用狼纬。這個(gè)API是同步的。

通過(guò)transact()傳輸?shù)臄?shù)據(jù)是一個(gè)Parcel骂际,一個(gè)通用的緩存數(shù)據(jù)疗琉,同時(shí)也有一些元數(shù)據(jù)。在buffer中元數(shù)據(jù)使用來(lái)管理IBinder對(duì)象標(biāo)記的歉铝,這樣的引用可以在buffer穿越過(guò)程中得以保留盈简。這種機(jī)制確保IBinder被寫(xiě)入Parcel發(fā)送到另一個(gè)進(jìn)程,如果其他進(jìn)程發(fā)送一個(gè)標(biāo)記到同一個(gè)IBinder回到原來(lái)的過(guò)程太示,那么原始的過(guò)程中會(huì)接收到同一個(gè)IBinder對(duì)象回來(lái)柠贤。這些語(yǔ)義允許IBinder/Binder對(duì)象作為一個(gè)獨(dú)特的身份(作為一個(gè)記號(hào)或作其他用途),可以在過(guò)程管理类缤。

The system maintains a pool of transaction threads in each process that it runs in. These threads are used to dispatch all IPCs coming in from other processes.

The Binder system also supports recursion across processes.

1.1臼勉、transact()方法

  • IBinder核心接口方法:
    • 允許你可以分別發(fā)送一個(gè)消息到一個(gè)Binder對(duì)象和接收一個(gè)從Binder對(duì)象發(fā)出的消息。
/*
Perform a generic operation with the object.

@param code The action to perform.  This should be a number between FIRST_CALL_TRANSACTION and LAST_CALL_TRANSACTION.
@param data Marshalled data to send to the target.  Must not be null. If you are not sending any data, you must create an empty Parcel that is given here.
@param reply Marshalled data to be received from the target. May be null if you are not interested in the return value.
@param flags Additional operation flags.  Either 0 for a normal RPC, or FLAG_ONEWAY for a one-way RPC.
*/
public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException;
  • 確認(rèn)遠(yuǎn)程對(duì)象是否有效有三個(gè)方法:
    • The transact(); 如果對(duì)象被銷(xiāo)毀而你嘗試去調(diào)用這個(gè)函數(shù)餐弱,它會(huì)拋出一個(gè)異常宴霸。
    • The pingBinder(); 如果對(duì)象被銷(xiāo)毀,它會(huì)返回false膏蚓。
    • The linkToDeath(); 用來(lái)注冊(cè)一個(gè)DeathRecipient猖败,當(dāng)被銷(xiāo)毀的時(shí)候?qū)?huì)監(jiān)聽(tīng)到。

2降允、Binder

Base class for a remotable object, the core part of a lightweight remote procedure call mechanism defined by IBinder. This class is an implementation of IBinder that provides standard local implementation of such an object.
翻譯:
基類(lèi)可遠(yuǎn)程對(duì)象恩闻,由定義的IBinder一個(gè)輕量級(jí)的遠(yuǎn)程過(guò)程調(diào)用機(jī)制的核心組成部分。這個(gè)類(lèi)是的IBinder的實(shí)現(xiàn)剧董,提供了標(biāo)準(zhǔn)的地方實(shí)現(xiàn)這樣一個(gè)目標(biāo)的幢尚。

大多數(shù)開(kāi)發(fā)者不應(yīng)該直接實(shí)現(xiàn)這個(gè)類(lèi),作為代替應(yīng)該使用AIDl工具去描述你想要的接口翅楼,產(chǎn)生合適的Binder子類(lèi)尉剩。但是,你可以直接使用Binder來(lái)實(shí)現(xiàn)自定義的RPC協(xié)議或簡(jiǎn)單地實(shí)例化一個(gè)Binder的對(duì)象來(lái)直接使用作為一個(gè)記號(hào)可以共享的過(guò)程毅臊。

2.1理茎、transact()方法

/**Default implementation rewinds the parcels and calls onTransact.  On the remote side, transact calls into the binder to do the IPC.*/
public final boolean transact(int code, Parcel data, Parcel reply,
        int flags) throws RemoteException {
    if (false) Log.v("Binder", "Transact: " + code + " to " + this);
    if (data != null) {
        data.setDataPosition(0);
    }
    boolean r = onTransact(code, data, reply, flags);
    if (reply != null) {
        reply.setDataPosition(0);
    }
    return r;
}

2.2、onTransact()方法

/*Default implementation is a stub that returns false.  You will want to override this to do the appropriate unmarshalling of transactions. If you want to call this, call transact().*/
protected boolean onTransact(int code, Parcel data, Parcel reply,
        int flags) throws RemoteException {
    if (code == INTERFACE_TRANSACTION) {
        ...
        return true;
    } else if (code == DUMP_TRANSACTION) {
        ...
        return true;
    }
    return false;
}

2.3、execTransact()方法

// Entry point from android_util_Binder.cpp's onTransact
private boolean execTransact(int code, long dataObj, long replyObj,
        int flags) {
    Parcel data = Parcel.obtain(dataObj);
    Parcel reply = Parcel.obtain(replyObj);
    // theoretically, we should call transact, which will call onTransact,
    // but all that does is rewind it, and we just got these from an IPC,
    // so we'll just call it directly.
    boolean res;
    // Log any exceptions as warnings, don't silently suppress them.
    // If the call was FLAG_ONEWAY then these exceptions disappear into the ether.
    try {
        res = onTransact(code, data, reply, flags);
    } catch (RemoteException e) {
        if ((flags & FLAG_ONEWAY) != 0) {
        } else {
            reply.setDataPosition(0);
            reply.writeException(e);
        }
        res = true;
    } catch (RuntimeException e) {
        if ((flags & FLAG_ONEWAY) != 0) {
        } else {
            reply.setDataPosition(0);
            reply.writeException(e);
        }
        res = true;
    } catch (OutOfMemoryError e) {
        // Unconditionally log this, since this is generally unrecoverable.
        RuntimeException re = new RuntimeException("Out of memory", e);
        reply.setDataPosition(0);
        reply.writeException(re);
        res = true;
    }
    checkParcel(this, code, reply, "Unreasonably large binder reply buffer");
    reply.recycle();
    data.recycle();

    // Just in case -- we are done with the IPC, so there should be no more strict
    // mode violations that have gathered for this thread.  Either they have been
    // parceled and are now in transport off to the caller, or we are returning back
    // to the main transaction loop to wait for another incoming transaction.  Either
    // way, strict mode begone!
    StrictMode.clearGatheredViolations();

    return res;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末皂林,一起剝皮案震驚了整個(gè)濱河市朗鸠,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌础倍,老刑警劉巖烛占,帶你破解...
    沈念sama閱讀 222,946評(píng)論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異沟启,居然都是意外死亡忆家,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,336評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)德迹,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)芽卿,“玉大人,你說(shuō)我怎么就攤上這事胳搞〉攀” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,716評(píng)論 0 364
  • 文/不壞的土叔 我叫張陵流酬,是天一觀的道長(zhǎng)币厕。 經(jīng)常有香客問(wèn)我,道長(zhǎng)芽腾,這世上最難降的妖魔是什么旦装? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 60,222評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮摊滔,結(jié)果婚禮上阴绢,老公的妹妹穿的比我還像新娘。我一直安慰自己艰躺,他們只是感情好呻袭,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,223評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著腺兴,像睡著了一般左电。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上页响,一...
    開(kāi)封第一講書(shū)人閱讀 52,807評(píng)論 1 314
  • 那天篓足,我揣著相機(jī)與錄音,去河邊找鬼闰蚕。 笑死栈拖,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的没陡。 我是一名探鬼主播涩哟,決...
    沈念sama閱讀 41,235評(píng)論 3 424
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼索赏,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了贴彼?” 一聲冷哼從身側(cè)響起潜腻,我...
    開(kāi)封第一講書(shū)人閱讀 40,189評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎锻弓,沒(méi)想到半個(gè)月后砾赔,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體蝌箍,經(jīng)...
    沈念sama閱讀 46,712評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡青灼,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,775評(píng)論 3 343
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了妓盲。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片杂拨。...
    茶點(diǎn)故事閱讀 40,926評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖悯衬,靈堂內(nèi)的尸體忽然破棺而出弹沽,到底是詐尸還是另有隱情,我是刑警寧澤筋粗,帶...
    沈念sama閱讀 36,580評(píng)論 5 351
  • 正文 年R本政府宣布策橘,位于F島的核電站,受9級(jí)特大地震影響娜亿,放射性物質(zhì)發(fā)生泄漏丽已。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,259評(píng)論 3 336
  • 文/蒙蒙 一买决、第九天 我趴在偏房一處隱蔽的房頂上張望沛婴。 院中可真熱鬧,春花似錦督赤、人聲如沸嘁灯。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,750評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)丑婿。三九已至,卻和暖如春没卸,著一層夾襖步出監(jiān)牢的瞬間枯冈,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,867評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工办悟, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留尘奏,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,368評(píng)論 3 379
  • 正文 我出身青樓病蛉,卻偏偏與公主長(zhǎng)得像炫加,于是被迫代替她去往敵國(guó)和親瑰煎。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,930評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容