AndroidIPCMechanismJimHuang(黃敬群)Developer,0xlabjserv@0xlab.
orgMarch19,2012/南台科大RightstocopyAttribution–ShareAlike3.
0Youarefreetocopy,distribute,display,andperformtheworktomakederivativeworkstomakecommercialuseoftheworkUnderthefollowingconditionsAttribution.
Youmustgivetheoriginalauthorcredit.
ShareAlike.
Ifyoualter,transform,orbuilduponthiswork,youmaydistributetheresultingworkonlyunderalicenseidenticaltothisone.
Foranyreuseordistribution,youmustmakecleartoothersthelicensetermsofthiswork.
Anyoftheseconditionscanbewaivedifyougetpermissionfromthecopyrightholder.
Yourfairuseandotherrightsareinnowayaffectedbytheabove.
Licensetext:http://creativecommons.
org/licenses/by-sa/3.
0/legalcodeCopyright20120xlabhttp://0xlab.
org/contact@0xlab.
orgCorrections,suggestions,contributionsandtranslationsarewelcome!
Latestupdate:Mar21,2012Agenda(0)IPC:TheheartofAndroid(1)DesignPatterns(2)BinderIPCInternals(3)Usecase:GraphicsBinderIPC:TheheartofAndroidProcessAProcessAProcessBProcessBTaskActivityActivityActivityActivity.
apkpackage.
apkpackageContentProviderContentProviderActivityActivityServiceService5AndroidTasksDifferentcomponenttypes–Activity–Service–ContentProvider–BroadcastReceiverComponentViewApplicationComponentsSystemActivityManagerWindowManagerAlarmManagerActivityKernelIPC=Inter-ProcessCommunicationWhyIPCEachprocesshasitsownaddressspaceProvidesdataisolationPreventsharmfuldirectinteractionbetweentwodifferentprocesses–Sometimes,communicationbetweenprocessesisrequiredformodularization10IPCMechanismsInGNU/Linux–Signal–Pipe–Socket–Semaphore–Messagequeue–SharedmemoryInAndroid–Binder:lightweightRPC(RemoteProcedureCommunication)mechanismDevelopedunderthenameOpenBinderbyPalmInc.
undertheleadershipofDianneHackbornAndroidBinderisthecustomizedre-implementationofOpenBinder,whichprovidesbindingstofunctionsanddatafromoneexecutionenvironmenttoanotherBinderHistory12BackgroundProblemsApplicationsandServicesmayruninseparateprocessesbutmustcommunicateandsharedataIPCcanintroducesignificantprocessingoverheadandsecurityholesBinder:Android'sSolutionDrivertofacilitateinter-processcommunicationHighperformancethroughsharedmemoryPer-processthreadpoolforprocessingrequestsReferencecounting,andmappingofobjectreferencesacrossprocessesSynchronouscallsbetweenprocesses"IntheAndroidplatform,thebinderisusedfornearlyeverythingthathappensacrossprocessesinthecoreplatform.
"–DianneHackbornhttps://lkml.
org/lkml/2009/6/25/3BinderAIDLIntentMoreabstractIPCAbstractionIntent–ThehighestlevelabstractionInterprocessmethodinvocation–AIDL:AndroidInterfaceDefinitionLanguagebinder:kerneldriverashmem:sharedmemorycallercalleeInthesameprocessMethodinvocationcallercalleecalleecallerinterfaceinterfaceinterfaceHowInter-processmethodinvocationcallercalleeBinderinkernelcalleecallerProxyBinderThreadStubinterfaceinterfaceinterfaceInter-processmethodinvocationDesignPatternsTheProxyPattern11ProxyserviceServiceserviceAbstractServiceserviceClientPatternAbstractsandnamesarecurringdesignstructureComprisesclassand/orobject–Dependencies–Structures–Interactions–ConventionsSpecifiesthedesignstructureexplicitlyisdistilledfromactualdesignexperienceAndroiditselffollowsobjectorienteddesignDesignPatternsusedinBinder(incomplete)ProxyPatternMediatorPatternBridgePattern21ProxyPatternTheproxycouldinterfacetoanything:anetworkconnection,alargeobjectinmemory,afile,orsomeotherresourcethatisexpensiveorimpossibletoduplicate.
22ProxyPatterninAndroidBinderdecomposesthemethodcallandallitscorrespondingdatatoalevelthatLinuxcanunderstand,transmittingitfromthelocalprocessandaddressspacetotheremoteprocessandaddressspace,andreassemblingandreenactingthecallthere.
23MediatorPatternWiththemediatorpattern,communicationbetweenobjectsisencapsulatedwithamediatorobject.
24BridgePatterndecoupleanabstractionfromitsimplementationsothatthetwocanvaryindependently25BridgepatternsinlinkingJavaandC++MediatorpatternBridgeandMediatorPatterninAndroid>ProxyStubimplementsUMLRepresentation>ProxyStubcallercalleecallsimplementsextendsUMLRepresentation>ProxyStubcallercalleeAutogeneratedfrom.
aidlfileAIDLActivityManagerKernelBinderThread#1MainThreadLooperOnPause()iscalledinmainthreadCall"schedulePauseActivity"acrossprocessSendmessagebyHandlerActivityUseCase:WhocallsonPause()inActivity321queueIPCInteractioninAndroid(ApplicationView)FrameworkgetService1callinterface23parts:BnXXX:nativeBpXXX:proxyClientInvokeBpXXXBinderinActionProcessBProcessABinderInternalsBinderBinderObject–aninstanceofaclassthatimplementstheBinderinterface.
–OneBinderobjectcanimplementmultipleBindersBinderProtocolIBinderInterface–isawell-definedsetofmethods,propertiesandeventsthataBindercanimplement.
BinderToken–AnumericvaluethatuniquelyidentifiesaBinderBinderTerminologySimpleinterprocessmessagingsystemManagingIdentifyingCallsNotificationBinderasasecurityaccesstokenFacilitiesBinderframeworkprovidesmorethanasimpleinterprocessmessagingsystem.
Methodsonremoteobjectscanbecalledasiftheywherelocalobjectmethods.
CommunicationprotocolIfoneprocesssendsdatatoanotherprocess,itiscalledtransaction.
Thedataiscalledtransactiondata.
SpecialBindernodewithknownBinderaddressClientdoesnotknowtheaddressofremoteBinder–onlyBinderinterfaceknowsitsownaddressBindersubmitsanameanditsBindertokentoSM–ClientretrievesBinderaddresswithservicenamefromSMServiceManager(SM)GetServicelistfromSM$adbshellservicelistFound71services:0stub_isms:[com.
android.
internal.
telephony.
ISms]1stub_phone:[com.
android.
internal.
telephony.
ITelephony]2stub_iphonesubinfo:[com.
android.
internal.
telephony.
IPhoneSubInfo].
.
5stub_telephony.
registry:[com.
android.
internal.
telephony.
ITelephonyRegistry].
.
.
7stub_activity:[android.
app.
IActivityManager].
.
.
9phone:[com.
android.
internal.
telephony.
ITelephony]…56activity:[android.
app.
IActivityManager].
.
.
64SurfaceFlinger:[android.
ui.
ISurfaceComposer].
.
.
CallremotemethodinActivityManagerpublicabstractinterfaceIBinder{.
.
.
fieldpublicstaticfinalintINTERFACE_TRANSACTION=1598968902;//0x5f4e5446…}Source:frameworks/base/api/current.
txt$adbshellservicelist.
.
.
56activity:[android.
app.
IActivityManager].
.
.
$adbservicecallactivity1598968902Result:Parcel(0x00000000:0000001c006e0061007200640069006f'.
.
.
.
a.
n.
d.
r.
o.
i.
'0x00000010:002e006400700061002e007000410049'd.
.
.
a.
p.
p.
.
.
I.
A.
'0x00000020:007400630076006900740069004d0079'c.
t.
i.
v.
i.
t.
y.
M.
'0x00000030:006e0061006700610072006500000000'a.
n.
a.
g.
e.
r.
.
.
.
.
')InteractwithAndroidService$adbshellservicelistFound71services:.
.
.
9phone:[com.
android.
internal.
telephony.
ITelephony]$adbshellservicelistFound71services:.
.
.
9phone:[com.
android.
internal.
telephony.
ITelephony]servicecallSERVICECODE[i32INT|s16STR]…Options:i32:WritetheintegerINTintothesendparcel.
s16:WritetheUTF-16stringSTRintothesendparcel.
servicecallSERVICECODE[i32INT|s16STR]…Options:i32:WritetheintegerINTintothesendparcel.
s16:WritetheUTF-16stringSTRintothesendparcel.
PhoneApplicationappearsinforeground.
parameter"1"→dial()s16"123"→String("123")interfaceITelephony{/*Dialanumber.
Thisdoesn'tplacethecall.
Itdisplays*theDialerscreen.
*/voiddial(Stringnumber);Source:frameworks/base/telephony/java/com/android/internal/telephony/ITelephony.
aidl$adbservicecallphone1s16"123"Result:Parcel(00000000'.
.
.
.
')ImplementationLayersofBinderImplementedinCImplementedinC++ImplementedinJavaAIDL(AndroidInterfaceDefinitionLanguage)–EasetheimplementationofAndroidremoteservices–Definesaninterfacewithmethodofremoteservices–AIDLparsergeneratesJavaclassProxyclassforClientStubclassforServiceJavaAPIWrapperIntroducefacilitiestothebinder–WrapsthemiddlewarelayerAPILayer43AIDLDataTypes–JavaPrimitives–ContainersString,List,Map,CharSequenceListMultidimensionalArray–Parcelable–InterfaceReferenceDirection-in,out,inoutoneway–android.
os.
IBinder.
FLAG_ONEWAY44AIDLCompilerFull-fledgedJava(-only)SupportStubandProxyGenerator//InterfaceinterfaceIRemoteService{voidping();}publicclassRemoteServiceextendsService{publicIBinderonBind(Intentintent){returnmBinder;}privatefinalIRemoteService.
StubmBinder=newIRemoteService.
Stub(){publicvoidping(){//Nothing}};}IRemoteServicemService=IRemoteService.
Stub.
asInterface(service);ServerClientSimpleinterprocessmessagingsystemInanobjectorientedview,thetransactiondataiscalledparcel.
Theprocedureofbuildingaparceliscalledmarshallinganobject.
Theprocedureofrebuildingaobjectfromaparceliscalledunmarshallinganobject.
ParcelsandMarshalling47ParcelMarshalling–Thetransferringofdataacrossprocessboundaries–RepresentedinnativebinaryencodingMostlyhandledbyAIDL-generatedcodeExtensible–Parcelable"flatten""unflatten"transmitDeliveringargumentsofmethodandroid.
os.
ParcelParcelDefinitionContainerforamessage(dataandobjectreferences)thatcanbesentthroughanIBinder.
AParcelcancontainbothflatteneddatathatwillbeunflattenedontheothersideoftheIPC(usingthevariousmethodshereforwritingspecifictypes,orthegeneralParcelableinterface),andreferencestoliveIBinderobjectsthatwillresultintheothersidereceivingaproxyIBinderconnectedwiththeoriginalIBinderintheParcel.
RepresentationofParcelParcelisnotforgeneral-purposeserialization–Thisclass(andthecorrespondingParcelableAPIforplacingarbitraryobjectsintoaParcel)isdesignedasahigh-performanceIPCtransport.
–NotappropriatetoplaceanyParceldataintopersistentstorageFunctionsforwriting/readingprimitivedatatypes:–writeByte(byte)/readByte()–writeDouble(double)/readDouble()–writeFloat(float)/readFloat()–writeInt(int)/readInt()–writeLong(long)/readLong()–writeString(String)/readString()ParcelableTheParcelableprotocolprovidesanextremelyefficient(butlow-level)protocolforobjectstowriteandreadthemselvesfromParcels.
Usethedirectmethodstowrite/read–writeParcelable(Parcelable,int)readParcelable(ClassLoader)–writeParcelableArray(T[],int)readParcelableArray(ClassLoader)ThesemethodswriteboththeclasstypeanditsdatatotheParcel,allowingthatclasstobereconstructedfromtheappropriateclassloaderwhenlaterreading.
52BundlesAspecialtype-safecontainer,calledBundle,isavailableforkey/valuemapsofheterogeneousvalues.
Thishasmanyoptimizationsforimprovedperformancewhenreadingandwritingdata,anditstype-safeAPIavoidsdifficulttodebugtypeerrorswhenfinallymarshallingthedatacontentsintoaParcel.
ImplementstheuserspacefacilitiesoftheBinderframeworkinC++ImplementsstructuresandmethodstospawnandmanagenewthreadsMarshallingandunmarshallingofspecificdataProvidesinteractionwiththeBinderkerneldriverMiddlewareLayerframeworks/base/include/binder/IServiceManager.
hspdefaultServiceManager()frameworks/base/include/binder/IInterface.
htemplateBpInterface55KernelDriverLayerBinderDriversupportsthefileoperationsopen,mmap,release,pollandthesystemcallioctlioctlarguments–Binderdrivercommandcode–DatabufferCommandcodes–BINDER_WRITE_READ–BINDER_SET_MAX_THREADS–BINDER_SET_CONTEXT_MGR–BINDER_THREAD_EXIT–BINDER_VERSIONMulti-threadaware–Haveinternalstatusperthead–ComparetoUNIXsocket:socketshaveinternalstatusperfiledescriptor(FD)BinderDriverBinderDriverApoolofthreadsisassociatedtoeachserviceapplicationtoprocessincomingIPCBinderperformsmappingofobjectbetweentwoprocesses.
Binderusesanobjectreferenceasanaddressinaprocess'smemoryspace.
Synchronouscall,referencecountingsocketbinderinternalstatusassociatedtoFDassociatedtoPID(FDcanbesharedamongthreadsinthesameprocess)read&writeoperationstreamI/OdoneatoncebyioctlnetworktransparencyYesNoexpectedlocalonlyBinderisdifferentfromUNIXsocketBinder$adbcat/sys/devices/virtual/misc/binder/ueventMAJOR=10MINOR=47DEVNAME=binderClientClientServerServerServiceManagerServiceManagerBinderDriver:/dev/binderBinderDriver:/dev/binderKernelSpaceUserSpaceHandle=0Name:HandleName:HandleName:HandleservicelistIXXXonTransact(…)threadpoolmemorymappingtransact(…)60fromSMtoBinderDriver12345if(ioctl(fd,BINDER_WRITE_READ,&bwt)>=0)err=NO_ERROR;elseerr=-errno;writebufferreadbufferwrite_sizewrite_consumedwrite_bufferread_sizeread_consumedread_bufferbinder_write_readTransactionBR→BinderDriverReturnProtocolBC→BinderDriverCommandProtocolProcessAProcessBBinderProcessABinderProcessBCopymemorybycopy_from_userCopymemorybycopy_to_userThen,wakeupprocessBProcessAandBhavedifferentmemoryspace.
Theycannotseeeachother.
KernelKernelTransactionofBinderInternally,AndroidusesBinderforgraphicsdatatransactionacrossprocesses.
Itisfairlyefficient.
63LimitationofBinderIPCBindersareusedtotocommunicateoverprocessboundariessincedifferentprocessesdon'tshareacommonVMcontext–nomoredirectaccesstoeachothersObjects(memory).
Bindersarenotidealfortransferringlargedatastreams(likeaudio/video)sinceeveryobjecthastobeconvertedto(andbackfrom)aParcel.
64BinderPerformanceGood–Compactmethodindex–Nativebinarymarshalling–Supportofashmemshortcut–NoGUIDBad–DalvikParceloverhead–ioctl()pathisnotoptimal–Interfacenameoverhead–Globallock65BinderSecurityBinder'sSecurityFeatures–SecurelyDeterminedClientIdentityBinder.
getCallingUid(),Binder.
getCallingPid()SimilartoUnixDomainSocketgetsockopt(.
.
.
,SO_PEERCRED,.
.
.
)–InterfaceReferenceSecurityClientcannotguessInterfaceReferenceServiceManager–DirectoryServiceforSystemServicesServershouldcheckclientpermissionContext.
checkPermission(permission,pid,uid)BindersampleprogramBuildbinderbenchmarkprogramcdsystem/extras/tests/binder/benchmarksmmadbpush\out/target/product/crespo/data/nativebenchmark/binderAddInts\/data/local/Executeadbshellsu/data/local/binderAddInts-d5-n5&ps.
.
.
root17133167544568860ffffffff400e6284S/data/local/binderAddIntsroot1713517133252061600000000400e5cb0R/data/local/binderAddIntsBindersampleprogramExecute/data/local/binderAddInts-d5-n5&ps.
.
.
root17133167544568860ffffffff400e6284S/data/local/binderAddIntsroot1713517133252061600000000400e5cb0R/data/local/binderAddIntscat/sys/kernel/debug/binder/transaction_logtransaction_log:3439847:callfrom17133:17133to72:0node1handle0size124:4transaction_log:3439850:replyfrom72:72to17133:17133node0handle0size4:0transaction_log:3439855:callfrom17135:17135to17133:0node3439848handle1size8:0.
.
.
Bindersysfsentriesadbshellls/sys/kernel/debug/binderfailed_transaction_logprocstatestatstransaction_logtransactionsRemoteProcedureCallBINDER_WRITE_READTargetMethod–handle:RemoteInterface–ptr&cookie:LocalInterface–code:MethodIDParcel-Input/OutputParameters–data.
ptr.
buffer–data_sizeObjectReferenceManagement–data.
ptr.
offsets–offsets_sizeSecurity–sender_pid–sender_euidNoTransactionGUID–TransparentRecursionBinderTransactionObjectReferenceManagementSystemserviceisexecutedbyIServiceManager::addService()calls.
–Parameter:handletoBinderDriverLookupthenameofspecificserviceinBinderDriverMap–IServiceManager::getService()returnsthehandleofthefoundregisteredservicesandroid.
os.
IBinder.
INTERFACE_TRANSACTION:theactualnameServiceRegistrationandDiscoveryBinderusecase:AndroidGraphicsBinderIPCisusedforcommunicatingbetweenGraphicsclientandserver.
Takenfromhttp://www.
cnblogs.
com/xl19862005/archive/2011/11/17/2215363.
htmlRealCaseSurfaceSource:frameworks/base/core/java/android/view/Surface.
java/*Handleontoarawbufferthatisbeingmanagedbythescreencompositor*/publicclassSurfaceimplementsParcelable{publicSurface(){mCanvas=newCompatibleCanvas();}privateclassCompatibleCanvasextendsCanvas}SurfaceinstancescanbewrittentoandrestoredfromaParcel.
SurfaceinstancescanbewrittentoandrestoredfromaParcel.
"flatten""unflatten"transmitDeliveringargumentsofmethodPropertiesCancombine2D/3DsurfacesandsurfacesfrommultipleapplicationsSurfacespassedasbuffersviaBinderIPCcallsCanuseOpenGLESand2DhardwareacceleratorforitscompositionsDouble-bufferingusingpage-flipAndroidSurfaceFlingerEverythingisaroundBinderEverythingisaroundBinderCamera+SurfaceFlinger+BinderReferenceInter-processcommunicationofAndroid,TetsuyukiKobayashi淺談Android系統進程間通信(IPC)機制Binder中的Server和Client獲得ServiceManager接口之路http://blog.
goggb.
com/post=1580AndroidBinder–AndroidInterprocessCommunication,ThorstenSchreiberDesignPatternsintheAndroidFramework,Prof.
Sheng-DeWanghttp://0xlab.
org
Pia云商家在前面有介绍过一次,根据市面上的信息是2018的开办的国人商家,原名叫哔哔云,目前整合到了魔方云平台。这个云服务商家主要销售云服务器VPS主机业务和服务,云服务器采用KVM虚拟架构 。目前涉及的机房有美国洛杉矶、中国香港和深圳地区。洛杉矶为crea机房,三网回程CN2 GIA,自带20G防御。中国香港机房的线路也是CN2直连大陆,比较适合建站或者有游戏业务需求的用户群。在这篇文章中,简...
数脉科技(shuhost)8月促销:香港独立服务器,自营BGP、CN2+BGP、阿里云线路,新客立减400港币/月,老用户按照优惠码减免!香港服务器带宽可选10Mbps、30Mbps、50Mbps、100Mbps带宽,支持中文本Windows、Linux等系统。数脉香港特价阿里云10MbpsCN2,e3-1230v2,16G内存,1T HDD 或 240G SSD,10Mbps带宽,IPv41个,...
tmhhost放出了2021年的端午佳节+618年中大促的优惠活动:日本软银、洛杉矶200G高防cn2 gia、洛杉矶三网cn2 gia、香港200M直连BGP、韩国cn2,全都是高端优化线路,所有这些VPS直接8折,部分已经做了季付8折然后再在此基础上继续8折(也就是6.4折)。 官方网站:https://www.tmhhost.com 香港BGP线路VPS ,200M带宽 200M带...
android5.1为你推荐
2021年中国城镇污泥处理处置技术与应用高级研讨会支持ipadipad上网新买的ipad怎么用。什么装程序 怎么上网google图片搜索如何用google搜索空间照片联通iphone4iphone4想换联通的卡 是普通联通的卡都能开通3G么 还是得换联通3G卡 联通都有什么套餐 我是北京的win7关闭135端口win7系统怎么关闭135端口?网上很多方法都不好用!迅雷雷鸟迅雷会员每日免费抽奖,抽中迅雷的雷鸟披肩了,要钱吗google搜图google自定义搜索是什么?怎么用卡巴斯基好用吗卡巴斯基好吗altools.u32为什么我做的Authorware在打包后不是全屏的?
网站空间域名 四川虚拟主机 花生壳免费域名 新加坡服务器 美国主机推荐 外国域名 双11抢红包攻略 京东商城0元抢购 e蜗 免费美国空间 服务器监测 网站在线扫描 华为云盘 cdn网站加速 买空间网 国外代理服务器 重庆联通服务器托管 zcloud reboot 建站论坛 更多