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

DiyVM(50元起)老牌商家,香港沙田CN2直连vps/不限流量/五折终身优惠

diyvm怎么样?diyvm是一家国内成立时间比较久的主机商家了,大约在6年前站长曾经用过他家的美国机房的套餐,非常稳定,适合做站,目前商家正在针对香港沙田机房的VPS进行促销,给的是五折优惠,续费同价,香港沙田机房走的是CN2直连的线路,到大陆地区的速度非常好,DiyVM商家采用小带宽不限流量的形式,带宽2Mbps起步,做站完全够用,有需要的朋友可以入手。diyvm优惠码:五折优惠码:OFF50...

IntoVPS:按小时计费KVM月费5美元起($0.0075/小时),6个机房可选

IntoVPS是成立于2004年的Hosterion SRL旗下于2009年推出的无管理型VPS主机品牌,商家提供基于OpenStack构建的VPS产品,支持小时计费是他的一大特色,VPS可选数据中心包括美国弗里蒙特、达拉斯、英国伦敦、荷兰和罗马尼亚等6个地区机房。商家VPS主机基于KVM架构,最低每小时0.0075美元起($5/月)。下面列出几款VPS主机配置信息。CPU:1core内存:2GB...

日本CN2独立物理服务器 E3 1230 16G 20M 500元/月 提速啦

提速啦的来历提速啦是 网站 本着“良心 便宜 稳定”的初衷 为小白用户避免被坑 由赣州王成璟网络科技有限公司旗下赣州提速啦网络科技有限公司运营 投资1000万人民币 在美国Cera 香港CTG 香港Cera 国内 杭州 宿迁 浙江 赣州 南昌 大连 辽宁 扬州 等地区建立数据中心 正规持有IDC ISP CDN 云牌照 公司。公司购买产品支持3天内退款 超过3天步退款政策。提速啦的市场定位提速啦主...

android5.1为你推荐
"2018年中文图书第5期新书通报",,,,,santeeset盗版itunes支持ipadwin7关闭445端口win7系统怎么关闭445和135这两个端口windows键是哪个Windows键是哪个键啊?itunes备份怎么使用iTunes备份iphonewifi为什么我的苹果手机连不上wifi联通版iphone4s怎么区分iphone4s电信版和联通版google中国地图求教谷歌中国地图~手机如何使用?
域名邮箱 过期备案域名查询 租服务器价格 美国vps评测 域名备案批量查询 最便宜虚拟主机 qq云存储 镇江联通宽带 本网站在美国维护 昆明蜗牛家 服务器是干什么用的 空间租赁 西安服务器托管 中国电信网络测速 大化网 黑科云 乐视会员免费领取 双11促销 腾讯云平台 美国asp空间 更多