之路android

android5.1  时间:2021-02-14  阅读:()
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

创梦网络-四川一手资源高防大带宽云服务器,物理机租用,机柜资源,自建防火墙,雅安最高单机700G防护,四川联通1G大带宽8.3W/年,无视UDP攻击,免费防CC

? ? ? ?创梦网络怎么样,创梦网络公司位于四川省达州市,属于四川本地企业,资质齐全,IDC/ISP均有,从创梦网络这边租的服务器均可以****,属于一手资源,高防机柜、大带宽、高防IP业务,另外创梦网络近期还会上线四川联通大带宽,四川联通高防IP,一手整CIP段,四川电信,联通高防机柜,CN2专线相关业务。成都优化线路,机柜租用、服务器云服务器租用,适合建站做游戏,不须要在套CDN,全国访问快...

DMIT$10.9/月,日本VPS/三网直连/1核1.5G内存/20GB存储/1Gbps端口

优惠码年付一次性5折优惠码:TYO-Lite-Open-Beta-1y-50OFF永久8折优惠码:TYO-Lite-Open-Beta-Recur-20OFF日本vpsCPU内存SSD流量带宽价格购买1核1.5G20 GB4 TB1Gbps$10.9/月购买2核2 G40 GB6 TB1Gbps$16.9/月购买2核4 G60 GB8 TB1Gbps$21.9/月购买4核4 G80 GB12 TB...

RAKsmart美国VPS上市,活动期间5折抢购仅$30,$1.99/月

RAKsmart机房将于7月1日~7月31日推出“年中大促”活动,多重惊喜供您选择;爆款I3-2120仅30美金秒杀、V4新品上市,活动期间5折抢购、爆款产品持续热卖、洛杉矶+硅谷+香港+日本站群恢复销售、G口不限流量产品超低价热卖。美国VPS、日本VPS及香港VPS享全场7折优惠;爆款VPS $ 1.99/月限量秒杀,10台/天,售完即止, VPS 7折优惠码:VPS-TP-disRAKsmar...

android5.1为你推荐
公开微信5学生微信5Committeesios11三星itunes水土保持ios8支持ipad城乡居民社会养老保险人脸识别生存认证photoshop技术photoshop技术对哪些工作有用?x-routerX-TRAlL是什么意思icloudiphone自己用icloud把iPhone抹掉了.激活却不是自己的id怎么破
虚拟主机评测 未注册域名查询 xenvps winscp 国外主机 directspace 哈喽图床 表单样式 日本空间 卡巴斯基官方免费版 ftp教程 seednet ntfs格式分区 129邮箱 国外代理服务器软件 美国堪萨斯 gtt 服务器硬件防火墙 网站在线扫描 阿里云邮箱登陆地址 更多