developedandroid

android5.1  时间:2021-02-14  阅读:()
AndroidDynamicLinker-MarshmallowWANGZhenhua,i@jackwish.
netAbstractDynamiclinker,linkssharedlibrariestogethertobeabletorun,hasbeenafundamentalmechanisminmodernoperatingsystemandrichsoftwareecosystemoverthepastdecades.
Dynamiclinkerisalwayshighlyplatform-customizedsinceit'scoupledwithbinaryformatofasystem.
ThisarticleintroducesthebasicconceptionofdynamiclinkerandtakesAndroid(Marshmallow)dynamiclinkerasexampletodiscusstheimplementation.
IntroductionDynamicLinkOpenanyprogramminglanguagebook,"HelloWorld"isusuallytherstcodeexample.
TheCexamplebelowwhichwearefamiliarwithisrelatedwithdynamiclink.
ThelifecycleofthiscodeisasFigure1(memoryrelatedpartisinbluewhilesymbolrelatedisinpurple).
#includeintmain(){printf("HelloWorld!
\n");return0;}Asweknow,functionsneedtobedeclaredanddenedbeforeuse.
Forthe"HelloWorld"example,printf()isdeclaredinstdio.
handtheimplementationisinsharedlibrarylibc.
so.
Theprocedureoflocatingthedeclarationiscompiling(pre-processmoreprecisely)whilelocatingtheimplementationislinking.
Therearetwocategoriesoflinking-staticlinkinganddynamiclinking-ofwhichthedierenceisthetimethelinkingprocedureisperformed,asFigure1demonstrated.
Staticlinkingisperformedbycompilertool-chain,gccexample.
c-staticonLinuxisanexample.
Astaticlinkedbinaryrunswithouttheneedtorelocate1symbol-printfisasitsself-denedfunction.
Whenthebinaryhello.
elfisexecuted,operatingsystemonlyneedstoloaditintomemory.
Dynamiclinkingisperformedatruntimebydynamiclinker.
Atcompiletime,compilertool-chaingeneratesdynamiclinkedbinaryhello.
elfwhichcontainstheinformationthatitdependsonlibc.
sofortheimplementationofprintf.
Atruntime,dynamiclinkerloadshello.
elf,readsthedependentdata,loadslibc.
sointomemory,andllstheaddressofprintfintohello.
elf.
Inthisway,themainfunctioncancorrectlycallsprintf.
Figure1:printfExampleofLinkWiththeabilityofdynamiclinking,developerscouldcreateandsharelibraries.
Libraryauthorcouldupdateinternalimplementationwithoutneedtoinformusers,whilelibraryusersdon'tneedtore-deploytheirapplicationsunlesslibraryinterfaceshavechange.
ThisistheinfrastructureofAPI(ApplicationProgramInterface)!
LibraryDependencyDiverseprogramsrunningonmoderncomputersystemareconstructedbylibrariestodiminishdevelopmenteortandmemoryandstorageconsumption.
2Dynamiclinkerisresponsibleforlocatinglibrariesfromstorage,loadingthemintomemoryandlinkingthereferenceofthem.
Developerscreateprogramorlibrarybasedondierentlibraries.
OnetypicaldependencyoflibraryisasFigure2(libcutils.
soofAndroid,libdl.
soisignored).
Alibraryauthorknowswhichlibrariesisdependeduponbyhislibrary,andrecordsthedependencyinthelibrary(DT_NEEDEDtableforELFformatlibrary).
Atruntime,dynamiclinkerre-buildsthedependencyofanexecutableorsharedlibraryandlinksthebinaryagainstitsdependency.
Figure2:Dependencyoflibcutils.
soThedependencyismostlyaDAG(DirectedAcyclicGraph).
Fordynamicsystemsupportingrecursivedependent,thedependencycouldbeaDCG(DirectedCyclicGraph).
Nomatterwhatkindthegraphis,dynamiclinkercansimplyvisitallnodesinthegraph,locate,loadandlinkthem.
Inadependencygraph,thereisoneandonlyonenodewhichhasnoentryedge,calledroot.
There-buildingprocedureofadependencyistraversingthegraphinDFS(DepthFirstSearch)orBFS(BreadthFirstSearch)orderstartingwithroot.
Figure2isaBFSexample.
Inthisarticle,ourdiscussionisbasedontheBFSdependency.
DocumentStructureWetakethedynamiclinkerofAndroidastheimplementationexample.
Itispartofbionic,thestandardClibrarydevelopedbyGoogleforitsAndroidoperatingsystem.
AndroidisbasedonLinuxofwhichthesharedlibraryformatisELF.
DynamiclinkerprovideslinkingserviceforAndroidsystemandapplicationsdeployedwithJNIcapability.
WerstlyintroducethebasicmechanismofdynamiclinkerofAndroid.
Thentalkabouthowspecialfeaturesisimplemented.
Afterthat,thebootstrapofdynamiclinkerisdiscussed.
And,atlast,comingtothetrickypartoflibrarydependency.
3DynamicLinkingMechanismInAndroid,dynamiclinkerisinvokedwhenSystem.
loadLibrary()isexecutedinJavaordlopen()isexecutedinnativecode.
ForJavacode,Dalvik/Android-runtimecallsintodynamiclinkerjustlikedlopen()eventually.
StartingwithLollipopMR1(OurdiscussionisbasedonMarshmallow),Androiddynamiclinkingistwo-phase:libraryloadingandlibraryrelocation.
AsFigure3shows,thelefthalfisloadingwhiletherighthalfislinking.
Duringthelibraryloadingprocedure,dynamiclinkerre-buildsthelibraryde-pendency,loadsalllibrariesofitintomemory.
Thelibraryrelocationprocedurelinksthedependency.
WetalkabouttheimportantdatastructureofAndroiddynamiclinkerrstly.
Figure3:WorkowofAndroidDynamicLinkerDataStructurePersistentDataStructureDynamiclinkerofAndroidhastwopersistentdatastructureduringthelifetimeofanapplication/program-LSPath(LibrarySearchPaths)andALList(Already-loadedLibraryList).
4LSPatharethedirectorieswherelibrariesarestored.
Dynamiclinkertraversesthesepathstohuntforalibrary.
Thesepathsarecriticaltothelibrarylocatingandaresequencedinpriority.
ALListisalistofsoinfowhichisusedtomaintainmetadataofloadedlibraries(ELFdataandmemorylayoutforexample).
DynamiclinkerobtainsdatafromALListacrossdierentlibraryloadingandlinking.
ALListgrowsandshortenswhenlibraryisloadingandunloadingrespectively.
PersistentdatastructuresareatthetopsideofFigure3.
"Storage"inFigure3meansLSPathsomehow.
TemporaryDataStructureNaturally,manytemporarydatastructuresareusedduringloadinglibrary.
Amongthem,themostimportanttwoareload_tasksandlocal_group.
Bothofthempresentthelibrarydependency.
load_tasksisaqueuecontainingthelibrariestobeloaded-asubsetlibrariesoflibrarydependencywhichhaveNOTbeenloadedintomemoryyet.
load_tasksdequeueswhenlinkerbeginstosearchalibraryandenqueuesthedependentlibrariesjustparsed(fromDT_NEEDEDtableofanELFformatlibrary).
Afterallthetreehasbeenloaded(load_tasksisemptyatthistime),local_groupisconstructedandusedforrelocation.
local_groupisaqueueofsoinfoandrepresentslibrarydependencyinBFSorder.
(Anothersimilardatastructurecalledglobal_groupwillbediscussedin"SpecialFeatures"section.
)TemporarydatastructuresarelistedatthebottomsideofFigure3.
LibraryLoadingProcedureAtthebeginning,thelibraryrequestedbyoperatingsystem-root-isaddedtoload_tasks,asFigure3.
Duringtheprocedureoflibraryloading,dynamiclinkercontinuallyloadsalllibrariesinload_tasksandupdatesitifnecessary,asthelefthalfpartofFigure3.
Alllibrariesinthelibrarydependencywillbeloadedwhenthisprocedureisnished.
LibraryLocatingDynamiclinkerextractsonename/pathfromload_tasks,andopensdirectlyifit'sabsolutepathortraversesLSPathtohuntforthelibraryotherwise.
Whenthelibraryislocatedandopened,itcouldbeasystemlibraryoraapplibrary.
systemlibraryarelibrariesloadedfromsystemlibrarypaths5like/system/lib;applibraryareloadedfromapplicationlibrarypathslike/data/data/com.
example.
app/lib.
BeforeapplicationisforkedfromZygote,dynamiclinkeronlysearchesforlibraryundersystemlibrarypaths.
Afterapplicationisforkedandlibrarypathsareset,dynamiclinkersearchesunderapplicationpathsrstly,thensystemlibrarypaths.
LibraryLoadingAfterlibraryisopenedfromstorage,andbeforeloadsthelibraryintomemory,linkerwantstoverifywhetherthelejustopenedisavalidsharedlibrary.
ItperformscheckbasedonELFdata:magicnumber,32/64bit,little/bigendian,machinetypeandsoon.
Ifanythingwrong,thislibraryandthelibrarydependencywillbeunloaded.
Ifvalidationpasses,dynamiclinkerreadsthelibraryheaderandloadsallloadablesegmentsintomemory.
ItcalculatestheneededmemorysizeofthelibrarybycheckingPT_LOADtablesofprogramheader.
Thememoryallocationissimplyviammap.
(InandbeforeJellyBean,thelibrarymemoryismanagedbyabuddymemoryallocationsystemsystem)LibraryPre-link"Pre-link"intendstobuildonemoreleveloflibrarydependencybyreadingthedependency(dynamicDT_NEEDEDsection)ofalibrary.
AlllibrarynamesrecordedinDT_NEEDEDtableareaddedtoload_tasksandtobeloaded.
It'seasilytoseethatsamelibrary(name)maybeaddedtoload_tasksmanytimeswhenloadsalibrary.
DynamiclinkertraversesALListtocheckifthelibraryhasalreadybeloadedintomemorybynameandi-node,beforeandafteropenthatlibrary.
Iffound,dynamiclinkerdropsthatload_tasksnodeandfetchesnext.
SotherearenoduplicateloadedlibrariesinALList.
TheoccurrencetimeofreadingdependencyofalibraryhaschangedacrossthedevelopmentofAndroid.
BeforeLollipop-MR1,librarylinkingisDFSwhichloadsandlinksthelibrarydependencyrecursively.
BeginningwithLollipop-MR1,librarylinkingchangestoBFS.
Thischangemakesthelibrarylinkingatwo-stageprocedure,alllibrariesinalibrarydependencyhasbeenloadedintomemorybeforeanyofthemhasbeenrelocated.
LibraryRelocationProcedureAfterlibraryloadingprocedure,thedependentrelationshipoflibariesarerecordedinsoinfo.
Dynamiclinkerreadssoinfobeginningwithroottobuild6local_group.
Relocationisperformedonlocal_group.
Mainloopofrelocationdequeuesalibraryfromlocal_groupandrelocatesit.
local_groupisBFSbuilt,sotherelocationisBFStoo.
Whenresolvingasymbolofalibrary,dynamiclinkerwalkstheRelocationSection,atableofallthingsneededtoberelocated(DT_RELorDT_RELAofELF),ofasharedlibrary.
Foreachrelocationentry,linkerreadsthesymbolindexandconvertsittosymbolname.
Withthename,linkersearchesthedenitionofitinthedependencytree-beginwiththelibraryitself,thenglobal_group(see"ExtensionofDynamicLinker")andlocal_group.
Whensearchesasymboldenitioninalibrary,dynamiclinkerchecksthesymboltable(DT_SYMTABofELF)ofit.
Thereisaccelerationmethodsforthetablelookup,DT_HASHofELFisahashlistwhichcontainsallthe"exported"or"imported"symbolofalibrary.
Thelibraryrelocationprocedureisintuitive.
Whenit'sdone,dynamiclinkercallsalllibraryconstructorsinthedependency.
Afterconstructorsarenished,thelibraryisloaded,dynamiclinkerreturnsahandlerofthislibrarytouser.
ExtensionofDynamicLinkerDynamiclinkinghassomeextensionstosupportvariousscenarios,andAndroidhasextendeddynamiclinkingfunctionsforspecicpurpose.
GenericDynamicLinkGlobalLibraryWhenalibraryisdeclaredasa"globallibrary",loadedwiththeagRTLD_GLOBAL,thedenitionofthesymbolofthelibraryhasthehighestpriorityforalllibrariesloadedafterit.
Androiddynamiclinkerbuildstheglobal_groupeverytimeatthebeginningwhenloadalibrary.
Whenrelocatingasymbol,theglobal_groupisrstlylookedup-"globallibrary"canoverlaysthesymboldenitionofthelibrariestobeloadedafterwards.
PreloadLibraryWhenabinaryexecutedwithagLD_PRELOAD.
Theselibrarieswillbeloadedbeforethebinaryisreallyexecuted.
Androiddynamiclinkerpreloadstheselibrarieswhenitinitializes.
TheselibrarieswillcarrytheagRTLD_GLOBAL.
Afterthat,"preloadlibrary"isjustlike"globallibrary".
LD_PRELOADonlytakeseectforpurenativeprograms.
7AndroidExtendedDynamicLinkAndroidsystemextendsdynamiclinkingtoimproveexperiencewhenloadslibrariesfrombothJavaandnative.
TheAPIisandroid_dlopen_ext().
TillM,featuresofthisextensionisasbelow,mostofthemareprettyeasytounderstand.
Justcopyfromthesourcele.
.
.
.
Thedatastructureofthisextensionislikethis:typedefstruct{uint64_tflags;void*reserved_addr;size_treserved_size;intrelro_fd;intlibrary_fd;off64_tlibrary_fd_offset;}android_dlextinfo;LibraryMemoryRelatedANDROID_DLEXT_RESERVED_ADDRESS:Whenset,thereserved_addrandreserved_sizeeldsmustpointtoanalready-reservedregionofaddressspacewhichwillbeusedtoloadthelibraryifitts.
Ifthereservedregionisnotlargeenough,theloadwillfail.
ANDROID_DLEXT_RESERVED_ADDRESS_HINT:AsDLEXT_RESERVED_ADDRESS,butifthereservedregionisnotlargeenough,thelinkerwillchooseanavailableaddressinstead.
LibraryOpeningRelatedANDROID_DLEXT_USE_LIBRARY_FD:Instructdlopentouselibrary_fdinsteadofopeninglebyname.
Thelenameparameterisstillusedtoidentifythelibrary.
ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET:Ifopeningalibraryusinglibrary_fdreaditstartingatlibrary_fd_offset.
ThisagisonlyvalidwhenANDROID_DLEXT_USE_LIBRARY_FDisset.
ANDROID_DLEXT_FORCE_LOAD:Whenset,donotcheckifthelibraryhasalreadybeenloadedbylestat(2)s.
ThisagallowsforcedloadingofthelibraryinthecasewhenforsomereasonmultipleELFlessharethesamelename(becausethealready-loadedlibraryhasbeenremovedandoverwritten,forexample).
Notethatifthelibraryhasthesamedt_sonameasanoldoneandsomeotherlibraryhasthesonameinDT_NEEDEDlist,therstonewillbeusedtoresolveanydependencies.
8LibraryRelocationRelatedANDROID_DLEXT_WRITE_RELRO:Whenset,writetheGNURELROsectionofthemappedlibrarytorelro_fdafterrelocationhasbeenperformed,toallowittobereusedbyanotherprocessloadingthesamelibraryatthesameaddress.
ThisimpliesANDROID_DLEXT_USE_RELRO.
ANDROID_DLEXT_USE_RELRO:Whenset,comparetheGNURELROsectionofthemappedlibrarytorelro_fdafterrelocationhasbeenperformed,andreplaceanyrelocatedpagesthatareidenticalwithaversionmappedfromthele.
BootstrapofDynamicLinkerDynamiclinkerisdesignedto"link"allrelocatablebinaries,andmustmakeitselflookslikelibdl.
sotorelocatables-thelibdl.
sobinaryisjustadummylibrarywhichmakesldofcompilertool-chainhappy.
Dynamiclinkerisstaticallylinkedatcompiletimeanddoesn'tdependonanyotherresourcesexceptsystemcall.
Theself-relocatingandfakinglibdl.
soisBootstrap.
ThebootstrapofAndroiddynamiclinkerisdividedintotwosteps:1.
Initialize:hardcodedtorelocatelinkeritself.
2.
Post-initialize:prepare"linkerruntime"forlibraryloading.
InitializeDuringthisstage,allexecutedcodeisstaticallyrelocated.
Noexternvariable,externfunction,orGOTaccess.
Calledfrombegin.
SandwillcallPost-initializefunctionsafterwards.
Primaryoperationsarerelocatinglinkeritselfandcreatingthedummylibdl.
sosoinfo.
Relocatinglinkeritselfisasadstory,everythingishand-obtained.
Afterthesoinfoiswell-setuped(memoryrelatedmostly),therealrelocationisconducted.
Thenconstructorsoflinkerarecalledtoinitializelinker'sglobalvariables.
Creatingdummylibdl.
sosoinfoismainlysetandupdatethereferenceofthesoinfotohard-codedarray,symboltableforexample.
Thissoinfonodeoflibdl.
soisalwaystherstnodeofALList.
Withtheseworkdone,linkerisrelocated.
9Post-initializeAfterself-relocated,dynamiclinkerrelocatessomain-themainprocess-Zygote.
BeforerelocatesZygote,linkerasksforruntimevariablefromsystemlikeLD_LIBRARY_PATHandLD_PRELOAD.
Andthen,itrelocatesZygote.
WithZygoterelocated,loadalllibrariesdeclaredinLD_PRELOAD.
Witheverythingdone,linkernishesBootstrapandjumpstoZygote.
LibraryDependencyAsdiscussedinthebeginning,onetaskofdynamiclinkeristore-buildlibrarydependency.
There-buildingprocedureissensitivetoruntimeenvironmentinsomecornerscenario.
Figure4:TrickyLibraryDepdendencyGenerationofAndroidConsiderthattherearetwosetsoflibraries-set1andset2.
Somelibrariesinthesetwosetssharesamenamebuthavedierentdenitions.
Atthebeginning,onlyset1canbeloaded,andthenbothset1andset2canbeloaded.
Thetrickis,inanydependency,thelibraryloadedinphase1couldonlydependsonlibraryinset1,asFigure4.
Thisisbecausewheneverlibraryinset1isneeded,dynamiclinkersimplyreusesthesoinfoofit.
LD_PRELOADintraditionalLinuxandlibrariesloadedbeforeZygoteforksinAndroidaresuchscenarios.
Thisisneformostdevelopers,butcouldimpactsomeemulationsystem.
10SummaryDynamiclinkerre-buildsthedependencyofexecutables,locates,loadsandlinksit.
It'sfundamentalinfrastructureofmodernoperatingsystemandsensitivetorunningenvironment.
Dynamiclinkingisusuallyhighplatformcustomizedandrequiresbootstrap.
AndroidNincludesnamespacechangestopreventloadingofnon-publicAPIs.
ThisfeatureheavilyimpactstheecosystemofAndroid.
Intheory,namespaceenables"virtualization"indynamiclinking.
Thedynamiclinkingwediscussedinthisdocumentin"processinternal",whilenamespacecanbuildseveralvirtualspace-namespace-fordynamiclinkinginoneprocess,makingthedynamiclink"namespaceinternal".
Wewillrefertonamespaceinthefuture.
11

