Contenu connexe Similaire à Android binder-ipc Similaire à Android binder-ipc (20) Plus de magoroku Yamamoto Plus de magoroku Yamamoto (20) Android binder-ipc1. Android プロセス間通信の仕組み
(Android IPC Mechanism)
Jim Huang (黃敬群)
Developer, 0xlab
jserv@0xlab.org
March 19, 2012 / 南台科大
http://www.slideshare.net/jserv/android-ipc-mechanism を許可を得て@magoroku15が翻訳
2. Rights to copy
© Copyright 2012 0xlab
http://0xlab.org/
contact@0xlab.org
Corrections, suggestions, contributions and translations
Attribution – ShareAlike 3.0 are welcome!
You are free Latest update: Mar 21, 2012
to copy, distribute, display, and perform the work
to make derivative works
to make commercial use of the work
Under the following conditions
Attribution. You must give the original author credit.
Share Alike. If you alter, transform, or build upon this work, you may
distribute the resulting work only under a license identical to this one.
For any reuse or distribution, you must make clear to others the license terms
of this work.
Any of these conditions can be waived if you get permission from the
copyright holder.
Your fair use and other rights are in no way affected by the above.
License text: http://creativecommons.org/licenses/by-sa/3.0/legalcode
2
3. この資料の内容
• AndroidとBinder IPC
• デザインパターン
• Binderの構造
• Graphicsでの利用例
3
5. Androidのタスク
Process A Process B
Task Activity Activity
Content
Activity
Provider
.apk package
Service
.apk package
5
8. IPC = Inter-Process Communication
プロセス間通信
Activity
Activity Window Alarm
Manager Manager Manager
Kernel
8
10. IPCの例
• Linuxの場合
– Signal シグナル
– Pipe パイプ
– Socket ソケット
– Semaphore セマフォ
– Message queue メッセージキュー
– Shared memory 共用メモリ
• Androidの場合
– Binder Lightweight RPC を提供
10
13. Androidでの解決 Binder
• プロセス間通信をドライバで実装
• 共用メモリを利用した高速処理
• 処理要求のためのプロセス毎にスレッドプールを用意
• 参照カウントとプロセスと超えてオブジェクトの参照
• プロセス間の同期呼び出し
“In the Android platform, the binder is used for
nearly everything that happens across processes
in the core platform. " – Dianne Hackborn
https://lkml.org/lkml/2009/6/25/3
13
14. Binder: IPCの抽象化
• Intent
– 高位の抽象化
• AIDL
– Android InterfaceDefinition Language
– プロセス間通信呼び出し More abstract
• Binder Intent
– カーネルドライバ
• Ashmem AIDL
– 共用メモリ
Binder
14
16. プロセス間の手続き呼び出し
caller
interface
caller
interface
どうやって?
callee
interface
callee
16
17. プロセス間の手続き呼び出し
caller
interface
Proxy
caller
interface Binder in kernel
Binder Thread
callee
Stub
interface
callee
17
25. UMLでの表現
<<interface>>
implements
Proxy Stub
25
26. UMLでの表現
caller
<<interface>> calls
implements
Proxy Stub
extends
callee
26
28. ActivityのonPause()を呼ぶのは誰か?
2
Handlerを利用して
プロセス内でメッセージ
を送る Activity
3
Main threadから
queue OnPause() が
Looper 呼び出される
Activity
Manager Main
Binder Thread
Thread #1
Kernel 1
プロセスを跨いで
”schedulePauseActivity”
を呼び出す
28
32. 用語
• Binder
– Binder Object
• Binderインターフェイスが生成するクラスのインスタンス
• 1つのBinder objectは複数のBinderを実装する
• Binder Protocol
– IBinder インターフェイス
• 事前に定義されたBinderが実装可能な手続き、プロパティ、
イベントの集合
– Binder Token
• Binderを識別するユニークな数値
32
33. Binderの機能
• シンプルなプロセス間メッセージング
• Managing/管理
• Identifying/識別
• Calls/呼び出し
• Notification/通知
• Binder as a security access token
– セキュリティアクセストークン
33
36. Service Manager (SM)
• あらかじめ、アドレスがわかっている特殊なBinderノード
– クライアントは接続先のBinderのアドレスを知らない
– Binder interfaceだけが自分のアドレスを知っている
• Binder Interfaceは自分の名前とトークンをSMに登録する
– クライアントは利用するサービス名をSMに問い合わせてBinder
のアドレスを解決する
36
37. SMからサービスの一覧を取得
$ adb shell service list
Found 71 services:
0 stub_isms: [com.android.internal.telephony.ISms]
1 stub_phone: [com.android.internal.telephony.ITelephony]
2 stub_iphonesubinfo:
[com.android.internal.telephony.IPhoneSubInfo]
..
5 stub_telephony.registry:
[com.android.internal.telephony.ITelephonyRegistry]
...
7 stub_activity: [android.app.IActivityManager]
...
9 phone: [com.android.internal.telephony.ITelephony]
…
56 activity: [android.app.IActivityManager]
...
64 SurfaceFlinger: [android.ui.ISurfaceComposer]
...
37
38. ActivityManagerの手続き呼び出し
$ adb shell service list
...
56 activity: [android.app.IActivityManager]
...
$ adb service call activity 1598968902
Result: Parcel(
0x00000000: 0000001c 006e0061 00720064 0069006f '....a.n.d.r.o.i.'
0x00000010: 002e0064 00700061 002e0070 00410049 'd...a.p.p...I.A.'
0x00000020: 00740063 00760069 00740069 004d0079 'c.t.i.v.i.t.y.M.'
0x00000030: 006e0061 00670061 00720065 00000000 'a.n.a.g.e.r.....')
public abstract interface IBinder {
...
field public static final int INTERFACE_TRANSACTION
= 1598968902; // 0x5f4e5446
…
} Source: frameworks/base/api/current.txt
38
39. Serviceとの関係
$ adb service call phone 1 s16 "123"
Result: Parcel(00000000 '....')
電話アプリに”123”と表示される
parameter “1” → dial()
s16 "123" → String("123")
$ adb shell service list
Found 71 services:
...
9 phone: [com.android.internal.telephony.ITelephony]
interface ITelephony {
/* Dial a number. This doesn't place the call. It displays
* the Dialer screen. */
void dial(String number);
Source: frameworks/base/
telephony/java/com/android/internal/telephony/ITelephony.aidl
39
41. APIレイヤ
• AIDLはリモートサービ
スの実装を容易にする
• AIDLパーサが以下を生
成しミドルウェアを隠ぺ
いする
– Proxy class
– Stub class
– Java API Wrapper
41
42. AIDL
• データ型
• Javaプリミティブ
• コンテナ
• String,List,Map,CharSequence,List<>,多次元配列、
• Parcelable
• Interface Reference
• 方向 in, out, inout, oneway
• Android os Ibinder FLAG_ONEWAY
42
43. AIDL コンパイラ
// Interface
• Javaのみをサポート
interface IRemoteService
• StubとProxyを生成 {
void ping();
}
Client
IRemoteService mService =
IRemoteService.Stub.asInterface(servic
Server
public class RemoteService extends Service {
public IBinder onBind(Intent intent) { return mBinder; }
private final IRemoteService.Stub mBinder =
new IRemoteService.Stub() {
public void ping() { // Nothing }
};
}
43
48. Parceelの定義
• IBinderを経て送
信可能なメッ
セージのコンテ
ナ
• Parcelはフラット
に展開したデー
タと転送先で有
効なオブジェクト
して利用可能な
データを含む
48
49. Parcelのrepresentation
• Parcelは汎用的なserializationでは無い
– 高速なIPCのためのClass API
– 永続的なストレージにparcelを置く事は不適切
• 基本データ型を読み・書きする機能
–writeByte(byte) / readByte()
–writeDouble(double) / readDouble()
–writeFloat(float) / readFloat()
–writeInt(int) / readInt()
–writeLong(long) / readLong()
–writeString(String) / readString()
49
50. Parcelable
• ParcelabeプロトコルはParcelが自身を読み書
きする効率的なプロトコル
– writeParcelable(Parcelable, int)
– readParcelable(ClassLoader)
– writeParcelableArray(T[],int)
– readParcelableArray(ClassLoader)
• これらの手続きはクラスタイプとparcelへの
データ書き込みの双方で用いられて、後に適
切なクラスローダを用いて復元される
50
52. ミドルウェアレイヤ
• ユーザ空間に実装さ
れた、C++のBinderフ
レームワーク
• スレッドの生成と管理
のための構造と手続き
を実現している
• Binderのカーネルドラ
イバを呼び出す
52
54. Kernel Driver レイヤ
• Binderドライバは次のシス
テムコールをサポート
– open,mmap,release,poll,ioctl
• Ioctlの引数
– コマンドコード
• BINDER_WRITE_READ
• BINDER_SET_MAX_THREADS
• BINDER_SET_CONTEXT_MGR
• BINDER_THREAD_EXIT
• BINDER_VERSION
– データバッファ
54
58. Binder
$ adb cat /sys/devices/virtual/misc/binder/uevent
MAJOR=10
MINOR=47
DEVNAME=binder
58
59. SMからBinder Driver
Client Service Manager
service list
1 登録 Server
IXXX
Name:Handle onTransact(…)
2 Name:Handle thread pool
Handle=0 Name:Handle
transact(…)
問い合わせ
3 4 5 User Space
Kernel Spac
Binder Driver: /dev/binder
59
60. Transaction
BR
BinderDriverReturnProtocol
BC
BinderDriverCommandProtocol
ioctl(fd, BINDER_WRITE_READ, &bwt ) >= 0)
binder_write_read
write_size
write buffer
write_consumed
write_buffer
read_size
read_consumed
read_buffer read buffer
60
62. Binder IPCの限界
• Dalvik VMはメモリを共有していないので、
Binder IPCがプロセスの境界を跨いだ通信を
行う
– お互いのメモリオブジェクトを直接参照できない
• Binderは大きなデータストリームの転送には
向いていない
– Audio/VideoをParcelに変換して転送するのには
向かない
62
63. Binderの特性
• 良い点
– コンパクトな手続きの呼び出し
– バイナリデータの転送
– Ashmemのショートカット
– GUIDを利用しない
• 悪い点
– DalvikのParcel処理のオーバヘッド
– Ioctl経由での冗長な処理
– 名前解決のオーバヘッド
– 大域ロックの欠如
63
64. Binderのセキュリティ
• Binderのセキュリティ機能
– セキュリティはクライアント識別で行う
• Binder.getCallingUid(), Binder.getCallingPid()
– UNIXドメインソケットに似ている
• getsockopt(…, SO_PEERCRED, …)
– クライアントはInterfaceの利用状況を推測できない
• Service Manager
– システムサービスのディレクトリサービス
• サーバがクライアントのパミッションをチェック
– Context.checkPermission(permission, pid, uid)
64
65. Binderのサンプルプログラム
• Build binder benchmark program
% cd system/extras/tests/binder/benchmarks
% mm
% adb push ¥
../../../../out/target/product/crespo/data/nativebenchmark/binderAddInts ¥
/data/local/
• Execute
% adb shell
$ su
# /data/local/binderAddInts -d 5 -n 5 &
# ps
...
root 17133 16754 4568 860 ffffffff 400e6284 S /data/local/binderAddInts
root 17135 17133 2520 616 00000000 400e5cb0 R /data/local/binderAddInts
65
66. Binder sample program
• Execute
# /data/local/binderAddInts -d 5 -n 5 &
# ps
...
root 17133 16754 4568 860 ffffffff 400e6284 S /data/local/binderAddInts
root 17135 17133 2520 616 00000000 400e5cb0 R /data/local/binderAddInts
#cat /sys/kernel/debug/binder/transaction_log
transaction_log:3439847: call from 17133:17133 to 72:0 node 1 handle 0 size 124:4
transaction_log:3439850: reply from 72:72 to 17133:17133 node 0 handle 0 size 4:0
transaction_log:3439855: call from 17135:17135 to 17133:0 node 3439848 handle 1 size 8:0
...
66
70. Binder Transaction
• Target Method
– handle : Remote Interface
– ptr & cookie : Local Interface
– code : Method ID
• Parcel - Input/Output Parameters
– data.ptr.buffer
– data_size
• Object Reference Management
– data.ptr.offsets
– offsets_size
• Security
– sender_pid
– sender_euid
• No Transaction GUID
– Transparent Recursion
70
72. Serviceの登録と検索
• 登録
– System serviceはISserviceManager::addServiceの呼び出しで登録
– パラメータはBinder Driverのhandle
• 検索
– Binder Driver Mapの中を指定された名前で検索
– IServiceManager::getService()が登録済みのサービスのhandleを返す
• Android.os.Ibinder.INTERFACE_TRANSACTIONが実際の名前
72
74. 実際の例
Binder IPC is used for communicating between Graphics client and server.
Taken from http://www.cnblogs.com/xl19862005/archive/2011/11/17/2215363.html 74
77. Android SurfaceFlinger
• 2D/3D のsurfaceを重ね合わせる
• surfaceは複数のアプリケーションが生成
• surfaces はbuffers をBinder IPC callsで渡す
• OpenGL ES and 2D hardware accelerator を重ね合わせ
• ダブルバッファをページ切り替え
77
80. Reference
• Inter-process communication of Android, Tetsuyuki Kobayashi
• 淺談Android系統進程間通信(IPC)機制Binder中的Server和
Client獲得Service Manager接口之路
• http://blog.goggb.com/?post=1580
• Android Binder – Android Interprocess Communication,
Thorsten Schreiber
• Design Patterns in the Android Framework, Prof. Sheng-De
Wang
80