之路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

NameCheap新注册.COM域名$5.98

随着自媒体和短视频的发展,确实对于传统的PC独立网站影响比较大的。我们可以看到云服务器商家的各种促销折扣活动,我们也看到传统域名商的轮番新注册和转入的促销,到现在这个状态已经不能说这些商家的为用户考虑,而是在不断的抢夺同行的客户。我们看到Namecheap商家新注册域名和转入活动一个接一个。如果我们有需要新注册.COM域名的,只需要5.98美元。优惠码:NEWCOM598。同时有赠送2个月免费域名...

极光KVM美国美国洛杉矶元/极光kvmCN7月促销,美国CN2 GIA大带宽vps,洛杉矶联通CUVIP,14元/月起

极光KVM怎么样?极光KVM本月主打产品:美西CN2双向,1H1G100M,189/年!在美西CN2资源“一兆难求”的大环境下,CN2+大带宽 是很多用户的福音,也是商家实力的象征。目前,极光KVM在7月份的促销,7月促销,美国CN2 GIA大带宽vps,洛杉矶联通cuvip,14元/月起;香港CN2+BGP仅19元/月起,这次补货,机会,不要错过了。点击进入:极光KVM官方网站地址极光KVM七月...

快云科技:夏季大促销,香港VPS7.5折特惠,CN2 GIA线路; 年付仅不到五折巨惠,续费永久同价

快云科技怎么样?快云科技是一家成立于2020年的新起国内主机商,资质齐全 持有IDC ICP ISP等正规商家。我们秉承着服务于客户服务于大众的理念运营,机器线路优价格低。目前已注册用户达到5000+!主营产品有:香港弹性云服务器,美国vps和日本vps,香港物理机,国内高防物理机以及美国日本高防物理机!产品特色:全配置均20M带宽,架构采用KVM虚拟化技术,全盘SSD硬盘,RAID10阵列, 国...

android5.1为你推荐
界面winrar5loadedios仪器win7思科flash之路android支持ipad支持ipad用itunes备份iphone怎么从itunes备份恢复重庆电信宽带测速重庆电信光纤宽带网络,内外网络和电脑等设备都没发生变化的情况下,办理了从20M提速到100M业务。micromediaMacromedia翻译成中文是什么?
视频空间租用 美国vps评测 独享100m siteground themeforest mediafire下载工具 轻博客 卡巴斯基永久免费版 个人免费空间 cpanel空间 权嘉云 老左来了 东莞数据中心 卡巴斯基免费试用 台湾谷歌 银盘服务 云营销系统 免费的asp空间 游戏服务器出租 lamp架构 更多