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

hosthatch:14个数据中心15美元/年

hosthatch在做美国独立日促销,可能你会说这操作是不是晚了一个月?对,为了准备资源等,他们拖延到现在才有空,这次是针对自己全球14个数据中心的VPS。提前示警:各个数据中心的网络没有一个是针对中国直连的,都会绕道而且ping值比较高,想买的考虑清楚再说!官方网站:https://hosthatch.com所有VPS都基于KVM虚拟,支持PayPal在内的多种付款方式!芝加哥(大硬盘)VPS5...

月神科技 国内上新成都高防 全场八折促销续费同价!

月神科技是由江西月神科技有限公司运营的一家自营云产品的IDC服务商,提供香港安畅、香港沙田、美国CERA、成都电信等机房资源,月神科技有自己的用户群和拥有创宇认证,并且也有电商企业将业务架设在月神科技的平台上。本次带来的是全场八折促销,续费同价。并且上新了国内成都高防服务器,单机100G集群1.2T真实防御,上层屏蔽UDP,可定制CC策略。非常适合网站用户。官方网站:https://www.ysi...

Sharktech鲨鱼服务器商提供洛杉矶独立服务器促销 不限流量月99美元

Sharktech(鲨鱼服务器商)我们还是比较懂的,有提供独立服务器和高防服务器,而且性价比都还算是不错,而且我们看到有一些主机商的服务器也是走这个商家渠道分销的。这不看到鲨鱼服务器商家洛杉矶独立服务器纷纷促销,不限制流量的独立服务器起步99美元,这个还未曾有过。第一、鲨鱼机房服务器方案洛杉矶机房,默认1Gbps带宽,不限流量,自带5个IPv4,免费60Gbps / 48Mpps DDoS防御。C...

android5.1为你推荐
考试chromehttp://www.huajinsc.cn/formgraphIOJsios8iexplore.exe应用程序错误iexplore.exe应用程序错误x-routerX-TRAlL是什么意思iphonewifi为什么我的苹果手机连不上wifi重庆电信宽带管家电信的宽带上网助手是什么?联通iphone4iphone4想换联通的卡 是普通联通的卡都能开通3G么 还是得换联通3G卡 联通都有什么套餐 我是北京的迅雷快鸟迅雷快鸟这种强盗软件不违规吗?
个人虚拟主机 cybermonday sugarhosts 荷兰服务器 美国翻墙 info域名 debian6 国外免费空间 java虚拟主机 微信收钱 北京双线机房 183是联通还是移动 四核服务器 789电视剧 域名与空间 云营销系统 国外代理服务器 香港ip asp介绍 带宽测速 更多