华纳云新人下单立减40元/香港云服务器月付60元起,香港双向CN2(GIA)

华纳云(HNCloud Limited)是一家专业的全球数据中心基础服务提供商,总部在香港,隶属于香港联合通讯国际有限公司,拥有香港政府颁发的商业登记证明,保证用户的安全性和合规性。 华纳云是APNIC 和 ARIN 会员单位。主要提供数据中心基础服务、互联网业务解决方案, 以及香港服务器租用、香港服务器托管、香港云服务器、美国云服务器,云计算、云安全技术研发等产品和服务。其中云服务器基于成熟的 ...

hostkvm:7折优惠-香港VPS韩国VPS,8折优惠-日本软银、美国CN2 GIA、新加坡直连VPS

hostkvm本月对香港国际线路的VPS、韩国CN2+bgp线路的VPS正在做7折终身优惠,对日本软银线路、美国CN2 GIA线路、新加坡直连线路的VPS进行8折终身优惠促销。所有VPS从4G内存开始支持Windows系统,当然主流Linux发行版是绝对不会缺席的!官方网站:https://hostkvm.com香港国际线路、韩国,7折优惠码:2021summer日本、美国、新加坡,8折优惠码:2...

spinservers春节优惠:$149/月10Gbps圣何塞服务器-2*E5-2630Lv3 CPU,256G内存,2*1.6T SSD硬盘

spinservers是Majestic Hosting Solutions LLC旗下站点,商家提供国外服务器租用和Hybrid Dedicated等产品,数据中心包括美国达拉斯和圣何塞机房,机器默认10Gbps端口带宽,高配置硬件,支持使用PayPal、信用卡、支付宝或者微信等付款方式。农历春节之际,商家推出了几款特别促销配置,最低双路E5-2630Lv3机器每月149美元起,下面列出几款机器...

android5.1为你推荐
传感器安卓4尊敬的浪潮英信服务器用户:交换机route导致卡巴斯基followgoogle支持ipad重庆宽带测速重庆联通宽带测速的网址是好多呢?勒索病毒win7补丁怎么删除 防勒索病毒 打的补丁win10关闭445端口win10家庭版怎么禁用445端口iphone连不上wifi苹果iphone6/plus wifi连接不上怎么办
海外域名 网站备案域名查询 inmotionhosting windows主机 rackspace idc测评网 asp免费空间申请 hinet 电信虚拟主机 昆明蜗牛家 t云 电信主机 如何注册阿里云邮箱 环聊 中国联通宽带测速 腾讯网盘 小夜博客 葫芦机 新网dns 湖南铁通 更多