MachOObjectFile.cpp 181 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780
  1. //===- MachOObjectFile.cpp - Mach-O object file binding -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the MachOObjectFile class, which binds the MachOObject
  10. // class to the generic ObjectFile wrapper.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/None.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/ADT/StringSwitch.h"
  19. #include "llvm/ADT/Triple.h"
  20. #include "llvm/ADT/Twine.h"
  21. #include "llvm/BinaryFormat/MachO.h"
  22. #include "llvm/BinaryFormat/Swift.h"
  23. #include "llvm/Object/Error.h"
  24. #include "llvm/Object/MachO.h"
  25. #include "llvm/Object/ObjectFile.h"
  26. #include "llvm/Object/SymbolicFile.h"
  27. #include "llvm/Support/DataExtractor.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/Errc.h"
  30. #include "llvm/Support/Error.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. #include "llvm/Support/FileSystem.h"
  33. #include "llvm/Support/Format.h"
  34. #include "llvm/Support/Host.h"
  35. #include "llvm/Support/LEB128.h"
  36. #include "llvm/Support/MemoryBuffer.h"
  37. #include "llvm/Support/Path.h"
  38. #include "llvm/Support/SwapByteOrder.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include <algorithm>
  41. #include <cassert>
  42. #include <cstddef>
  43. #include <cstdint>
  44. #include <cstring>
  45. #include <limits>
  46. #include <list>
  47. #include <memory>
  48. #include <system_error>
  49. using namespace llvm;
  50. using namespace object;
  51. namespace {
  52. struct section_base {
  53. char sectname[16];
  54. char segname[16];
  55. };
  56. } // end anonymous namespace
  57. static Error malformedError(const Twine &Msg) {
  58. return make_error<GenericBinaryError>("truncated or malformed object (" +
  59. Msg + ")",
  60. object_error::parse_failed);
  61. }
  62. // FIXME: Replace all uses of this function with getStructOrErr.
  63. template <typename T>
  64. static T getStruct(const MachOObjectFile &O, const char *P) {
  65. // Don't read before the beginning or past the end of the file
  66. if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
  67. report_fatal_error("Malformed MachO file.");
  68. T Cmd;
  69. memcpy(&Cmd, P, sizeof(T));
  70. if (O.isLittleEndian() != sys::IsLittleEndianHost)
  71. MachO::swapStruct(Cmd);
  72. return Cmd;
  73. }
  74. template <typename T>
  75. static Expected<T> getStructOrErr(const MachOObjectFile &O, const char *P) {
  76. // Don't read before the beginning or past the end of the file
  77. if (P < O.getData().begin() || P + sizeof(T) > O.getData().end())
  78. return malformedError("Structure read out-of-range");
  79. T Cmd;
  80. memcpy(&Cmd, P, sizeof(T));
  81. if (O.isLittleEndian() != sys::IsLittleEndianHost)
  82. MachO::swapStruct(Cmd);
  83. return Cmd;
  84. }
  85. static const char *
  86. getSectionPtr(const MachOObjectFile &O, MachOObjectFile::LoadCommandInfo L,
  87. unsigned Sec) {
  88. uintptr_t CommandAddr = reinterpret_cast<uintptr_t>(L.Ptr);
  89. bool Is64 = O.is64Bit();
  90. unsigned SegmentLoadSize = Is64 ? sizeof(MachO::segment_command_64) :
  91. sizeof(MachO::segment_command);
  92. unsigned SectionSize = Is64 ? sizeof(MachO::section_64) :
  93. sizeof(MachO::section);
  94. uintptr_t SectionAddr = CommandAddr + SegmentLoadSize + Sec * SectionSize;
  95. return reinterpret_cast<const char*>(SectionAddr);
  96. }
  97. static const char *getPtr(const MachOObjectFile &O, size_t Offset) {
  98. assert(Offset <= O.getData().size());
  99. return O.getData().data() + Offset;
  100. }
  101. static MachO::nlist_base
  102. getSymbolTableEntryBase(const MachOObjectFile &O, DataRefImpl DRI) {
  103. const char *P = reinterpret_cast<const char *>(DRI.p);
  104. return getStruct<MachO::nlist_base>(O, P);
  105. }
  106. static StringRef parseSegmentOrSectionName(const char *P) {
  107. if (P[15] == 0)
  108. // Null terminated.
  109. return P;
  110. // Not null terminated, so this is a 16 char string.
  111. return StringRef(P, 16);
  112. }
  113. static unsigned getCPUType(const MachOObjectFile &O) {
  114. return O.getHeader().cputype;
  115. }
  116. static unsigned getCPUSubType(const MachOObjectFile &O) {
  117. return O.getHeader().cpusubtype;
  118. }
  119. static uint32_t
  120. getPlainRelocationAddress(const MachO::any_relocation_info &RE) {
  121. return RE.r_word0;
  122. }
  123. static unsigned
  124. getScatteredRelocationAddress(const MachO::any_relocation_info &RE) {
  125. return RE.r_word0 & 0xffffff;
  126. }
  127. static bool getPlainRelocationPCRel(const MachOObjectFile &O,
  128. const MachO::any_relocation_info &RE) {
  129. if (O.isLittleEndian())
  130. return (RE.r_word1 >> 24) & 1;
  131. return (RE.r_word1 >> 7) & 1;
  132. }
  133. static bool
  134. getScatteredRelocationPCRel(const MachO::any_relocation_info &RE) {
  135. return (RE.r_word0 >> 30) & 1;
  136. }
  137. static unsigned getPlainRelocationLength(const MachOObjectFile &O,
  138. const MachO::any_relocation_info &RE) {
  139. if (O.isLittleEndian())
  140. return (RE.r_word1 >> 25) & 3;
  141. return (RE.r_word1 >> 5) & 3;
  142. }
  143. static unsigned
  144. getScatteredRelocationLength(const MachO::any_relocation_info &RE) {
  145. return (RE.r_word0 >> 28) & 3;
  146. }
  147. static unsigned getPlainRelocationType(const MachOObjectFile &O,
  148. const MachO::any_relocation_info &RE) {
  149. if (O.isLittleEndian())
  150. return RE.r_word1 >> 28;
  151. return RE.r_word1 & 0xf;
  152. }
  153. static uint32_t getSectionFlags(const MachOObjectFile &O,
  154. DataRefImpl Sec) {
  155. if (O.is64Bit()) {
  156. MachO::section_64 Sect = O.getSection64(Sec);
  157. return Sect.flags;
  158. }
  159. MachO::section Sect = O.getSection(Sec);
  160. return Sect.flags;
  161. }
  162. static Expected<MachOObjectFile::LoadCommandInfo>
  163. getLoadCommandInfo(const MachOObjectFile &Obj, const char *Ptr,
  164. uint32_t LoadCommandIndex) {
  165. if (auto CmdOrErr = getStructOrErr<MachO::load_command>(Obj, Ptr)) {
  166. if (CmdOrErr->cmdsize + Ptr > Obj.getData().end())
  167. return malformedError("load command " + Twine(LoadCommandIndex) +
  168. " extends past end of file");
  169. if (CmdOrErr->cmdsize < 8)
  170. return malformedError("load command " + Twine(LoadCommandIndex) +
  171. " with size less than 8 bytes");
  172. return MachOObjectFile::LoadCommandInfo({Ptr, *CmdOrErr});
  173. } else
  174. return CmdOrErr.takeError();
  175. }
  176. static Expected<MachOObjectFile::LoadCommandInfo>
  177. getFirstLoadCommandInfo(const MachOObjectFile &Obj) {
  178. unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
  179. : sizeof(MachO::mach_header);
  180. if (sizeof(MachO::load_command) > Obj.getHeader().sizeofcmds)
  181. return malformedError("load command 0 extends past the end all load "
  182. "commands in the file");
  183. return getLoadCommandInfo(Obj, getPtr(Obj, HeaderSize), 0);
  184. }
  185. static Expected<MachOObjectFile::LoadCommandInfo>
  186. getNextLoadCommandInfo(const MachOObjectFile &Obj, uint32_t LoadCommandIndex,
  187. const MachOObjectFile::LoadCommandInfo &L) {
  188. unsigned HeaderSize = Obj.is64Bit() ? sizeof(MachO::mach_header_64)
  189. : sizeof(MachO::mach_header);
  190. if (L.Ptr + L.C.cmdsize + sizeof(MachO::load_command) >
  191. Obj.getData().data() + HeaderSize + Obj.getHeader().sizeofcmds)
  192. return malformedError("load command " + Twine(LoadCommandIndex + 1) +
  193. " extends past the end all load commands in the file");
  194. return getLoadCommandInfo(Obj, L.Ptr + L.C.cmdsize, LoadCommandIndex + 1);
  195. }
  196. template <typename T>
  197. static void parseHeader(const MachOObjectFile &Obj, T &Header,
  198. Error &Err) {
  199. if (sizeof(T) > Obj.getData().size()) {
  200. Err = malformedError("the mach header extends past the end of the "
  201. "file");
  202. return;
  203. }
  204. if (auto HeaderOrErr = getStructOrErr<T>(Obj, getPtr(Obj, 0)))
  205. Header = *HeaderOrErr;
  206. else
  207. Err = HeaderOrErr.takeError();
  208. }
  209. // This is used to check for overlapping of Mach-O elements.
  210. struct MachOElement {
  211. uint64_t Offset;
  212. uint64_t Size;
  213. const char *Name;
  214. };
  215. static Error checkOverlappingElement(std::list<MachOElement> &Elements,
  216. uint64_t Offset, uint64_t Size,
  217. const char *Name) {
  218. if (Size == 0)
  219. return Error::success();
  220. for (auto it = Elements.begin(); it != Elements.end(); ++it) {
  221. const auto &E = *it;
  222. if ((Offset >= E.Offset && Offset < E.Offset + E.Size) ||
  223. (Offset + Size > E.Offset && Offset + Size < E.Offset + E.Size) ||
  224. (Offset <= E.Offset && Offset + Size >= E.Offset + E.Size))
  225. return malformedError(Twine(Name) + " at offset " + Twine(Offset) +
  226. " with a size of " + Twine(Size) + ", overlaps " +
  227. E.Name + " at offset " + Twine(E.Offset) + " with "
  228. "a size of " + Twine(E.Size));
  229. auto nt = it;
  230. nt++;
  231. if (nt != Elements.end()) {
  232. const auto &N = *nt;
  233. if (Offset + Size <= N.Offset) {
  234. Elements.insert(nt, {Offset, Size, Name});
  235. return Error::success();
  236. }
  237. }
  238. }
  239. Elements.push_back({Offset, Size, Name});
  240. return Error::success();
  241. }
  242. // Parses LC_SEGMENT or LC_SEGMENT_64 load command, adds addresses of all
  243. // sections to \param Sections, and optionally sets
  244. // \param IsPageZeroSegment to true.
  245. template <typename Segment, typename Section>
  246. static Error parseSegmentLoadCommand(
  247. const MachOObjectFile &Obj, const MachOObjectFile::LoadCommandInfo &Load,
  248. SmallVectorImpl<const char *> &Sections, bool &IsPageZeroSegment,
  249. uint32_t LoadCommandIndex, const char *CmdName, uint64_t SizeOfHeaders,
  250. std::list<MachOElement> &Elements) {
  251. const unsigned SegmentLoadSize = sizeof(Segment);
  252. if (Load.C.cmdsize < SegmentLoadSize)
  253. return malformedError("load command " + Twine(LoadCommandIndex) +
  254. " " + CmdName + " cmdsize too small");
  255. if (auto SegOrErr = getStructOrErr<Segment>(Obj, Load.Ptr)) {
  256. Segment S = SegOrErr.get();
  257. const unsigned SectionSize = sizeof(Section);
  258. uint64_t FileSize = Obj.getData().size();
  259. if (S.nsects > std::numeric_limits<uint32_t>::max() / SectionSize ||
  260. S.nsects * SectionSize > Load.C.cmdsize - SegmentLoadSize)
  261. return malformedError("load command " + Twine(LoadCommandIndex) +
  262. " inconsistent cmdsize in " + CmdName +
  263. " for the number of sections");
  264. for (unsigned J = 0; J < S.nsects; ++J) {
  265. const char *Sec = getSectionPtr(Obj, Load, J);
  266. Sections.push_back(Sec);
  267. auto SectionOrErr = getStructOrErr<Section>(Obj, Sec);
  268. if (!SectionOrErr)
  269. return SectionOrErr.takeError();
  270. Section s = SectionOrErr.get();
  271. if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
  272. Obj.getHeader().filetype != MachO::MH_DSYM &&
  273. s.flags != MachO::S_ZEROFILL &&
  274. s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
  275. s.offset > FileSize)
  276. return malformedError("offset field of section " + Twine(J) + " in " +
  277. CmdName + " command " + Twine(LoadCommandIndex) +
  278. " extends past the end of the file");
  279. if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
  280. Obj.getHeader().filetype != MachO::MH_DSYM &&
  281. s.flags != MachO::S_ZEROFILL &&
  282. s.flags != MachO::S_THREAD_LOCAL_ZEROFILL && S.fileoff == 0 &&
  283. s.offset < SizeOfHeaders && s.size != 0)
  284. return malformedError("offset field of section " + Twine(J) + " in " +
  285. CmdName + " command " + Twine(LoadCommandIndex) +
  286. " not past the headers of the file");
  287. uint64_t BigSize = s.offset;
  288. BigSize += s.size;
  289. if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
  290. Obj.getHeader().filetype != MachO::MH_DSYM &&
  291. s.flags != MachO::S_ZEROFILL &&
  292. s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
  293. BigSize > FileSize)
  294. return malformedError("offset field plus size field of section " +
  295. Twine(J) + " in " + CmdName + " command " +
  296. Twine(LoadCommandIndex) +
  297. " extends past the end of the file");
  298. if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
  299. Obj.getHeader().filetype != MachO::MH_DSYM &&
  300. s.flags != MachO::S_ZEROFILL &&
  301. s.flags != MachO::S_THREAD_LOCAL_ZEROFILL &&
  302. s.size > S.filesize)
  303. return malformedError("size field of section " +
  304. Twine(J) + " in " + CmdName + " command " +
  305. Twine(LoadCommandIndex) +
  306. " greater than the segment");
  307. if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
  308. Obj.getHeader().filetype != MachO::MH_DSYM && s.size != 0 &&
  309. s.addr < S.vmaddr)
  310. return malformedError("addr field of section " + Twine(J) + " in " +
  311. CmdName + " command " + Twine(LoadCommandIndex) +
  312. " less than the segment's vmaddr");
  313. BigSize = s.addr;
  314. BigSize += s.size;
  315. uint64_t BigEnd = S.vmaddr;
  316. BigEnd += S.vmsize;
  317. if (S.vmsize != 0 && s.size != 0 && BigSize > BigEnd)
  318. return malformedError("addr field plus size of section " + Twine(J) +
  319. " in " + CmdName + " command " +
  320. Twine(LoadCommandIndex) +
  321. " greater than than "
  322. "the segment's vmaddr plus vmsize");
  323. if (Obj.getHeader().filetype != MachO::MH_DYLIB_STUB &&
  324. Obj.getHeader().filetype != MachO::MH_DSYM &&
  325. s.flags != MachO::S_ZEROFILL &&
  326. s.flags != MachO::S_THREAD_LOCAL_ZEROFILL)
  327. if (Error Err = checkOverlappingElement(Elements, s.offset, s.size,
  328. "section contents"))
  329. return Err;
  330. if (s.reloff > FileSize)
  331. return malformedError("reloff field of section " + Twine(J) + " in " +
  332. CmdName + " command " + Twine(LoadCommandIndex) +
  333. " extends past the end of the file");
  334. BigSize = s.nreloc;
  335. BigSize *= sizeof(struct MachO::relocation_info);
  336. BigSize += s.reloff;
  337. if (BigSize > FileSize)
  338. return malformedError("reloff field plus nreloc field times sizeof("
  339. "struct relocation_info) of section " +
  340. Twine(J) + " in " + CmdName + " command " +
  341. Twine(LoadCommandIndex) +
  342. " extends past the end of the file");
  343. if (Error Err = checkOverlappingElement(Elements, s.reloff, s.nreloc *
  344. sizeof(struct
  345. MachO::relocation_info),
  346. "section relocation entries"))
  347. return Err;
  348. }
  349. if (S.fileoff > FileSize)
  350. return malformedError("load command " + Twine(LoadCommandIndex) +
  351. " fileoff field in " + CmdName +
  352. " extends past the end of the file");
  353. uint64_t BigSize = S.fileoff;
  354. BigSize += S.filesize;
  355. if (BigSize > FileSize)
  356. return malformedError("load command " + Twine(LoadCommandIndex) +
  357. " fileoff field plus filesize field in " +
  358. CmdName + " extends past the end of the file");
  359. if (S.vmsize != 0 && S.filesize > S.vmsize)
  360. return malformedError("load command " + Twine(LoadCommandIndex) +
  361. " filesize field in " + CmdName +
  362. " greater than vmsize field");
  363. IsPageZeroSegment |= StringRef("__PAGEZERO").equals(S.segname);
  364. } else
  365. return SegOrErr.takeError();
  366. return Error::success();
  367. }
  368. static Error checkSymtabCommand(const MachOObjectFile &Obj,
  369. const MachOObjectFile::LoadCommandInfo &Load,
  370. uint32_t LoadCommandIndex,
  371. const char **SymtabLoadCmd,
  372. std::list<MachOElement> &Elements) {
  373. if (Load.C.cmdsize < sizeof(MachO::symtab_command))
  374. return malformedError("load command " + Twine(LoadCommandIndex) +
  375. " LC_SYMTAB cmdsize too small");
  376. if (*SymtabLoadCmd != nullptr)
  377. return malformedError("more than one LC_SYMTAB command");
  378. auto SymtabOrErr = getStructOrErr<MachO::symtab_command>(Obj, Load.Ptr);
  379. if (!SymtabOrErr)
  380. return SymtabOrErr.takeError();
  381. MachO::symtab_command Symtab = SymtabOrErr.get();
  382. if (Symtab.cmdsize != sizeof(MachO::symtab_command))
  383. return malformedError("LC_SYMTAB command " + Twine(LoadCommandIndex) +
  384. " has incorrect cmdsize");
  385. uint64_t FileSize = Obj.getData().size();
  386. if (Symtab.symoff > FileSize)
  387. return malformedError("symoff field of LC_SYMTAB command " +
  388. Twine(LoadCommandIndex) + " extends past the end "
  389. "of the file");
  390. uint64_t SymtabSize = Symtab.nsyms;
  391. const char *struct_nlist_name;
  392. if (Obj.is64Bit()) {
  393. SymtabSize *= sizeof(MachO::nlist_64);
  394. struct_nlist_name = "struct nlist_64";
  395. } else {
  396. SymtabSize *= sizeof(MachO::nlist);
  397. struct_nlist_name = "struct nlist";
  398. }
  399. uint64_t BigSize = SymtabSize;
  400. BigSize += Symtab.symoff;
  401. if (BigSize > FileSize)
  402. return malformedError("symoff field plus nsyms field times sizeof(" +
  403. Twine(struct_nlist_name) + ") of LC_SYMTAB command " +
  404. Twine(LoadCommandIndex) + " extends past the end "
  405. "of the file");
  406. if (Error Err = checkOverlappingElement(Elements, Symtab.symoff, SymtabSize,
  407. "symbol table"))
  408. return Err;
  409. if (Symtab.stroff > FileSize)
  410. return malformedError("stroff field of LC_SYMTAB command " +
  411. Twine(LoadCommandIndex) + " extends past the end "
  412. "of the file");
  413. BigSize = Symtab.stroff;
  414. BigSize += Symtab.strsize;
  415. if (BigSize > FileSize)
  416. return malformedError("stroff field plus strsize field of LC_SYMTAB "
  417. "command " + Twine(LoadCommandIndex) + " extends "
  418. "past the end of the file");
  419. if (Error Err = checkOverlappingElement(Elements, Symtab.stroff,
  420. Symtab.strsize, "string table"))
  421. return Err;
  422. *SymtabLoadCmd = Load.Ptr;
  423. return Error::success();
  424. }
  425. static Error checkDysymtabCommand(const MachOObjectFile &Obj,
  426. const MachOObjectFile::LoadCommandInfo &Load,
  427. uint32_t LoadCommandIndex,
  428. const char **DysymtabLoadCmd,
  429. std::list<MachOElement> &Elements) {
  430. if (Load.C.cmdsize < sizeof(MachO::dysymtab_command))
  431. return malformedError("load command " + Twine(LoadCommandIndex) +
  432. " LC_DYSYMTAB cmdsize too small");
  433. if (*DysymtabLoadCmd != nullptr)
  434. return malformedError("more than one LC_DYSYMTAB command");
  435. auto DysymtabOrErr =
  436. getStructOrErr<MachO::dysymtab_command>(Obj, Load.Ptr);
  437. if (!DysymtabOrErr)
  438. return DysymtabOrErr.takeError();
  439. MachO::dysymtab_command Dysymtab = DysymtabOrErr.get();
  440. if (Dysymtab.cmdsize != sizeof(MachO::dysymtab_command))
  441. return malformedError("LC_DYSYMTAB command " + Twine(LoadCommandIndex) +
  442. " has incorrect cmdsize");
  443. uint64_t FileSize = Obj.getData().size();
  444. if (Dysymtab.tocoff > FileSize)
  445. return malformedError("tocoff field of LC_DYSYMTAB command " +
  446. Twine(LoadCommandIndex) + " extends past the end of "
  447. "the file");
  448. uint64_t BigSize = Dysymtab.ntoc;
  449. BigSize *= sizeof(MachO::dylib_table_of_contents);
  450. BigSize += Dysymtab.tocoff;
  451. if (BigSize > FileSize)
  452. return malformedError("tocoff field plus ntoc field times sizeof(struct "
  453. "dylib_table_of_contents) of LC_DYSYMTAB command " +
  454. Twine(LoadCommandIndex) + " extends past the end of "
  455. "the file");
  456. if (Error Err = checkOverlappingElement(Elements, Dysymtab.tocoff,
  457. Dysymtab.ntoc * sizeof(struct
  458. MachO::dylib_table_of_contents),
  459. "table of contents"))
  460. return Err;
  461. if (Dysymtab.modtaboff > FileSize)
  462. return malformedError("modtaboff field of LC_DYSYMTAB command " +
  463. Twine(LoadCommandIndex) + " extends past the end of "
  464. "the file");
  465. BigSize = Dysymtab.nmodtab;
  466. const char *struct_dylib_module_name;
  467. uint64_t sizeof_modtab;
  468. if (Obj.is64Bit()) {
  469. sizeof_modtab = sizeof(MachO::dylib_module_64);
  470. struct_dylib_module_name = "struct dylib_module_64";
  471. } else {
  472. sizeof_modtab = sizeof(MachO::dylib_module);
  473. struct_dylib_module_name = "struct dylib_module";
  474. }
  475. BigSize *= sizeof_modtab;
  476. BigSize += Dysymtab.modtaboff;
  477. if (BigSize > FileSize)
  478. return malformedError("modtaboff field plus nmodtab field times sizeof(" +
  479. Twine(struct_dylib_module_name) + ") of LC_DYSYMTAB "
  480. "command " + Twine(LoadCommandIndex) + " extends "
  481. "past the end of the file");
  482. if (Error Err = checkOverlappingElement(Elements, Dysymtab.modtaboff,
  483. Dysymtab.nmodtab * sizeof_modtab,
  484. "module table"))
  485. return Err;
  486. if (Dysymtab.extrefsymoff > FileSize)
  487. return malformedError("extrefsymoff field of LC_DYSYMTAB command " +
  488. Twine(LoadCommandIndex) + " extends past the end of "
  489. "the file");
  490. BigSize = Dysymtab.nextrefsyms;
  491. BigSize *= sizeof(MachO::dylib_reference);
  492. BigSize += Dysymtab.extrefsymoff;
  493. if (BigSize > FileSize)
  494. return malformedError("extrefsymoff field plus nextrefsyms field times "
  495. "sizeof(struct dylib_reference) of LC_DYSYMTAB "
  496. "command " + Twine(LoadCommandIndex) + " extends "
  497. "past the end of the file");
  498. if (Error Err = checkOverlappingElement(Elements, Dysymtab.extrefsymoff,
  499. Dysymtab.nextrefsyms *
  500. sizeof(MachO::dylib_reference),
  501. "reference table"))
  502. return Err;
  503. if (Dysymtab.indirectsymoff > FileSize)
  504. return malformedError("indirectsymoff field of LC_DYSYMTAB command " +
  505. Twine(LoadCommandIndex) + " extends past the end of "
  506. "the file");
  507. BigSize = Dysymtab.nindirectsyms;
  508. BigSize *= sizeof(uint32_t);
  509. BigSize += Dysymtab.indirectsymoff;
  510. if (BigSize > FileSize)
  511. return malformedError("indirectsymoff field plus nindirectsyms field times "
  512. "sizeof(uint32_t) of LC_DYSYMTAB command " +
  513. Twine(LoadCommandIndex) + " extends past the end of "
  514. "the file");
  515. if (Error Err = checkOverlappingElement(Elements, Dysymtab.indirectsymoff,
  516. Dysymtab.nindirectsyms *
  517. sizeof(uint32_t),
  518. "indirect table"))
  519. return Err;
  520. if (Dysymtab.extreloff > FileSize)
  521. return malformedError("extreloff field of LC_DYSYMTAB command " +
  522. Twine(LoadCommandIndex) + " extends past the end of "
  523. "the file");
  524. BigSize = Dysymtab.nextrel;
  525. BigSize *= sizeof(MachO::relocation_info);
  526. BigSize += Dysymtab.extreloff;
  527. if (BigSize > FileSize)
  528. return malformedError("extreloff field plus nextrel field times sizeof"
  529. "(struct relocation_info) of LC_DYSYMTAB command " +
  530. Twine(LoadCommandIndex) + " extends past the end of "
  531. "the file");
  532. if (Error Err = checkOverlappingElement(Elements, Dysymtab.extreloff,
  533. Dysymtab.nextrel *
  534. sizeof(MachO::relocation_info),
  535. "external relocation table"))
  536. return Err;
  537. if (Dysymtab.locreloff > FileSize)
  538. return malformedError("locreloff field of LC_DYSYMTAB command " +
  539. Twine(LoadCommandIndex) + " extends past the end of "
  540. "the file");
  541. BigSize = Dysymtab.nlocrel;
  542. BigSize *= sizeof(MachO::relocation_info);
  543. BigSize += Dysymtab.locreloff;
  544. if (BigSize > FileSize)
  545. return malformedError("locreloff field plus nlocrel field times sizeof"
  546. "(struct relocation_info) of LC_DYSYMTAB command " +
  547. Twine(LoadCommandIndex) + " extends past the end of "
  548. "the file");
  549. if (Error Err = checkOverlappingElement(Elements, Dysymtab.locreloff,
  550. Dysymtab.nlocrel *
  551. sizeof(MachO::relocation_info),
  552. "local relocation table"))
  553. return Err;
  554. *DysymtabLoadCmd = Load.Ptr;
  555. return Error::success();
  556. }
  557. static Error checkLinkeditDataCommand(const MachOObjectFile &Obj,
  558. const MachOObjectFile::LoadCommandInfo &Load,
  559. uint32_t LoadCommandIndex,
  560. const char **LoadCmd, const char *CmdName,
  561. std::list<MachOElement> &Elements,
  562. const char *ElementName) {
  563. if (Load.C.cmdsize < sizeof(MachO::linkedit_data_command))
  564. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  565. CmdName + " cmdsize too small");
  566. if (*LoadCmd != nullptr)
  567. return malformedError("more than one " + Twine(CmdName) + " command");
  568. auto LinkDataOrError =
  569. getStructOrErr<MachO::linkedit_data_command>(Obj, Load.Ptr);
  570. if (!LinkDataOrError)
  571. return LinkDataOrError.takeError();
  572. MachO::linkedit_data_command LinkData = LinkDataOrError.get();
  573. if (LinkData.cmdsize != sizeof(MachO::linkedit_data_command))
  574. return malformedError(Twine(CmdName) + " command " +
  575. Twine(LoadCommandIndex) + " has incorrect cmdsize");
  576. uint64_t FileSize = Obj.getData().size();
  577. if (LinkData.dataoff > FileSize)
  578. return malformedError("dataoff field of " + Twine(CmdName) + " command " +
  579. Twine(LoadCommandIndex) + " extends past the end of "
  580. "the file");
  581. uint64_t BigSize = LinkData.dataoff;
  582. BigSize += LinkData.datasize;
  583. if (BigSize > FileSize)
  584. return malformedError("dataoff field plus datasize field of " +
  585. Twine(CmdName) + " command " +
  586. Twine(LoadCommandIndex) + " extends past the end of "
  587. "the file");
  588. if (Error Err = checkOverlappingElement(Elements, LinkData.dataoff,
  589. LinkData.datasize, ElementName))
  590. return Err;
  591. *LoadCmd = Load.Ptr;
  592. return Error::success();
  593. }
  594. static Error checkDyldInfoCommand(const MachOObjectFile &Obj,
  595. const MachOObjectFile::LoadCommandInfo &Load,
  596. uint32_t LoadCommandIndex,
  597. const char **LoadCmd, const char *CmdName,
  598. std::list<MachOElement> &Elements) {
  599. if (Load.C.cmdsize < sizeof(MachO::dyld_info_command))
  600. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  601. CmdName + " cmdsize too small");
  602. if (*LoadCmd != nullptr)
  603. return malformedError("more than one LC_DYLD_INFO and or LC_DYLD_INFO_ONLY "
  604. "command");
  605. auto DyldInfoOrErr =
  606. getStructOrErr<MachO::dyld_info_command>(Obj, Load.Ptr);
  607. if (!DyldInfoOrErr)
  608. return DyldInfoOrErr.takeError();
  609. MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
  610. if (DyldInfo.cmdsize != sizeof(MachO::dyld_info_command))
  611. return malformedError(Twine(CmdName) + " command " +
  612. Twine(LoadCommandIndex) + " has incorrect cmdsize");
  613. uint64_t FileSize = Obj.getData().size();
  614. if (DyldInfo.rebase_off > FileSize)
  615. return malformedError("rebase_off field of " + Twine(CmdName) +
  616. " command " + Twine(LoadCommandIndex) + " extends "
  617. "past the end of the file");
  618. uint64_t BigSize = DyldInfo.rebase_off;
  619. BigSize += DyldInfo.rebase_size;
  620. if (BigSize > FileSize)
  621. return malformedError("rebase_off field plus rebase_size field of " +
  622. Twine(CmdName) + " command " +
  623. Twine(LoadCommandIndex) + " extends past the end of "
  624. "the file");
  625. if (Error Err = checkOverlappingElement(Elements, DyldInfo.rebase_off,
  626. DyldInfo.rebase_size,
  627. "dyld rebase info"))
  628. return Err;
  629. if (DyldInfo.bind_off > FileSize)
  630. return malformedError("bind_off field of " + Twine(CmdName) +
  631. " command " + Twine(LoadCommandIndex) + " extends "
  632. "past the end of the file");
  633. BigSize = DyldInfo.bind_off;
  634. BigSize += DyldInfo.bind_size;
  635. if (BigSize > FileSize)
  636. return malformedError("bind_off field plus bind_size field of " +
  637. Twine(CmdName) + " command " +
  638. Twine(LoadCommandIndex) + " extends past the end of "
  639. "the file");
  640. if (Error Err = checkOverlappingElement(Elements, DyldInfo.bind_off,
  641. DyldInfo.bind_size,
  642. "dyld bind info"))
  643. return Err;
  644. if (DyldInfo.weak_bind_off > FileSize)
  645. return malformedError("weak_bind_off field of " + Twine(CmdName) +
  646. " command " + Twine(LoadCommandIndex) + " extends "
  647. "past the end of the file");
  648. BigSize = DyldInfo.weak_bind_off;
  649. BigSize += DyldInfo.weak_bind_size;
  650. if (BigSize > FileSize)
  651. return malformedError("weak_bind_off field plus weak_bind_size field of " +
  652. Twine(CmdName) + " command " +
  653. Twine(LoadCommandIndex) + " extends past the end of "
  654. "the file");
  655. if (Error Err = checkOverlappingElement(Elements, DyldInfo.weak_bind_off,
  656. DyldInfo.weak_bind_size,
  657. "dyld weak bind info"))
  658. return Err;
  659. if (DyldInfo.lazy_bind_off > FileSize)
  660. return malformedError("lazy_bind_off field of " + Twine(CmdName) +
  661. " command " + Twine(LoadCommandIndex) + " extends "
  662. "past the end of the file");
  663. BigSize = DyldInfo.lazy_bind_off;
  664. BigSize += DyldInfo.lazy_bind_size;
  665. if (BigSize > FileSize)
  666. return malformedError("lazy_bind_off field plus lazy_bind_size field of " +
  667. Twine(CmdName) + " command " +
  668. Twine(LoadCommandIndex) + " extends past the end of "
  669. "the file");
  670. if (Error Err = checkOverlappingElement(Elements, DyldInfo.lazy_bind_off,
  671. DyldInfo.lazy_bind_size,
  672. "dyld lazy bind info"))
  673. return Err;
  674. if (DyldInfo.export_off > FileSize)
  675. return malformedError("export_off field of " + Twine(CmdName) +
  676. " command " + Twine(LoadCommandIndex) + " extends "
  677. "past the end of the file");
  678. BigSize = DyldInfo.export_off;
  679. BigSize += DyldInfo.export_size;
  680. if (BigSize > FileSize)
  681. return malformedError("export_off field plus export_size field of " +
  682. Twine(CmdName) + " command " +
  683. Twine(LoadCommandIndex) + " extends past the end of "
  684. "the file");
  685. if (Error Err = checkOverlappingElement(Elements, DyldInfo.export_off,
  686. DyldInfo.export_size,
  687. "dyld export info"))
  688. return Err;
  689. *LoadCmd = Load.Ptr;
  690. return Error::success();
  691. }
  692. static Error checkDylibCommand(const MachOObjectFile &Obj,
  693. const MachOObjectFile::LoadCommandInfo &Load,
  694. uint32_t LoadCommandIndex, const char *CmdName) {
  695. if (Load.C.cmdsize < sizeof(MachO::dylib_command))
  696. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  697. CmdName + " cmdsize too small");
  698. auto CommandOrErr = getStructOrErr<MachO::dylib_command>(Obj, Load.Ptr);
  699. if (!CommandOrErr)
  700. return CommandOrErr.takeError();
  701. MachO::dylib_command D = CommandOrErr.get();
  702. if (D.dylib.name < sizeof(MachO::dylib_command))
  703. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  704. CmdName + " name.offset field too small, not past "
  705. "the end of the dylib_command struct");
  706. if (D.dylib.name >= D.cmdsize)
  707. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  708. CmdName + " name.offset field extends past the end "
  709. "of the load command");
  710. // Make sure there is a null between the starting offset of the name and
  711. // the end of the load command.
  712. uint32_t i;
  713. const char *P = (const char *)Load.Ptr;
  714. for (i = D.dylib.name; i < D.cmdsize; i++)
  715. if (P[i] == '\0')
  716. break;
  717. if (i >= D.cmdsize)
  718. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  719. CmdName + " library name extends past the end of the "
  720. "load command");
  721. return Error::success();
  722. }
  723. static Error checkDylibIdCommand(const MachOObjectFile &Obj,
  724. const MachOObjectFile::LoadCommandInfo &Load,
  725. uint32_t LoadCommandIndex,
  726. const char **LoadCmd) {
  727. if (Error Err = checkDylibCommand(Obj, Load, LoadCommandIndex,
  728. "LC_ID_DYLIB"))
  729. return Err;
  730. if (*LoadCmd != nullptr)
  731. return malformedError("more than one LC_ID_DYLIB command");
  732. if (Obj.getHeader().filetype != MachO::MH_DYLIB &&
  733. Obj.getHeader().filetype != MachO::MH_DYLIB_STUB)
  734. return malformedError("LC_ID_DYLIB load command in non-dynamic library "
  735. "file type");
  736. *LoadCmd = Load.Ptr;
  737. return Error::success();
  738. }
  739. static Error checkDyldCommand(const MachOObjectFile &Obj,
  740. const MachOObjectFile::LoadCommandInfo &Load,
  741. uint32_t LoadCommandIndex, const char *CmdName) {
  742. if (Load.C.cmdsize < sizeof(MachO::dylinker_command))
  743. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  744. CmdName + " cmdsize too small");
  745. auto CommandOrErr = getStructOrErr<MachO::dylinker_command>(Obj, Load.Ptr);
  746. if (!CommandOrErr)
  747. return CommandOrErr.takeError();
  748. MachO::dylinker_command D = CommandOrErr.get();
  749. if (D.name < sizeof(MachO::dylinker_command))
  750. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  751. CmdName + " name.offset field too small, not past "
  752. "the end of the dylinker_command struct");
  753. if (D.name >= D.cmdsize)
  754. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  755. CmdName + " name.offset field extends past the end "
  756. "of the load command");
  757. // Make sure there is a null between the starting offset of the name and
  758. // the end of the load command.
  759. uint32_t i;
  760. const char *P = (const char *)Load.Ptr;
  761. for (i = D.name; i < D.cmdsize; i++)
  762. if (P[i] == '\0')
  763. break;
  764. if (i >= D.cmdsize)
  765. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  766. CmdName + " dyld name extends past the end of the "
  767. "load command");
  768. return Error::success();
  769. }
  770. static Error checkVersCommand(const MachOObjectFile &Obj,
  771. const MachOObjectFile::LoadCommandInfo &Load,
  772. uint32_t LoadCommandIndex,
  773. const char **LoadCmd, const char *CmdName) {
  774. if (Load.C.cmdsize != sizeof(MachO::version_min_command))
  775. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  776. CmdName + " has incorrect cmdsize");
  777. if (*LoadCmd != nullptr)
  778. return malformedError("more than one LC_VERSION_MIN_MACOSX, "
  779. "LC_VERSION_MIN_IPHONEOS, LC_VERSION_MIN_TVOS or "
  780. "LC_VERSION_MIN_WATCHOS command");
  781. *LoadCmd = Load.Ptr;
  782. return Error::success();
  783. }
  784. static Error checkNoteCommand(const MachOObjectFile &Obj,
  785. const MachOObjectFile::LoadCommandInfo &Load,
  786. uint32_t LoadCommandIndex,
  787. std::list<MachOElement> &Elements) {
  788. if (Load.C.cmdsize != sizeof(MachO::note_command))
  789. return malformedError("load command " + Twine(LoadCommandIndex) +
  790. " LC_NOTE has incorrect cmdsize");
  791. auto NoteCmdOrErr = getStructOrErr<MachO::note_command>(Obj, Load.Ptr);
  792. if (!NoteCmdOrErr)
  793. return NoteCmdOrErr.takeError();
  794. MachO::note_command Nt = NoteCmdOrErr.get();
  795. uint64_t FileSize = Obj.getData().size();
  796. if (Nt.offset > FileSize)
  797. return malformedError("offset field of LC_NOTE command " +
  798. Twine(LoadCommandIndex) + " extends "
  799. "past the end of the file");
  800. uint64_t BigSize = Nt.offset;
  801. BigSize += Nt.size;
  802. if (BigSize > FileSize)
  803. return malformedError("size field plus offset field of LC_NOTE command " +
  804. Twine(LoadCommandIndex) + " extends past the end of "
  805. "the file");
  806. if (Error Err = checkOverlappingElement(Elements, Nt.offset, Nt.size,
  807. "LC_NOTE data"))
  808. return Err;
  809. return Error::success();
  810. }
  811. static Error
  812. parseBuildVersionCommand(const MachOObjectFile &Obj,
  813. const MachOObjectFile::LoadCommandInfo &Load,
  814. SmallVectorImpl<const char*> &BuildTools,
  815. uint32_t LoadCommandIndex) {
  816. auto BVCOrErr =
  817. getStructOrErr<MachO::build_version_command>(Obj, Load.Ptr);
  818. if (!BVCOrErr)
  819. return BVCOrErr.takeError();
  820. MachO::build_version_command BVC = BVCOrErr.get();
  821. if (Load.C.cmdsize !=
  822. sizeof(MachO::build_version_command) +
  823. BVC.ntools * sizeof(MachO::build_tool_version))
  824. return malformedError("load command " + Twine(LoadCommandIndex) +
  825. " LC_BUILD_VERSION_COMMAND has incorrect cmdsize");
  826. auto Start = Load.Ptr + sizeof(MachO::build_version_command);
  827. BuildTools.resize(BVC.ntools);
  828. for (unsigned i = 0; i < BVC.ntools; ++i)
  829. BuildTools[i] = Start + i * sizeof(MachO::build_tool_version);
  830. return Error::success();
  831. }
  832. static Error checkRpathCommand(const MachOObjectFile &Obj,
  833. const MachOObjectFile::LoadCommandInfo &Load,
  834. uint32_t LoadCommandIndex) {
  835. if (Load.C.cmdsize < sizeof(MachO::rpath_command))
  836. return malformedError("load command " + Twine(LoadCommandIndex) +
  837. " LC_RPATH cmdsize too small");
  838. auto ROrErr = getStructOrErr<MachO::rpath_command>(Obj, Load.Ptr);
  839. if (!ROrErr)
  840. return ROrErr.takeError();
  841. MachO::rpath_command R = ROrErr.get();
  842. if (R.path < sizeof(MachO::rpath_command))
  843. return malformedError("load command " + Twine(LoadCommandIndex) +
  844. " LC_RPATH path.offset field too small, not past "
  845. "the end of the rpath_command struct");
  846. if (R.path >= R.cmdsize)
  847. return malformedError("load command " + Twine(LoadCommandIndex) +
  848. " LC_RPATH path.offset field extends past the end "
  849. "of the load command");
  850. // Make sure there is a null between the starting offset of the path and
  851. // the end of the load command.
  852. uint32_t i;
  853. const char *P = (const char *)Load.Ptr;
  854. for (i = R.path; i < R.cmdsize; i++)
  855. if (P[i] == '\0')
  856. break;
  857. if (i >= R.cmdsize)
  858. return malformedError("load command " + Twine(LoadCommandIndex) +
  859. " LC_RPATH library name extends past the end of the "
  860. "load command");
  861. return Error::success();
  862. }
  863. static Error checkEncryptCommand(const MachOObjectFile &Obj,
  864. const MachOObjectFile::LoadCommandInfo &Load,
  865. uint32_t LoadCommandIndex,
  866. uint64_t cryptoff, uint64_t cryptsize,
  867. const char **LoadCmd, const char *CmdName) {
  868. if (*LoadCmd != nullptr)
  869. return malformedError("more than one LC_ENCRYPTION_INFO and or "
  870. "LC_ENCRYPTION_INFO_64 command");
  871. uint64_t FileSize = Obj.getData().size();
  872. if (cryptoff > FileSize)
  873. return malformedError("cryptoff field of " + Twine(CmdName) +
  874. " command " + Twine(LoadCommandIndex) + " extends "
  875. "past the end of the file");
  876. uint64_t BigSize = cryptoff;
  877. BigSize += cryptsize;
  878. if (BigSize > FileSize)
  879. return malformedError("cryptoff field plus cryptsize field of " +
  880. Twine(CmdName) + " command " +
  881. Twine(LoadCommandIndex) + " extends past the end of "
  882. "the file");
  883. *LoadCmd = Load.Ptr;
  884. return Error::success();
  885. }
  886. static Error checkLinkerOptCommand(const MachOObjectFile &Obj,
  887. const MachOObjectFile::LoadCommandInfo &Load,
  888. uint32_t LoadCommandIndex) {
  889. if (Load.C.cmdsize < sizeof(MachO::linker_option_command))
  890. return malformedError("load command " + Twine(LoadCommandIndex) +
  891. " LC_LINKER_OPTION cmdsize too small");
  892. auto LinkOptionOrErr =
  893. getStructOrErr<MachO::linker_option_command>(Obj, Load.Ptr);
  894. if (!LinkOptionOrErr)
  895. return LinkOptionOrErr.takeError();
  896. MachO::linker_option_command L = LinkOptionOrErr.get();
  897. // Make sure the count of strings is correct.
  898. const char *string = (const char *)Load.Ptr +
  899. sizeof(struct MachO::linker_option_command);
  900. uint32_t left = L.cmdsize - sizeof(struct MachO::linker_option_command);
  901. uint32_t i = 0;
  902. while (left > 0) {
  903. while (*string == '\0' && left > 0) {
  904. string++;
  905. left--;
  906. }
  907. if (left > 0) {
  908. i++;
  909. uint32_t NullPos = StringRef(string, left).find('\0');
  910. if (0xffffffff == NullPos)
  911. return malformedError("load command " + Twine(LoadCommandIndex) +
  912. " LC_LINKER_OPTION string #" + Twine(i) +
  913. " is not NULL terminated");
  914. uint32_t len = std::min(NullPos, left) + 1;
  915. string += len;
  916. left -= len;
  917. }
  918. }
  919. if (L.count != i)
  920. return malformedError("load command " + Twine(LoadCommandIndex) +
  921. " LC_LINKER_OPTION string count " + Twine(L.count) +
  922. " does not match number of strings");
  923. return Error::success();
  924. }
  925. static Error checkSubCommand(const MachOObjectFile &Obj,
  926. const MachOObjectFile::LoadCommandInfo &Load,
  927. uint32_t LoadCommandIndex, const char *CmdName,
  928. size_t SizeOfCmd, const char *CmdStructName,
  929. uint32_t PathOffset, const char *PathFieldName) {
  930. if (PathOffset < SizeOfCmd)
  931. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  932. CmdName + " " + PathFieldName + ".offset field too "
  933. "small, not past the end of the " + CmdStructName);
  934. if (PathOffset >= Load.C.cmdsize)
  935. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  936. CmdName + " " + PathFieldName + ".offset field "
  937. "extends past the end of the load command");
  938. // Make sure there is a null between the starting offset of the path and
  939. // the end of the load command.
  940. uint32_t i;
  941. const char *P = (const char *)Load.Ptr;
  942. for (i = PathOffset; i < Load.C.cmdsize; i++)
  943. if (P[i] == '\0')
  944. break;
  945. if (i >= Load.C.cmdsize)
  946. return malformedError("load command " + Twine(LoadCommandIndex) + " " +
  947. CmdName + " " + PathFieldName + " name extends past "
  948. "the end of the load command");
  949. return Error::success();
  950. }
  951. static Error checkThreadCommand(const MachOObjectFile &Obj,
  952. const MachOObjectFile::LoadCommandInfo &Load,
  953. uint32_t LoadCommandIndex,
  954. const char *CmdName) {
  955. if (Load.C.cmdsize < sizeof(MachO::thread_command))
  956. return malformedError("load command " + Twine(LoadCommandIndex) +
  957. CmdName + " cmdsize too small");
  958. auto ThreadCommandOrErr =
  959. getStructOrErr<MachO::thread_command>(Obj, Load.Ptr);
  960. if (!ThreadCommandOrErr)
  961. return ThreadCommandOrErr.takeError();
  962. MachO::thread_command T = ThreadCommandOrErr.get();
  963. const char *state = Load.Ptr + sizeof(MachO::thread_command);
  964. const char *end = Load.Ptr + T.cmdsize;
  965. uint32_t nflavor = 0;
  966. uint32_t cputype = getCPUType(Obj);
  967. while (state < end) {
  968. if(state + sizeof(uint32_t) > end)
  969. return malformedError("load command " + Twine(LoadCommandIndex) +
  970. "flavor in " + CmdName + " extends past end of "
  971. "command");
  972. uint32_t flavor;
  973. memcpy(&flavor, state, sizeof(uint32_t));
  974. if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
  975. sys::swapByteOrder(flavor);
  976. state += sizeof(uint32_t);
  977. if(state + sizeof(uint32_t) > end)
  978. return malformedError("load command " + Twine(LoadCommandIndex) +
  979. " count in " + CmdName + " extends past end of "
  980. "command");
  981. uint32_t count;
  982. memcpy(&count, state, sizeof(uint32_t));
  983. if (Obj.isLittleEndian() != sys::IsLittleEndianHost)
  984. sys::swapByteOrder(count);
  985. state += sizeof(uint32_t);
  986. if (cputype == MachO::CPU_TYPE_I386) {
  987. if (flavor == MachO::x86_THREAD_STATE32) {
  988. if (count != MachO::x86_THREAD_STATE32_COUNT)
  989. return malformedError("load command " + Twine(LoadCommandIndex) +
  990. " count not x86_THREAD_STATE32_COUNT for "
  991. "flavor number " + Twine(nflavor) + " which is "
  992. "a x86_THREAD_STATE32 flavor in " + CmdName +
  993. " command");
  994. if (state + sizeof(MachO::x86_thread_state32_t) > end)
  995. return malformedError("load command " + Twine(LoadCommandIndex) +
  996. " x86_THREAD_STATE32 extends past end of "
  997. "command in " + CmdName + " command");
  998. state += sizeof(MachO::x86_thread_state32_t);
  999. } else {
  1000. return malformedError("load command " + Twine(LoadCommandIndex) +
  1001. " unknown flavor (" + Twine(flavor) + ") for "
  1002. "flavor number " + Twine(nflavor) + " in " +
  1003. CmdName + " command");
  1004. }
  1005. } else if (cputype == MachO::CPU_TYPE_X86_64) {
  1006. if (flavor == MachO::x86_THREAD_STATE) {
  1007. if (count != MachO::x86_THREAD_STATE_COUNT)
  1008. return malformedError("load command " + Twine(LoadCommandIndex) +
  1009. " count not x86_THREAD_STATE_COUNT for "
  1010. "flavor number " + Twine(nflavor) + " which is "
  1011. "a x86_THREAD_STATE flavor in " + CmdName +
  1012. " command");
  1013. if (state + sizeof(MachO::x86_thread_state_t) > end)
  1014. return malformedError("load command " + Twine(LoadCommandIndex) +
  1015. " x86_THREAD_STATE extends past end of "
  1016. "command in " + CmdName + " command");
  1017. state += sizeof(MachO::x86_thread_state_t);
  1018. } else if (flavor == MachO::x86_FLOAT_STATE) {
  1019. if (count != MachO::x86_FLOAT_STATE_COUNT)
  1020. return malformedError("load command " + Twine(LoadCommandIndex) +
  1021. " count not x86_FLOAT_STATE_COUNT for "
  1022. "flavor number " + Twine(nflavor) + " which is "
  1023. "a x86_FLOAT_STATE flavor in " + CmdName +
  1024. " command");
  1025. if (state + sizeof(MachO::x86_float_state_t) > end)
  1026. return malformedError("load command " + Twine(LoadCommandIndex) +
  1027. " x86_FLOAT_STATE extends past end of "
  1028. "command in " + CmdName + " command");
  1029. state += sizeof(MachO::x86_float_state_t);
  1030. } else if (flavor == MachO::x86_EXCEPTION_STATE) {
  1031. if (count != MachO::x86_EXCEPTION_STATE_COUNT)
  1032. return malformedError("load command " + Twine(LoadCommandIndex) +
  1033. " count not x86_EXCEPTION_STATE_COUNT for "
  1034. "flavor number " + Twine(nflavor) + " which is "
  1035. "a x86_EXCEPTION_STATE flavor in " + CmdName +
  1036. " command");
  1037. if (state + sizeof(MachO::x86_exception_state_t) > end)
  1038. return malformedError("load command " + Twine(LoadCommandIndex) +
  1039. " x86_EXCEPTION_STATE extends past end of "
  1040. "command in " + CmdName + " command");
  1041. state += sizeof(MachO::x86_exception_state_t);
  1042. } else if (flavor == MachO::x86_THREAD_STATE64) {
  1043. if (count != MachO::x86_THREAD_STATE64_COUNT)
  1044. return malformedError("load command " + Twine(LoadCommandIndex) +
  1045. " count not x86_THREAD_STATE64_COUNT for "
  1046. "flavor number " + Twine(nflavor) + " which is "
  1047. "a x86_THREAD_STATE64 flavor in " + CmdName +
  1048. " command");
  1049. if (state + sizeof(MachO::x86_thread_state64_t) > end)
  1050. return malformedError("load command " + Twine(LoadCommandIndex) +
  1051. " x86_THREAD_STATE64 extends past end of "
  1052. "command in " + CmdName + " command");
  1053. state += sizeof(MachO::x86_thread_state64_t);
  1054. } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
  1055. if (count != MachO::x86_EXCEPTION_STATE64_COUNT)
  1056. return malformedError("load command " + Twine(LoadCommandIndex) +
  1057. " count not x86_EXCEPTION_STATE64_COUNT for "
  1058. "flavor number " + Twine(nflavor) + " which is "
  1059. "a x86_EXCEPTION_STATE64 flavor in " + CmdName +
  1060. " command");
  1061. if (state + sizeof(MachO::x86_exception_state64_t) > end)
  1062. return malformedError("load command " + Twine(LoadCommandIndex) +
  1063. " x86_EXCEPTION_STATE64 extends past end of "
  1064. "command in " + CmdName + " command");
  1065. state += sizeof(MachO::x86_exception_state64_t);
  1066. } else {
  1067. return malformedError("load command " + Twine(LoadCommandIndex) +
  1068. " unknown flavor (" + Twine(flavor) + ") for "
  1069. "flavor number " + Twine(nflavor) + " in " +
  1070. CmdName + " command");
  1071. }
  1072. } else if (cputype == MachO::CPU_TYPE_ARM) {
  1073. if (flavor == MachO::ARM_THREAD_STATE) {
  1074. if (count != MachO::ARM_THREAD_STATE_COUNT)
  1075. return malformedError("load command " + Twine(LoadCommandIndex) +
  1076. " count not ARM_THREAD_STATE_COUNT for "
  1077. "flavor number " + Twine(nflavor) + " which is "
  1078. "a ARM_THREAD_STATE flavor in " + CmdName +
  1079. " command");
  1080. if (state + sizeof(MachO::arm_thread_state32_t) > end)
  1081. return malformedError("load command " + Twine(LoadCommandIndex) +
  1082. " ARM_THREAD_STATE extends past end of "
  1083. "command in " + CmdName + " command");
  1084. state += sizeof(MachO::arm_thread_state32_t);
  1085. } else {
  1086. return malformedError("load command " + Twine(LoadCommandIndex) +
  1087. " unknown flavor (" + Twine(flavor) + ") for "
  1088. "flavor number " + Twine(nflavor) + " in " +
  1089. CmdName + " command");
  1090. }
  1091. } else if (cputype == MachO::CPU_TYPE_ARM64 ||
  1092. cputype == MachO::CPU_TYPE_ARM64_32) {
  1093. if (flavor == MachO::ARM_THREAD_STATE64) {
  1094. if (count != MachO::ARM_THREAD_STATE64_COUNT)
  1095. return malformedError("load command " + Twine(LoadCommandIndex) +
  1096. " count not ARM_THREAD_STATE64_COUNT for "
  1097. "flavor number " + Twine(nflavor) + " which is "
  1098. "a ARM_THREAD_STATE64 flavor in " + CmdName +
  1099. " command");
  1100. if (state + sizeof(MachO::arm_thread_state64_t) > end)
  1101. return malformedError("load command " + Twine(LoadCommandIndex) +
  1102. " ARM_THREAD_STATE64 extends past end of "
  1103. "command in " + CmdName + " command");
  1104. state += sizeof(MachO::arm_thread_state64_t);
  1105. } else {
  1106. return malformedError("load command " + Twine(LoadCommandIndex) +
  1107. " unknown flavor (" + Twine(flavor) + ") for "
  1108. "flavor number " + Twine(nflavor) + " in " +
  1109. CmdName + " command");
  1110. }
  1111. } else if (cputype == MachO::CPU_TYPE_POWERPC) {
  1112. if (flavor == MachO::PPC_THREAD_STATE) {
  1113. if (count != MachO::PPC_THREAD_STATE_COUNT)
  1114. return malformedError("load command " + Twine(LoadCommandIndex) +
  1115. " count not PPC_THREAD_STATE_COUNT for "
  1116. "flavor number " + Twine(nflavor) + " which is "
  1117. "a PPC_THREAD_STATE flavor in " + CmdName +
  1118. " command");
  1119. if (state + sizeof(MachO::ppc_thread_state32_t) > end)
  1120. return malformedError("load command " + Twine(LoadCommandIndex) +
  1121. " PPC_THREAD_STATE extends past end of "
  1122. "command in " + CmdName + " command");
  1123. state += sizeof(MachO::ppc_thread_state32_t);
  1124. } else {
  1125. return malformedError("load command " + Twine(LoadCommandIndex) +
  1126. " unknown flavor (" + Twine(flavor) + ") for "
  1127. "flavor number " + Twine(nflavor) + " in " +
  1128. CmdName + " command");
  1129. }
  1130. } else {
  1131. return malformedError("unknown cputype (" + Twine(cputype) + ") load "
  1132. "command " + Twine(LoadCommandIndex) + " for " +
  1133. CmdName + " command can't be checked");
  1134. }
  1135. nflavor++;
  1136. }
  1137. return Error::success();
  1138. }
  1139. static Error checkTwoLevelHintsCommand(const MachOObjectFile &Obj,
  1140. const MachOObjectFile::LoadCommandInfo
  1141. &Load,
  1142. uint32_t LoadCommandIndex,
  1143. const char **LoadCmd,
  1144. std::list<MachOElement> &Elements) {
  1145. if (Load.C.cmdsize != sizeof(MachO::twolevel_hints_command))
  1146. return malformedError("load command " + Twine(LoadCommandIndex) +
  1147. " LC_TWOLEVEL_HINTS has incorrect cmdsize");
  1148. if (*LoadCmd != nullptr)
  1149. return malformedError("more than one LC_TWOLEVEL_HINTS command");
  1150. auto HintsOrErr = getStructOrErr<MachO::twolevel_hints_command>(Obj, Load.Ptr);
  1151. if(!HintsOrErr)
  1152. return HintsOrErr.takeError();
  1153. MachO::twolevel_hints_command Hints = HintsOrErr.get();
  1154. uint64_t FileSize = Obj.getData().size();
  1155. if (Hints.offset > FileSize)
  1156. return malformedError("offset field of LC_TWOLEVEL_HINTS command " +
  1157. Twine(LoadCommandIndex) + " extends past the end of "
  1158. "the file");
  1159. uint64_t BigSize = Hints.nhints;
  1160. BigSize *= sizeof(MachO::twolevel_hint);
  1161. BigSize += Hints.offset;
  1162. if (BigSize > FileSize)
  1163. return malformedError("offset field plus nhints times sizeof(struct "
  1164. "twolevel_hint) field of LC_TWOLEVEL_HINTS command " +
  1165. Twine(LoadCommandIndex) + " extends past the end of "
  1166. "the file");
  1167. if (Error Err = checkOverlappingElement(Elements, Hints.offset, Hints.nhints *
  1168. sizeof(MachO::twolevel_hint),
  1169. "two level hints"))
  1170. return Err;
  1171. *LoadCmd = Load.Ptr;
  1172. return Error::success();
  1173. }
  1174. // Returns true if the libObject code does not support the load command and its
  1175. // contents. The cmd value it is treated as an unknown load command but with
  1176. // an error message that says the cmd value is obsolete.
  1177. static bool isLoadCommandObsolete(uint32_t cmd) {
  1178. if (cmd == MachO::LC_SYMSEG ||
  1179. cmd == MachO::LC_LOADFVMLIB ||
  1180. cmd == MachO::LC_IDFVMLIB ||
  1181. cmd == MachO::LC_IDENT ||
  1182. cmd == MachO::LC_FVMFILE ||
  1183. cmd == MachO::LC_PREPAGE ||
  1184. cmd == MachO::LC_PREBOUND_DYLIB ||
  1185. cmd == MachO::LC_TWOLEVEL_HINTS ||
  1186. cmd == MachO::LC_PREBIND_CKSUM)
  1187. return true;
  1188. return false;
  1189. }
  1190. Expected<std::unique_ptr<MachOObjectFile>>
  1191. MachOObjectFile::create(MemoryBufferRef Object, bool IsLittleEndian,
  1192. bool Is64Bits, uint32_t UniversalCputype,
  1193. uint32_t UniversalIndex) {
  1194. Error Err = Error::success();
  1195. std::unique_ptr<MachOObjectFile> Obj(
  1196. new MachOObjectFile(std::move(Object), IsLittleEndian,
  1197. Is64Bits, Err, UniversalCputype,
  1198. UniversalIndex));
  1199. if (Err)
  1200. return std::move(Err);
  1201. return std::move(Obj);
  1202. }
  1203. MachOObjectFile::MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian,
  1204. bool Is64bits, Error &Err,
  1205. uint32_t UniversalCputype,
  1206. uint32_t UniversalIndex)
  1207. : ObjectFile(getMachOType(IsLittleEndian, Is64bits), Object) {
  1208. ErrorAsOutParameter ErrAsOutParam(&Err);
  1209. uint64_t SizeOfHeaders;
  1210. uint32_t cputype;
  1211. if (is64Bit()) {
  1212. parseHeader(*this, Header64, Err);
  1213. SizeOfHeaders = sizeof(MachO::mach_header_64);
  1214. cputype = Header64.cputype;
  1215. } else {
  1216. parseHeader(*this, Header, Err);
  1217. SizeOfHeaders = sizeof(MachO::mach_header);
  1218. cputype = Header.cputype;
  1219. }
  1220. if (Err)
  1221. return;
  1222. SizeOfHeaders += getHeader().sizeofcmds;
  1223. if (getData().data() + SizeOfHeaders > getData().end()) {
  1224. Err = malformedError("load commands extend past the end of the file");
  1225. return;
  1226. }
  1227. if (UniversalCputype != 0 && cputype != UniversalCputype) {
  1228. Err = malformedError("universal header architecture: " +
  1229. Twine(UniversalIndex) + "'s cputype does not match "
  1230. "object file's mach header");
  1231. return;
  1232. }
  1233. std::list<MachOElement> Elements;
  1234. Elements.push_back({0, SizeOfHeaders, "Mach-O headers"});
  1235. uint32_t LoadCommandCount = getHeader().ncmds;
  1236. LoadCommandInfo Load;
  1237. if (LoadCommandCount != 0) {
  1238. if (auto LoadOrErr = getFirstLoadCommandInfo(*this))
  1239. Load = *LoadOrErr;
  1240. else {
  1241. Err = LoadOrErr.takeError();
  1242. return;
  1243. }
  1244. }
  1245. const char *DyldIdLoadCmd = nullptr;
  1246. const char *FuncStartsLoadCmd = nullptr;
  1247. const char *SplitInfoLoadCmd = nullptr;
  1248. const char *CodeSignDrsLoadCmd = nullptr;
  1249. const char *CodeSignLoadCmd = nullptr;
  1250. const char *VersLoadCmd = nullptr;
  1251. const char *SourceLoadCmd = nullptr;
  1252. const char *EntryPointLoadCmd = nullptr;
  1253. const char *EncryptLoadCmd = nullptr;
  1254. const char *RoutinesLoadCmd = nullptr;
  1255. const char *UnixThreadLoadCmd = nullptr;
  1256. const char *TwoLevelHintsLoadCmd = nullptr;
  1257. for (unsigned I = 0; I < LoadCommandCount; ++I) {
  1258. if (is64Bit()) {
  1259. if (Load.C.cmdsize % 8 != 0) {
  1260. // We have a hack here to allow 64-bit Mach-O core files to have
  1261. // LC_THREAD commands that are only a multiple of 4 and not 8 to be
  1262. // allowed since the macOS kernel produces them.
  1263. if (getHeader().filetype != MachO::MH_CORE ||
  1264. Load.C.cmd != MachO::LC_THREAD || Load.C.cmdsize % 4) {
  1265. Err = malformedError("load command " + Twine(I) + " cmdsize not a "
  1266. "multiple of 8");
  1267. return;
  1268. }
  1269. }
  1270. } else {
  1271. if (Load.C.cmdsize % 4 != 0) {
  1272. Err = malformedError("load command " + Twine(I) + " cmdsize not a "
  1273. "multiple of 4");
  1274. return;
  1275. }
  1276. }
  1277. LoadCommands.push_back(Load);
  1278. if (Load.C.cmd == MachO::LC_SYMTAB) {
  1279. if ((Err = checkSymtabCommand(*this, Load, I, &SymtabLoadCmd, Elements)))
  1280. return;
  1281. } else if (Load.C.cmd == MachO::LC_DYSYMTAB) {
  1282. if ((Err = checkDysymtabCommand(*this, Load, I, &DysymtabLoadCmd,
  1283. Elements)))
  1284. return;
  1285. } else if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
  1286. if ((Err = checkLinkeditDataCommand(*this, Load, I, &DataInCodeLoadCmd,
  1287. "LC_DATA_IN_CODE", Elements,
  1288. "data in code info")))
  1289. return;
  1290. } else if (Load.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
  1291. if ((Err = checkLinkeditDataCommand(*this, Load, I, &LinkOptHintsLoadCmd,
  1292. "LC_LINKER_OPTIMIZATION_HINT",
  1293. Elements, "linker optimization "
  1294. "hints")))
  1295. return;
  1296. } else if (Load.C.cmd == MachO::LC_FUNCTION_STARTS) {
  1297. if ((Err = checkLinkeditDataCommand(*this, Load, I, &FuncStartsLoadCmd,
  1298. "LC_FUNCTION_STARTS", Elements,
  1299. "function starts data")))
  1300. return;
  1301. } else if (Load.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO) {
  1302. if ((Err = checkLinkeditDataCommand(*this, Load, I, &SplitInfoLoadCmd,
  1303. "LC_SEGMENT_SPLIT_INFO", Elements,
  1304. "split info data")))
  1305. return;
  1306. } else if (Load.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) {
  1307. if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignDrsLoadCmd,
  1308. "LC_DYLIB_CODE_SIGN_DRS", Elements,
  1309. "code signing RDs data")))
  1310. return;
  1311. } else if (Load.C.cmd == MachO::LC_CODE_SIGNATURE) {
  1312. if ((Err = checkLinkeditDataCommand(*this, Load, I, &CodeSignLoadCmd,
  1313. "LC_CODE_SIGNATURE", Elements,
  1314. "code signature data")))
  1315. return;
  1316. } else if (Load.C.cmd == MachO::LC_DYLD_INFO) {
  1317. if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
  1318. "LC_DYLD_INFO", Elements)))
  1319. return;
  1320. } else if (Load.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
  1321. if ((Err = checkDyldInfoCommand(*this, Load, I, &DyldInfoLoadCmd,
  1322. "LC_DYLD_INFO_ONLY", Elements)))
  1323. return;
  1324. } else if (Load.C.cmd == MachO::LC_UUID) {
  1325. if (Load.C.cmdsize != sizeof(MachO::uuid_command)) {
  1326. Err = malformedError("LC_UUID command " + Twine(I) + " has incorrect "
  1327. "cmdsize");
  1328. return;
  1329. }
  1330. if (UuidLoadCmd) {
  1331. Err = malformedError("more than one LC_UUID command");
  1332. return;
  1333. }
  1334. UuidLoadCmd = Load.Ptr;
  1335. } else if (Load.C.cmd == MachO::LC_SEGMENT_64) {
  1336. if ((Err = parseSegmentLoadCommand<MachO::segment_command_64,
  1337. MachO::section_64>(
  1338. *this, Load, Sections, HasPageZeroSegment, I,
  1339. "LC_SEGMENT_64", SizeOfHeaders, Elements)))
  1340. return;
  1341. } else if (Load.C.cmd == MachO::LC_SEGMENT) {
  1342. if ((Err = parseSegmentLoadCommand<MachO::segment_command,
  1343. MachO::section>(
  1344. *this, Load, Sections, HasPageZeroSegment, I,
  1345. "LC_SEGMENT", SizeOfHeaders, Elements)))
  1346. return;
  1347. } else if (Load.C.cmd == MachO::LC_ID_DYLIB) {
  1348. if ((Err = checkDylibIdCommand(*this, Load, I, &DyldIdLoadCmd)))
  1349. return;
  1350. } else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) {
  1351. if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_DYLIB")))
  1352. return;
  1353. Libraries.push_back(Load.Ptr);
  1354. } else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) {
  1355. if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_WEAK_DYLIB")))
  1356. return;
  1357. Libraries.push_back(Load.Ptr);
  1358. } else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) {
  1359. if ((Err = checkDylibCommand(*this, Load, I, "LC_LAZY_LOAD_DYLIB")))
  1360. return;
  1361. Libraries.push_back(Load.Ptr);
  1362. } else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) {
  1363. if ((Err = checkDylibCommand(*this, Load, I, "LC_REEXPORT_DYLIB")))
  1364. return;
  1365. Libraries.push_back(Load.Ptr);
  1366. } else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
  1367. if ((Err = checkDylibCommand(*this, Load, I, "LC_LOAD_UPWARD_DYLIB")))
  1368. return;
  1369. Libraries.push_back(Load.Ptr);
  1370. } else if (Load.C.cmd == MachO::LC_ID_DYLINKER) {
  1371. if ((Err = checkDyldCommand(*this, Load, I, "LC_ID_DYLINKER")))
  1372. return;
  1373. } else if (Load.C.cmd == MachO::LC_LOAD_DYLINKER) {
  1374. if ((Err = checkDyldCommand(*this, Load, I, "LC_LOAD_DYLINKER")))
  1375. return;
  1376. } else if (Load.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
  1377. if ((Err = checkDyldCommand(*this, Load, I, "LC_DYLD_ENVIRONMENT")))
  1378. return;
  1379. } else if (Load.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
  1380. if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
  1381. "LC_VERSION_MIN_MACOSX")))
  1382. return;
  1383. } else if (Load.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
  1384. if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
  1385. "LC_VERSION_MIN_IPHONEOS")))
  1386. return;
  1387. } else if (Load.C.cmd == MachO::LC_VERSION_MIN_TVOS) {
  1388. if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
  1389. "LC_VERSION_MIN_TVOS")))
  1390. return;
  1391. } else if (Load.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
  1392. if ((Err = checkVersCommand(*this, Load, I, &VersLoadCmd,
  1393. "LC_VERSION_MIN_WATCHOS")))
  1394. return;
  1395. } else if (Load.C.cmd == MachO::LC_NOTE) {
  1396. if ((Err = checkNoteCommand(*this, Load, I, Elements)))
  1397. return;
  1398. } else if (Load.C.cmd == MachO::LC_BUILD_VERSION) {
  1399. if ((Err = parseBuildVersionCommand(*this, Load, BuildTools, I)))
  1400. return;
  1401. } else if (Load.C.cmd == MachO::LC_RPATH) {
  1402. if ((Err = checkRpathCommand(*this, Load, I)))
  1403. return;
  1404. } else if (Load.C.cmd == MachO::LC_SOURCE_VERSION) {
  1405. if (Load.C.cmdsize != sizeof(MachO::source_version_command)) {
  1406. Err = malformedError("LC_SOURCE_VERSION command " + Twine(I) +
  1407. " has incorrect cmdsize");
  1408. return;
  1409. }
  1410. if (SourceLoadCmd) {
  1411. Err = malformedError("more than one LC_SOURCE_VERSION command");
  1412. return;
  1413. }
  1414. SourceLoadCmd = Load.Ptr;
  1415. } else if (Load.C.cmd == MachO::LC_MAIN) {
  1416. if (Load.C.cmdsize != sizeof(MachO::entry_point_command)) {
  1417. Err = malformedError("LC_MAIN command " + Twine(I) +
  1418. " has incorrect cmdsize");
  1419. return;
  1420. }
  1421. if (EntryPointLoadCmd) {
  1422. Err = malformedError("more than one LC_MAIN command");
  1423. return;
  1424. }
  1425. EntryPointLoadCmd = Load.Ptr;
  1426. } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO) {
  1427. if (Load.C.cmdsize != sizeof(MachO::encryption_info_command)) {
  1428. Err = malformedError("LC_ENCRYPTION_INFO command " + Twine(I) +
  1429. " has incorrect cmdsize");
  1430. return;
  1431. }
  1432. MachO::encryption_info_command E =
  1433. getStruct<MachO::encryption_info_command>(*this, Load.Ptr);
  1434. if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
  1435. &EncryptLoadCmd, "LC_ENCRYPTION_INFO")))
  1436. return;
  1437. } else if (Load.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
  1438. if (Load.C.cmdsize != sizeof(MachO::encryption_info_command_64)) {
  1439. Err = malformedError("LC_ENCRYPTION_INFO_64 command " + Twine(I) +
  1440. " has incorrect cmdsize");
  1441. return;
  1442. }
  1443. MachO::encryption_info_command_64 E =
  1444. getStruct<MachO::encryption_info_command_64>(*this, Load.Ptr);
  1445. if ((Err = checkEncryptCommand(*this, Load, I, E.cryptoff, E.cryptsize,
  1446. &EncryptLoadCmd, "LC_ENCRYPTION_INFO_64")))
  1447. return;
  1448. } else if (Load.C.cmd == MachO::LC_LINKER_OPTION) {
  1449. if ((Err = checkLinkerOptCommand(*this, Load, I)))
  1450. return;
  1451. } else if (Load.C.cmd == MachO::LC_SUB_FRAMEWORK) {
  1452. if (Load.C.cmdsize < sizeof(MachO::sub_framework_command)) {
  1453. Err = malformedError("load command " + Twine(I) +
  1454. " LC_SUB_FRAMEWORK cmdsize too small");
  1455. return;
  1456. }
  1457. MachO::sub_framework_command S =
  1458. getStruct<MachO::sub_framework_command>(*this, Load.Ptr);
  1459. if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_FRAMEWORK",
  1460. sizeof(MachO::sub_framework_command),
  1461. "sub_framework_command", S.umbrella,
  1462. "umbrella")))
  1463. return;
  1464. } else if (Load.C.cmd == MachO::LC_SUB_UMBRELLA) {
  1465. if (Load.C.cmdsize < sizeof(MachO::sub_umbrella_command)) {
  1466. Err = malformedError("load command " + Twine(I) +
  1467. " LC_SUB_UMBRELLA cmdsize too small");
  1468. return;
  1469. }
  1470. MachO::sub_umbrella_command S =
  1471. getStruct<MachO::sub_umbrella_command>(*this, Load.Ptr);
  1472. if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_UMBRELLA",
  1473. sizeof(MachO::sub_umbrella_command),
  1474. "sub_umbrella_command", S.sub_umbrella,
  1475. "sub_umbrella")))
  1476. return;
  1477. } else if (Load.C.cmd == MachO::LC_SUB_LIBRARY) {
  1478. if (Load.C.cmdsize < sizeof(MachO::sub_library_command)) {
  1479. Err = malformedError("load command " + Twine(I) +
  1480. " LC_SUB_LIBRARY cmdsize too small");
  1481. return;
  1482. }
  1483. MachO::sub_library_command S =
  1484. getStruct<MachO::sub_library_command>(*this, Load.Ptr);
  1485. if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_LIBRARY",
  1486. sizeof(MachO::sub_library_command),
  1487. "sub_library_command", S.sub_library,
  1488. "sub_library")))
  1489. return;
  1490. } else if (Load.C.cmd == MachO::LC_SUB_CLIENT) {
  1491. if (Load.C.cmdsize < sizeof(MachO::sub_client_command)) {
  1492. Err = malformedError("load command " + Twine(I) +
  1493. " LC_SUB_CLIENT cmdsize too small");
  1494. return;
  1495. }
  1496. MachO::sub_client_command S =
  1497. getStruct<MachO::sub_client_command>(*this, Load.Ptr);
  1498. if ((Err = checkSubCommand(*this, Load, I, "LC_SUB_CLIENT",
  1499. sizeof(MachO::sub_client_command),
  1500. "sub_client_command", S.client, "client")))
  1501. return;
  1502. } else if (Load.C.cmd == MachO::LC_ROUTINES) {
  1503. if (Load.C.cmdsize != sizeof(MachO::routines_command)) {
  1504. Err = malformedError("LC_ROUTINES command " + Twine(I) +
  1505. " has incorrect cmdsize");
  1506. return;
  1507. }
  1508. if (RoutinesLoadCmd) {
  1509. Err = malformedError("more than one LC_ROUTINES and or LC_ROUTINES_64 "
  1510. "command");
  1511. return;
  1512. }
  1513. RoutinesLoadCmd = Load.Ptr;
  1514. } else if (Load.C.cmd == MachO::LC_ROUTINES_64) {
  1515. if (Load.C.cmdsize != sizeof(MachO::routines_command_64)) {
  1516. Err = malformedError("LC_ROUTINES_64 command " + Twine(I) +
  1517. " has incorrect cmdsize");
  1518. return;
  1519. }
  1520. if (RoutinesLoadCmd) {
  1521. Err = malformedError("more than one LC_ROUTINES_64 and or LC_ROUTINES "
  1522. "command");
  1523. return;
  1524. }
  1525. RoutinesLoadCmd = Load.Ptr;
  1526. } else if (Load.C.cmd == MachO::LC_UNIXTHREAD) {
  1527. if ((Err = checkThreadCommand(*this, Load, I, "LC_UNIXTHREAD")))
  1528. return;
  1529. if (UnixThreadLoadCmd) {
  1530. Err = malformedError("more than one LC_UNIXTHREAD command");
  1531. return;
  1532. }
  1533. UnixThreadLoadCmd = Load.Ptr;
  1534. } else if (Load.C.cmd == MachO::LC_THREAD) {
  1535. if ((Err = checkThreadCommand(*this, Load, I, "LC_THREAD")))
  1536. return;
  1537. // Note: LC_TWOLEVEL_HINTS is really obsolete and is not supported.
  1538. } else if (Load.C.cmd == MachO::LC_TWOLEVEL_HINTS) {
  1539. if ((Err = checkTwoLevelHintsCommand(*this, Load, I,
  1540. &TwoLevelHintsLoadCmd, Elements)))
  1541. return;
  1542. } else if (Load.C.cmd == MachO::LC_IDENT) {
  1543. // Note: LC_IDENT is ignored.
  1544. continue;
  1545. } else if (isLoadCommandObsolete(Load.C.cmd)) {
  1546. Err = malformedError("load command " + Twine(I) + " for cmd value of: " +
  1547. Twine(Load.C.cmd) + " is obsolete and not "
  1548. "supported");
  1549. return;
  1550. }
  1551. // TODO: generate a error for unknown load commands by default. But still
  1552. // need work out an approach to allow or not allow unknown values like this
  1553. // as an option for some uses like lldb.
  1554. if (I < LoadCommandCount - 1) {
  1555. if (auto LoadOrErr = getNextLoadCommandInfo(*this, I, Load))
  1556. Load = *LoadOrErr;
  1557. else {
  1558. Err = LoadOrErr.takeError();
  1559. return;
  1560. }
  1561. }
  1562. }
  1563. if (!SymtabLoadCmd) {
  1564. if (DysymtabLoadCmd) {
  1565. Err = malformedError("contains LC_DYSYMTAB load command without a "
  1566. "LC_SYMTAB load command");
  1567. return;
  1568. }
  1569. } else if (DysymtabLoadCmd) {
  1570. MachO::symtab_command Symtab =
  1571. getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
  1572. MachO::dysymtab_command Dysymtab =
  1573. getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
  1574. if (Dysymtab.nlocalsym != 0 && Dysymtab.ilocalsym > Symtab.nsyms) {
  1575. Err = malformedError("ilocalsym in LC_DYSYMTAB load command "
  1576. "extends past the end of the symbol table");
  1577. return;
  1578. }
  1579. uint64_t BigSize = Dysymtab.ilocalsym;
  1580. BigSize += Dysymtab.nlocalsym;
  1581. if (Dysymtab.nlocalsym != 0 && BigSize > Symtab.nsyms) {
  1582. Err = malformedError("ilocalsym plus nlocalsym in LC_DYSYMTAB load "
  1583. "command extends past the end of the symbol table");
  1584. return;
  1585. }
  1586. if (Dysymtab.nextdefsym != 0 && Dysymtab.iextdefsym > Symtab.nsyms) {
  1587. Err = malformedError("iextdefsym in LC_DYSYMTAB load command "
  1588. "extends past the end of the symbol table");
  1589. return;
  1590. }
  1591. BigSize = Dysymtab.iextdefsym;
  1592. BigSize += Dysymtab.nextdefsym;
  1593. if (Dysymtab.nextdefsym != 0 && BigSize > Symtab.nsyms) {
  1594. Err = malformedError("iextdefsym plus nextdefsym in LC_DYSYMTAB "
  1595. "load command extends past the end of the symbol "
  1596. "table");
  1597. return;
  1598. }
  1599. if (Dysymtab.nundefsym != 0 && Dysymtab.iundefsym > Symtab.nsyms) {
  1600. Err = malformedError("iundefsym in LC_DYSYMTAB load command "
  1601. "extends past the end of the symbol table");
  1602. return;
  1603. }
  1604. BigSize = Dysymtab.iundefsym;
  1605. BigSize += Dysymtab.nundefsym;
  1606. if (Dysymtab.nundefsym != 0 && BigSize > Symtab.nsyms) {
  1607. Err = malformedError("iundefsym plus nundefsym in LC_DYSYMTAB load "
  1608. " command extends past the end of the symbol table");
  1609. return;
  1610. }
  1611. }
  1612. if ((getHeader().filetype == MachO::MH_DYLIB ||
  1613. getHeader().filetype == MachO::MH_DYLIB_STUB) &&
  1614. DyldIdLoadCmd == nullptr) {
  1615. Err = malformedError("no LC_ID_DYLIB load command in dynamic library "
  1616. "filetype");
  1617. return;
  1618. }
  1619. assert(LoadCommands.size() == LoadCommandCount);
  1620. Err = Error::success();
  1621. }
  1622. Error MachOObjectFile::checkSymbolTable() const {
  1623. uint32_t Flags = 0;
  1624. if (is64Bit()) {
  1625. MachO::mach_header_64 H_64 = MachOObjectFile::getHeader64();
  1626. Flags = H_64.flags;
  1627. } else {
  1628. MachO::mach_header H = MachOObjectFile::getHeader();
  1629. Flags = H.flags;
  1630. }
  1631. uint8_t NType = 0;
  1632. uint8_t NSect = 0;
  1633. uint16_t NDesc = 0;
  1634. uint32_t NStrx = 0;
  1635. uint64_t NValue = 0;
  1636. uint32_t SymbolIndex = 0;
  1637. MachO::symtab_command S = getSymtabLoadCommand();
  1638. for (const SymbolRef &Symbol : symbols()) {
  1639. DataRefImpl SymDRI = Symbol.getRawDataRefImpl();
  1640. if (is64Bit()) {
  1641. MachO::nlist_64 STE_64 = getSymbol64TableEntry(SymDRI);
  1642. NType = STE_64.n_type;
  1643. NSect = STE_64.n_sect;
  1644. NDesc = STE_64.n_desc;
  1645. NStrx = STE_64.n_strx;
  1646. NValue = STE_64.n_value;
  1647. } else {
  1648. MachO::nlist STE = getSymbolTableEntry(SymDRI);
  1649. NType = STE.n_type;
  1650. NSect = STE.n_sect;
  1651. NDesc = STE.n_desc;
  1652. NStrx = STE.n_strx;
  1653. NValue = STE.n_value;
  1654. }
  1655. if ((NType & MachO::N_STAB) == 0) {
  1656. if ((NType & MachO::N_TYPE) == MachO::N_SECT) {
  1657. if (NSect == 0 || NSect > Sections.size())
  1658. return malformedError("bad section index: " + Twine((int)NSect) +
  1659. " for symbol at index " + Twine(SymbolIndex));
  1660. }
  1661. if ((NType & MachO::N_TYPE) == MachO::N_INDR) {
  1662. if (NValue >= S.strsize)
  1663. return malformedError("bad n_value: " + Twine((int)NValue) + " past "
  1664. "the end of string table, for N_INDR symbol at "
  1665. "index " + Twine(SymbolIndex));
  1666. }
  1667. if ((Flags & MachO::MH_TWOLEVEL) == MachO::MH_TWOLEVEL &&
  1668. (((NType & MachO::N_TYPE) == MachO::N_UNDF && NValue == 0) ||
  1669. (NType & MachO::N_TYPE) == MachO::N_PBUD)) {
  1670. uint32_t LibraryOrdinal = MachO::GET_LIBRARY_ORDINAL(NDesc);
  1671. if (LibraryOrdinal != 0 &&
  1672. LibraryOrdinal != MachO::EXECUTABLE_ORDINAL &&
  1673. LibraryOrdinal != MachO::DYNAMIC_LOOKUP_ORDINAL &&
  1674. LibraryOrdinal - 1 >= Libraries.size() ) {
  1675. return malformedError("bad library ordinal: " + Twine(LibraryOrdinal) +
  1676. " for symbol at index " + Twine(SymbolIndex));
  1677. }
  1678. }
  1679. }
  1680. if (NStrx >= S.strsize)
  1681. return malformedError("bad string table index: " + Twine((int)NStrx) +
  1682. " past the end of string table, for symbol at "
  1683. "index " + Twine(SymbolIndex));
  1684. SymbolIndex++;
  1685. }
  1686. return Error::success();
  1687. }
  1688. void MachOObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
  1689. unsigned SymbolTableEntrySize = is64Bit() ?
  1690. sizeof(MachO::nlist_64) :
  1691. sizeof(MachO::nlist);
  1692. Symb.p += SymbolTableEntrySize;
  1693. }
  1694. Expected<StringRef> MachOObjectFile::getSymbolName(DataRefImpl Symb) const {
  1695. StringRef StringTable = getStringTableData();
  1696. MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
  1697. if (Entry.n_strx == 0)
  1698. // A n_strx value of 0 indicates that no name is associated with a
  1699. // particular symbol table entry.
  1700. return StringRef();
  1701. const char *Start = &StringTable.data()[Entry.n_strx];
  1702. if (Start < getData().begin() || Start >= getData().end()) {
  1703. return malformedError("bad string index: " + Twine(Entry.n_strx) +
  1704. " for symbol at index " + Twine(getSymbolIndex(Symb)));
  1705. }
  1706. return StringRef(Start);
  1707. }
  1708. unsigned MachOObjectFile::getSectionType(SectionRef Sec) const {
  1709. DataRefImpl DRI = Sec.getRawDataRefImpl();
  1710. uint32_t Flags = getSectionFlags(*this, DRI);
  1711. return Flags & MachO::SECTION_TYPE;
  1712. }
  1713. uint64_t MachOObjectFile::getNValue(DataRefImpl Sym) const {
  1714. if (is64Bit()) {
  1715. MachO::nlist_64 Entry = getSymbol64TableEntry(Sym);
  1716. return Entry.n_value;
  1717. }
  1718. MachO::nlist Entry = getSymbolTableEntry(Sym);
  1719. return Entry.n_value;
  1720. }
  1721. // getIndirectName() returns the name of the alias'ed symbol who's string table
  1722. // index is in the n_value field.
  1723. std::error_code MachOObjectFile::getIndirectName(DataRefImpl Symb,
  1724. StringRef &Res) const {
  1725. StringRef StringTable = getStringTableData();
  1726. MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
  1727. if ((Entry.n_type & MachO::N_TYPE) != MachO::N_INDR)
  1728. return object_error::parse_failed;
  1729. uint64_t NValue = getNValue(Symb);
  1730. if (NValue >= StringTable.size())
  1731. return object_error::parse_failed;
  1732. const char *Start = &StringTable.data()[NValue];
  1733. Res = StringRef(Start);
  1734. return std::error_code();
  1735. }
  1736. uint64_t MachOObjectFile::getSymbolValueImpl(DataRefImpl Sym) const {
  1737. return getNValue(Sym);
  1738. }
  1739. Expected<uint64_t> MachOObjectFile::getSymbolAddress(DataRefImpl Sym) const {
  1740. return getSymbolValue(Sym);
  1741. }
  1742. uint32_t MachOObjectFile::getSymbolAlignment(DataRefImpl DRI) const {
  1743. uint32_t Flags = cantFail(getSymbolFlags(DRI));
  1744. if (Flags & SymbolRef::SF_Common) {
  1745. MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
  1746. return 1 << MachO::GET_COMM_ALIGN(Entry.n_desc);
  1747. }
  1748. return 0;
  1749. }
  1750. uint64_t MachOObjectFile::getCommonSymbolSizeImpl(DataRefImpl DRI) const {
  1751. return getNValue(DRI);
  1752. }
  1753. Expected<SymbolRef::Type>
  1754. MachOObjectFile::getSymbolType(DataRefImpl Symb) const {
  1755. MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
  1756. uint8_t n_type = Entry.n_type;
  1757. // If this is a STAB debugging symbol, we can do nothing more.
  1758. if (n_type & MachO::N_STAB)
  1759. return SymbolRef::ST_Debug;
  1760. switch (n_type & MachO::N_TYPE) {
  1761. case MachO::N_UNDF :
  1762. return SymbolRef::ST_Unknown;
  1763. case MachO::N_SECT :
  1764. Expected<section_iterator> SecOrError = getSymbolSection(Symb);
  1765. if (!SecOrError)
  1766. return SecOrError.takeError();
  1767. section_iterator Sec = *SecOrError;
  1768. if (Sec == section_end())
  1769. return SymbolRef::ST_Other;
  1770. if (Sec->isData() || Sec->isBSS())
  1771. return SymbolRef::ST_Data;
  1772. return SymbolRef::ST_Function;
  1773. }
  1774. return SymbolRef::ST_Other;
  1775. }
  1776. Expected<uint32_t> MachOObjectFile::getSymbolFlags(DataRefImpl DRI) const {
  1777. MachO::nlist_base Entry = getSymbolTableEntryBase(*this, DRI);
  1778. uint8_t MachOType = Entry.n_type;
  1779. uint16_t MachOFlags = Entry.n_desc;
  1780. uint32_t Result = SymbolRef::SF_None;
  1781. if ((MachOType & MachO::N_TYPE) == MachO::N_INDR)
  1782. Result |= SymbolRef::SF_Indirect;
  1783. if (MachOType & MachO::N_STAB)
  1784. Result |= SymbolRef::SF_FormatSpecific;
  1785. if (MachOType & MachO::N_EXT) {
  1786. Result |= SymbolRef::SF_Global;
  1787. if ((MachOType & MachO::N_TYPE) == MachO::N_UNDF) {
  1788. if (getNValue(DRI))
  1789. Result |= SymbolRef::SF_Common;
  1790. else
  1791. Result |= SymbolRef::SF_Undefined;
  1792. }
  1793. if (!(MachOType & MachO::N_PEXT))
  1794. Result |= SymbolRef::SF_Exported;
  1795. }
  1796. if (MachOFlags & (MachO::N_WEAK_REF | MachO::N_WEAK_DEF))
  1797. Result |= SymbolRef::SF_Weak;
  1798. if (MachOFlags & (MachO::N_ARM_THUMB_DEF))
  1799. Result |= SymbolRef::SF_Thumb;
  1800. if ((MachOType & MachO::N_TYPE) == MachO::N_ABS)
  1801. Result |= SymbolRef::SF_Absolute;
  1802. return Result;
  1803. }
  1804. Expected<section_iterator>
  1805. MachOObjectFile::getSymbolSection(DataRefImpl Symb) const {
  1806. MachO::nlist_base Entry = getSymbolTableEntryBase(*this, Symb);
  1807. uint8_t index = Entry.n_sect;
  1808. if (index == 0)
  1809. return section_end();
  1810. DataRefImpl DRI;
  1811. DRI.d.a = index - 1;
  1812. if (DRI.d.a >= Sections.size()){
  1813. return malformedError("bad section index: " + Twine((int)index) +
  1814. " for symbol at index " + Twine(getSymbolIndex(Symb)));
  1815. }
  1816. return section_iterator(SectionRef(DRI, this));
  1817. }
  1818. unsigned MachOObjectFile::getSymbolSectionID(SymbolRef Sym) const {
  1819. MachO::nlist_base Entry =
  1820. getSymbolTableEntryBase(*this, Sym.getRawDataRefImpl());
  1821. return Entry.n_sect - 1;
  1822. }
  1823. void MachOObjectFile::moveSectionNext(DataRefImpl &Sec) const {
  1824. Sec.d.a++;
  1825. }
  1826. Expected<StringRef> MachOObjectFile::getSectionName(DataRefImpl Sec) const {
  1827. ArrayRef<char> Raw = getSectionRawName(Sec);
  1828. return parseSegmentOrSectionName(Raw.data());
  1829. }
  1830. uint64_t MachOObjectFile::getSectionAddress(DataRefImpl Sec) const {
  1831. if (is64Bit())
  1832. return getSection64(Sec).addr;
  1833. return getSection(Sec).addr;
  1834. }
  1835. uint64_t MachOObjectFile::getSectionIndex(DataRefImpl Sec) const {
  1836. return Sec.d.a;
  1837. }
  1838. uint64_t MachOObjectFile::getSectionSize(DataRefImpl Sec) const {
  1839. // In the case if a malformed Mach-O file where the section offset is past
  1840. // the end of the file or some part of the section size is past the end of
  1841. // the file return a size of zero or a size that covers the rest of the file
  1842. // but does not extend past the end of the file.
  1843. uint32_t SectOffset, SectType;
  1844. uint64_t SectSize;
  1845. if (is64Bit()) {
  1846. MachO::section_64 Sect = getSection64(Sec);
  1847. SectOffset = Sect.offset;
  1848. SectSize = Sect.size;
  1849. SectType = Sect.flags & MachO::SECTION_TYPE;
  1850. } else {
  1851. MachO::section Sect = getSection(Sec);
  1852. SectOffset = Sect.offset;
  1853. SectSize = Sect.size;
  1854. SectType = Sect.flags & MachO::SECTION_TYPE;
  1855. }
  1856. if (SectType == MachO::S_ZEROFILL || SectType == MachO::S_GB_ZEROFILL)
  1857. return SectSize;
  1858. uint64_t FileSize = getData().size();
  1859. if (SectOffset > FileSize)
  1860. return 0;
  1861. if (FileSize - SectOffset < SectSize)
  1862. return FileSize - SectOffset;
  1863. return SectSize;
  1864. }
  1865. ArrayRef<uint8_t> MachOObjectFile::getSectionContents(uint32_t Offset,
  1866. uint64_t Size) const {
  1867. return arrayRefFromStringRef(getData().substr(Offset, Size));
  1868. }
  1869. Expected<ArrayRef<uint8_t>>
  1870. MachOObjectFile::getSectionContents(DataRefImpl Sec) const {
  1871. uint32_t Offset;
  1872. uint64_t Size;
  1873. if (is64Bit()) {
  1874. MachO::section_64 Sect = getSection64(Sec);
  1875. Offset = Sect.offset;
  1876. Size = Sect.size;
  1877. } else {
  1878. MachO::section Sect = getSection(Sec);
  1879. Offset = Sect.offset;
  1880. Size = Sect.size;
  1881. }
  1882. return getSectionContents(Offset, Size);
  1883. }
  1884. uint64_t MachOObjectFile::getSectionAlignment(DataRefImpl Sec) const {
  1885. uint32_t Align;
  1886. if (is64Bit()) {
  1887. MachO::section_64 Sect = getSection64(Sec);
  1888. Align = Sect.align;
  1889. } else {
  1890. MachO::section Sect = getSection(Sec);
  1891. Align = Sect.align;
  1892. }
  1893. return uint64_t(1) << Align;
  1894. }
  1895. Expected<SectionRef> MachOObjectFile::getSection(unsigned SectionIndex) const {
  1896. if (SectionIndex < 1 || SectionIndex > Sections.size())
  1897. return malformedError("bad section index: " + Twine((int)SectionIndex));
  1898. DataRefImpl DRI;
  1899. DRI.d.a = SectionIndex - 1;
  1900. return SectionRef(DRI, this);
  1901. }
  1902. Expected<SectionRef> MachOObjectFile::getSection(StringRef SectionName) const {
  1903. for (const SectionRef &Section : sections()) {
  1904. auto NameOrErr = Section.getName();
  1905. if (!NameOrErr)
  1906. return NameOrErr.takeError();
  1907. if (*NameOrErr == SectionName)
  1908. return Section;
  1909. }
  1910. return errorCodeToError(object_error::parse_failed);
  1911. }
  1912. bool MachOObjectFile::isSectionCompressed(DataRefImpl Sec) const {
  1913. return false;
  1914. }
  1915. bool MachOObjectFile::isSectionText(DataRefImpl Sec) const {
  1916. uint32_t Flags = getSectionFlags(*this, Sec);
  1917. return Flags & MachO::S_ATTR_PURE_INSTRUCTIONS;
  1918. }
  1919. bool MachOObjectFile::isSectionData(DataRefImpl Sec) const {
  1920. uint32_t Flags = getSectionFlags(*this, Sec);
  1921. unsigned SectionType = Flags & MachO::SECTION_TYPE;
  1922. return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
  1923. !(SectionType == MachO::S_ZEROFILL ||
  1924. SectionType == MachO::S_GB_ZEROFILL);
  1925. }
  1926. bool MachOObjectFile::isSectionBSS(DataRefImpl Sec) const {
  1927. uint32_t Flags = getSectionFlags(*this, Sec);
  1928. unsigned SectionType = Flags & MachO::SECTION_TYPE;
  1929. return !(Flags & MachO::S_ATTR_PURE_INSTRUCTIONS) &&
  1930. (SectionType == MachO::S_ZEROFILL ||
  1931. SectionType == MachO::S_GB_ZEROFILL);
  1932. }
  1933. bool MachOObjectFile::isDebugSection(DataRefImpl Sec) const {
  1934. Expected<StringRef> SectionNameOrErr = getSectionName(Sec);
  1935. if (!SectionNameOrErr) {
  1936. // TODO: Report the error message properly.
  1937. consumeError(SectionNameOrErr.takeError());
  1938. return false;
  1939. }
  1940. StringRef SectionName = SectionNameOrErr.get();
  1941. return SectionName.startswith("__debug") ||
  1942. SectionName.startswith("__zdebug") ||
  1943. SectionName.startswith("__apple") || SectionName == "__gdb_index" ||
  1944. SectionName == "__swift_ast";
  1945. }
  1946. namespace {
  1947. template <typename LoadCommandType>
  1948. ArrayRef<uint8_t> getSegmentContents(const MachOObjectFile &Obj,
  1949. MachOObjectFile::LoadCommandInfo LoadCmd,
  1950. StringRef SegmentName) {
  1951. auto SegmentOrErr = getStructOrErr<LoadCommandType>(Obj, LoadCmd.Ptr);
  1952. if (!SegmentOrErr) {
  1953. consumeError(SegmentOrErr.takeError());
  1954. return {};
  1955. }
  1956. auto &Segment = SegmentOrErr.get();
  1957. if (StringRef(Segment.segname, 16).startswith(SegmentName))
  1958. return arrayRefFromStringRef(Obj.getData().slice(
  1959. Segment.fileoff, Segment.fileoff + Segment.filesize));
  1960. return {};
  1961. }
  1962. } // namespace
  1963. ArrayRef<uint8_t>
  1964. MachOObjectFile::getSegmentContents(StringRef SegmentName) const {
  1965. for (auto LoadCmd : load_commands()) {
  1966. ArrayRef<uint8_t> Contents;
  1967. switch (LoadCmd.C.cmd) {
  1968. case MachO::LC_SEGMENT:
  1969. Contents = ::getSegmentContents<MachO::segment_command>(*this, LoadCmd,
  1970. SegmentName);
  1971. break;
  1972. case MachO::LC_SEGMENT_64:
  1973. Contents = ::getSegmentContents<MachO::segment_command_64>(*this, LoadCmd,
  1974. SegmentName);
  1975. break;
  1976. default:
  1977. continue;
  1978. }
  1979. if (!Contents.empty())
  1980. return Contents;
  1981. }
  1982. return {};
  1983. }
  1984. unsigned MachOObjectFile::getSectionID(SectionRef Sec) const {
  1985. return Sec.getRawDataRefImpl().d.a;
  1986. }
  1987. bool MachOObjectFile::isSectionVirtual(DataRefImpl Sec) const {
  1988. uint32_t Flags = getSectionFlags(*this, Sec);
  1989. unsigned SectionType = Flags & MachO::SECTION_TYPE;
  1990. return SectionType == MachO::S_ZEROFILL ||
  1991. SectionType == MachO::S_GB_ZEROFILL;
  1992. }
  1993. bool MachOObjectFile::isSectionBitcode(DataRefImpl Sec) const {
  1994. StringRef SegmentName = getSectionFinalSegmentName(Sec);
  1995. if (Expected<StringRef> NameOrErr = getSectionName(Sec))
  1996. return (SegmentName == "__LLVM" && *NameOrErr == "__bitcode");
  1997. return false;
  1998. }
  1999. bool MachOObjectFile::isSectionStripped(DataRefImpl Sec) const {
  2000. if (is64Bit())
  2001. return getSection64(Sec).offset == 0;
  2002. return getSection(Sec).offset == 0;
  2003. }
  2004. relocation_iterator MachOObjectFile::section_rel_begin(DataRefImpl Sec) const {
  2005. DataRefImpl Ret;
  2006. Ret.d.a = Sec.d.a;
  2007. Ret.d.b = 0;
  2008. return relocation_iterator(RelocationRef(Ret, this));
  2009. }
  2010. relocation_iterator
  2011. MachOObjectFile::section_rel_end(DataRefImpl Sec) const {
  2012. uint32_t Num;
  2013. if (is64Bit()) {
  2014. MachO::section_64 Sect = getSection64(Sec);
  2015. Num = Sect.nreloc;
  2016. } else {
  2017. MachO::section Sect = getSection(Sec);
  2018. Num = Sect.nreloc;
  2019. }
  2020. DataRefImpl Ret;
  2021. Ret.d.a = Sec.d.a;
  2022. Ret.d.b = Num;
  2023. return relocation_iterator(RelocationRef(Ret, this));
  2024. }
  2025. relocation_iterator MachOObjectFile::extrel_begin() const {
  2026. DataRefImpl Ret;
  2027. // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
  2028. Ret.d.a = 0; // Would normally be a section index.
  2029. Ret.d.b = 0; // Index into the external relocations
  2030. return relocation_iterator(RelocationRef(Ret, this));
  2031. }
  2032. relocation_iterator MachOObjectFile::extrel_end() const {
  2033. MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
  2034. DataRefImpl Ret;
  2035. // for DYSYMTAB symbols, Ret.d.a == 0 for external relocations
  2036. Ret.d.a = 0; // Would normally be a section index.
  2037. Ret.d.b = DysymtabLoadCmd.nextrel; // Index into the external relocations
  2038. return relocation_iterator(RelocationRef(Ret, this));
  2039. }
  2040. relocation_iterator MachOObjectFile::locrel_begin() const {
  2041. DataRefImpl Ret;
  2042. // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
  2043. Ret.d.a = 1; // Would normally be a section index.
  2044. Ret.d.b = 0; // Index into the local relocations
  2045. return relocation_iterator(RelocationRef(Ret, this));
  2046. }
  2047. relocation_iterator MachOObjectFile::locrel_end() const {
  2048. MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
  2049. DataRefImpl Ret;
  2050. // for DYSYMTAB symbols, Ret.d.a == 1 for local relocations
  2051. Ret.d.a = 1; // Would normally be a section index.
  2052. Ret.d.b = DysymtabLoadCmd.nlocrel; // Index into the local relocations
  2053. return relocation_iterator(RelocationRef(Ret, this));
  2054. }
  2055. void MachOObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
  2056. ++Rel.d.b;
  2057. }
  2058. uint64_t MachOObjectFile::getRelocationOffset(DataRefImpl Rel) const {
  2059. assert((getHeader().filetype == MachO::MH_OBJECT ||
  2060. getHeader().filetype == MachO::MH_KEXT_BUNDLE) &&
  2061. "Only implemented for MH_OBJECT && MH_KEXT_BUNDLE");
  2062. MachO::any_relocation_info RE = getRelocation(Rel);
  2063. return getAnyRelocationAddress(RE);
  2064. }
  2065. symbol_iterator
  2066. MachOObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
  2067. MachO::any_relocation_info RE = getRelocation(Rel);
  2068. if (isRelocationScattered(RE))
  2069. return symbol_end();
  2070. uint32_t SymbolIdx = getPlainRelocationSymbolNum(RE);
  2071. bool isExtern = getPlainRelocationExternal(RE);
  2072. if (!isExtern)
  2073. return symbol_end();
  2074. MachO::symtab_command S = getSymtabLoadCommand();
  2075. unsigned SymbolTableEntrySize = is64Bit() ?
  2076. sizeof(MachO::nlist_64) :
  2077. sizeof(MachO::nlist);
  2078. uint64_t Offset = S.symoff + SymbolIdx * SymbolTableEntrySize;
  2079. DataRefImpl Sym;
  2080. Sym.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
  2081. return symbol_iterator(SymbolRef(Sym, this));
  2082. }
  2083. section_iterator
  2084. MachOObjectFile::getRelocationSection(DataRefImpl Rel) const {
  2085. return section_iterator(getAnyRelocationSection(getRelocation(Rel)));
  2086. }
  2087. uint64_t MachOObjectFile::getRelocationType(DataRefImpl Rel) const {
  2088. MachO::any_relocation_info RE = getRelocation(Rel);
  2089. return getAnyRelocationType(RE);
  2090. }
  2091. void MachOObjectFile::getRelocationTypeName(
  2092. DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
  2093. StringRef res;
  2094. uint64_t RType = getRelocationType(Rel);
  2095. unsigned Arch = this->getArch();
  2096. switch (Arch) {
  2097. case Triple::x86: {
  2098. static const char *const Table[] = {
  2099. "GENERIC_RELOC_VANILLA",
  2100. "GENERIC_RELOC_PAIR",
  2101. "GENERIC_RELOC_SECTDIFF",
  2102. "GENERIC_RELOC_PB_LA_PTR",
  2103. "GENERIC_RELOC_LOCAL_SECTDIFF",
  2104. "GENERIC_RELOC_TLV" };
  2105. if (RType > 5)
  2106. res = "Unknown";
  2107. else
  2108. res = Table[RType];
  2109. break;
  2110. }
  2111. case Triple::x86_64: {
  2112. static const char *const Table[] = {
  2113. "X86_64_RELOC_UNSIGNED",
  2114. "X86_64_RELOC_SIGNED",
  2115. "X86_64_RELOC_BRANCH",
  2116. "X86_64_RELOC_GOT_LOAD",
  2117. "X86_64_RELOC_GOT",
  2118. "X86_64_RELOC_SUBTRACTOR",
  2119. "X86_64_RELOC_SIGNED_1",
  2120. "X86_64_RELOC_SIGNED_2",
  2121. "X86_64_RELOC_SIGNED_4",
  2122. "X86_64_RELOC_TLV" };
  2123. if (RType > 9)
  2124. res = "Unknown";
  2125. else
  2126. res = Table[RType];
  2127. break;
  2128. }
  2129. case Triple::arm: {
  2130. static const char *const Table[] = {
  2131. "ARM_RELOC_VANILLA",
  2132. "ARM_RELOC_PAIR",
  2133. "ARM_RELOC_SECTDIFF",
  2134. "ARM_RELOC_LOCAL_SECTDIFF",
  2135. "ARM_RELOC_PB_LA_PTR",
  2136. "ARM_RELOC_BR24",
  2137. "ARM_THUMB_RELOC_BR22",
  2138. "ARM_THUMB_32BIT_BRANCH",
  2139. "ARM_RELOC_HALF",
  2140. "ARM_RELOC_HALF_SECTDIFF" };
  2141. if (RType > 9)
  2142. res = "Unknown";
  2143. else
  2144. res = Table[RType];
  2145. break;
  2146. }
  2147. case Triple::aarch64:
  2148. case Triple::aarch64_32: {
  2149. static const char *const Table[] = {
  2150. "ARM64_RELOC_UNSIGNED", "ARM64_RELOC_SUBTRACTOR",
  2151. "ARM64_RELOC_BRANCH26", "ARM64_RELOC_PAGE21",
  2152. "ARM64_RELOC_PAGEOFF12", "ARM64_RELOC_GOT_LOAD_PAGE21",
  2153. "ARM64_RELOC_GOT_LOAD_PAGEOFF12", "ARM64_RELOC_POINTER_TO_GOT",
  2154. "ARM64_RELOC_TLVP_LOAD_PAGE21", "ARM64_RELOC_TLVP_LOAD_PAGEOFF12",
  2155. "ARM64_RELOC_ADDEND"
  2156. };
  2157. if (RType >= array_lengthof(Table))
  2158. res = "Unknown";
  2159. else
  2160. res = Table[RType];
  2161. break;
  2162. }
  2163. case Triple::ppc: {
  2164. static const char *const Table[] = {
  2165. "PPC_RELOC_VANILLA",
  2166. "PPC_RELOC_PAIR",
  2167. "PPC_RELOC_BR14",
  2168. "PPC_RELOC_BR24",
  2169. "PPC_RELOC_HI16",
  2170. "PPC_RELOC_LO16",
  2171. "PPC_RELOC_HA16",
  2172. "PPC_RELOC_LO14",
  2173. "PPC_RELOC_SECTDIFF",
  2174. "PPC_RELOC_PB_LA_PTR",
  2175. "PPC_RELOC_HI16_SECTDIFF",
  2176. "PPC_RELOC_LO16_SECTDIFF",
  2177. "PPC_RELOC_HA16_SECTDIFF",
  2178. "PPC_RELOC_JBSR",
  2179. "PPC_RELOC_LO14_SECTDIFF",
  2180. "PPC_RELOC_LOCAL_SECTDIFF" };
  2181. if (RType > 15)
  2182. res = "Unknown";
  2183. else
  2184. res = Table[RType];
  2185. break;
  2186. }
  2187. case Triple::UnknownArch:
  2188. res = "Unknown";
  2189. break;
  2190. }
  2191. Result.append(res.begin(), res.end());
  2192. }
  2193. uint8_t MachOObjectFile::getRelocationLength(DataRefImpl Rel) const {
  2194. MachO::any_relocation_info RE = getRelocation(Rel);
  2195. return getAnyRelocationLength(RE);
  2196. }
  2197. //
  2198. // guessLibraryShortName() is passed a name of a dynamic library and returns a
  2199. // guess on what the short name is. Then name is returned as a substring of the
  2200. // StringRef Name passed in. The name of the dynamic library is recognized as
  2201. // a framework if it has one of the two following forms:
  2202. // Foo.framework/Versions/A/Foo
  2203. // Foo.framework/Foo
  2204. // Where A and Foo can be any string. And may contain a trailing suffix
  2205. // starting with an underbar. If the Name is recognized as a framework then
  2206. // isFramework is set to true else it is set to false. If the Name has a
  2207. // suffix then Suffix is set to the substring in Name that contains the suffix
  2208. // else it is set to a NULL StringRef.
  2209. //
  2210. // The Name of the dynamic library is recognized as a library name if it has
  2211. // one of the two following forms:
  2212. // libFoo.A.dylib
  2213. // libFoo.dylib
  2214. //
  2215. // The library may have a suffix trailing the name Foo of the form:
  2216. // libFoo_profile.A.dylib
  2217. // libFoo_profile.dylib
  2218. // These dyld image suffixes are separated from the short name by a '_'
  2219. // character. Because the '_' character is commonly used to separate words in
  2220. // filenames guessLibraryShortName() cannot reliably separate a dylib's short
  2221. // name from an arbitrary image suffix; imagine if both the short name and the
  2222. // suffix contains an '_' character! To better deal with this ambiguity,
  2223. // guessLibraryShortName() will recognize only "_debug" and "_profile" as valid
  2224. // Suffix values. Calling code needs to be tolerant of guessLibraryShortName()
  2225. // guessing incorrectly.
  2226. //
  2227. // The Name of the dynamic library is also recognized as a library name if it
  2228. // has the following form:
  2229. // Foo.qtx
  2230. //
  2231. // If the Name of the dynamic library is none of the forms above then a NULL
  2232. // StringRef is returned.
  2233. StringRef MachOObjectFile::guessLibraryShortName(StringRef Name,
  2234. bool &isFramework,
  2235. StringRef &Suffix) {
  2236. StringRef Foo, F, DotFramework, V, Dylib, Lib, Dot, Qtx;
  2237. size_t a, b, c, d, Idx;
  2238. isFramework = false;
  2239. Suffix = StringRef();
  2240. // Pull off the last component and make Foo point to it
  2241. a = Name.rfind('/');
  2242. if (a == Name.npos || a == 0)
  2243. goto guess_library;
  2244. Foo = Name.slice(a+1, Name.npos);
  2245. // Look for a suffix starting with a '_'
  2246. Idx = Foo.rfind('_');
  2247. if (Idx != Foo.npos && Foo.size() >= 2) {
  2248. Suffix = Foo.slice(Idx, Foo.npos);
  2249. if (Suffix != "_debug" && Suffix != "_profile")
  2250. Suffix = StringRef();
  2251. else
  2252. Foo = Foo.slice(0, Idx);
  2253. }
  2254. // First look for the form Foo.framework/Foo
  2255. b = Name.rfind('/', a);
  2256. if (b == Name.npos)
  2257. Idx = 0;
  2258. else
  2259. Idx = b+1;
  2260. F = Name.slice(Idx, Idx + Foo.size());
  2261. DotFramework = Name.slice(Idx + Foo.size(),
  2262. Idx + Foo.size() + sizeof(".framework/")-1);
  2263. if (F == Foo && DotFramework == ".framework/") {
  2264. isFramework = true;
  2265. return Foo;
  2266. }
  2267. // Next look for the form Foo.framework/Versions/A/Foo
  2268. if (b == Name.npos)
  2269. goto guess_library;
  2270. c = Name.rfind('/', b);
  2271. if (c == Name.npos || c == 0)
  2272. goto guess_library;
  2273. V = Name.slice(c+1, Name.npos);
  2274. if (!V.startswith("Versions/"))
  2275. goto guess_library;
  2276. d = Name.rfind('/', c);
  2277. if (d == Name.npos)
  2278. Idx = 0;
  2279. else
  2280. Idx = d+1;
  2281. F = Name.slice(Idx, Idx + Foo.size());
  2282. DotFramework = Name.slice(Idx + Foo.size(),
  2283. Idx + Foo.size() + sizeof(".framework/")-1);
  2284. if (F == Foo && DotFramework == ".framework/") {
  2285. isFramework = true;
  2286. return Foo;
  2287. }
  2288. guess_library:
  2289. // pull off the suffix after the "." and make a point to it
  2290. a = Name.rfind('.');
  2291. if (a == Name.npos || a == 0)
  2292. return StringRef();
  2293. Dylib = Name.slice(a, Name.npos);
  2294. if (Dylib != ".dylib")
  2295. goto guess_qtx;
  2296. // First pull off the version letter for the form Foo.A.dylib if any.
  2297. if (a >= 3) {
  2298. Dot = Name.slice(a-2, a-1);
  2299. if (Dot == ".")
  2300. a = a - 2;
  2301. }
  2302. b = Name.rfind('/', a);
  2303. if (b == Name.npos)
  2304. b = 0;
  2305. else
  2306. b = b+1;
  2307. // ignore any suffix after an underbar like Foo_profile.A.dylib
  2308. Idx = Name.rfind('_');
  2309. if (Idx != Name.npos && Idx != b) {
  2310. Lib = Name.slice(b, Idx);
  2311. Suffix = Name.slice(Idx, a);
  2312. if (Suffix != "_debug" && Suffix != "_profile") {
  2313. Suffix = StringRef();
  2314. Lib = Name.slice(b, a);
  2315. }
  2316. }
  2317. else
  2318. Lib = Name.slice(b, a);
  2319. // There are incorrect library names of the form:
  2320. // libATS.A_profile.dylib so check for these.
  2321. if (Lib.size() >= 3) {
  2322. Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
  2323. if (Dot == ".")
  2324. Lib = Lib.slice(0, Lib.size()-2);
  2325. }
  2326. return Lib;
  2327. guess_qtx:
  2328. Qtx = Name.slice(a, Name.npos);
  2329. if (Qtx != ".qtx")
  2330. return StringRef();
  2331. b = Name.rfind('/', a);
  2332. if (b == Name.npos)
  2333. Lib = Name.slice(0, a);
  2334. else
  2335. Lib = Name.slice(b+1, a);
  2336. // There are library names of the form: QT.A.qtx so check for these.
  2337. if (Lib.size() >= 3) {
  2338. Dot = Lib.slice(Lib.size()-2, Lib.size()-1);
  2339. if (Dot == ".")
  2340. Lib = Lib.slice(0, Lib.size()-2);
  2341. }
  2342. return Lib;
  2343. }
  2344. // getLibraryShortNameByIndex() is used to get the short name of the library
  2345. // for an undefined symbol in a linked Mach-O binary that was linked with the
  2346. // normal two-level namespace default (that is MH_TWOLEVEL in the header).
  2347. // It is passed the index (0 - based) of the library as translated from
  2348. // GET_LIBRARY_ORDINAL (1 - based).
  2349. std::error_code MachOObjectFile::getLibraryShortNameByIndex(unsigned Index,
  2350. StringRef &Res) const {
  2351. if (Index >= Libraries.size())
  2352. return object_error::parse_failed;
  2353. // If the cache of LibrariesShortNames is not built up do that first for
  2354. // all the Libraries.
  2355. if (LibrariesShortNames.size() == 0) {
  2356. for (unsigned i = 0; i < Libraries.size(); i++) {
  2357. auto CommandOrErr =
  2358. getStructOrErr<MachO::dylib_command>(*this, Libraries[i]);
  2359. if (!CommandOrErr)
  2360. return object_error::parse_failed;
  2361. MachO::dylib_command D = CommandOrErr.get();
  2362. if (D.dylib.name >= D.cmdsize)
  2363. return object_error::parse_failed;
  2364. const char *P = (const char *)(Libraries[i]) + D.dylib.name;
  2365. StringRef Name = StringRef(P);
  2366. if (D.dylib.name+Name.size() >= D.cmdsize)
  2367. return object_error::parse_failed;
  2368. StringRef Suffix;
  2369. bool isFramework;
  2370. StringRef shortName = guessLibraryShortName(Name, isFramework, Suffix);
  2371. if (shortName.empty())
  2372. LibrariesShortNames.push_back(Name);
  2373. else
  2374. LibrariesShortNames.push_back(shortName);
  2375. }
  2376. }
  2377. Res = LibrariesShortNames[Index];
  2378. return std::error_code();
  2379. }
  2380. uint32_t MachOObjectFile::getLibraryCount() const {
  2381. return Libraries.size();
  2382. }
  2383. section_iterator
  2384. MachOObjectFile::getRelocationRelocatedSection(relocation_iterator Rel) const {
  2385. DataRefImpl Sec;
  2386. Sec.d.a = Rel->getRawDataRefImpl().d.a;
  2387. return section_iterator(SectionRef(Sec, this));
  2388. }
  2389. basic_symbol_iterator MachOObjectFile::symbol_begin() const {
  2390. DataRefImpl DRI;
  2391. MachO::symtab_command Symtab = getSymtabLoadCommand();
  2392. if (!SymtabLoadCmd || Symtab.nsyms == 0)
  2393. return basic_symbol_iterator(SymbolRef(DRI, this));
  2394. return getSymbolByIndex(0);
  2395. }
  2396. basic_symbol_iterator MachOObjectFile::symbol_end() const {
  2397. DataRefImpl DRI;
  2398. MachO::symtab_command Symtab = getSymtabLoadCommand();
  2399. if (!SymtabLoadCmd || Symtab.nsyms == 0)
  2400. return basic_symbol_iterator(SymbolRef(DRI, this));
  2401. unsigned SymbolTableEntrySize = is64Bit() ?
  2402. sizeof(MachO::nlist_64) :
  2403. sizeof(MachO::nlist);
  2404. unsigned Offset = Symtab.symoff +
  2405. Symtab.nsyms * SymbolTableEntrySize;
  2406. DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
  2407. return basic_symbol_iterator(SymbolRef(DRI, this));
  2408. }
  2409. symbol_iterator MachOObjectFile::getSymbolByIndex(unsigned Index) const {
  2410. MachO::symtab_command Symtab = getSymtabLoadCommand();
  2411. if (!SymtabLoadCmd || Index >= Symtab.nsyms)
  2412. report_fatal_error("Requested symbol index is out of range.");
  2413. unsigned SymbolTableEntrySize =
  2414. is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
  2415. DataRefImpl DRI;
  2416. DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
  2417. DRI.p += Index * SymbolTableEntrySize;
  2418. return basic_symbol_iterator(SymbolRef(DRI, this));
  2419. }
  2420. uint64_t MachOObjectFile::getSymbolIndex(DataRefImpl Symb) const {
  2421. MachO::symtab_command Symtab = getSymtabLoadCommand();
  2422. if (!SymtabLoadCmd)
  2423. report_fatal_error("getSymbolIndex() called with no symbol table symbol");
  2424. unsigned SymbolTableEntrySize =
  2425. is64Bit() ? sizeof(MachO::nlist_64) : sizeof(MachO::nlist);
  2426. DataRefImpl DRIstart;
  2427. DRIstart.p = reinterpret_cast<uintptr_t>(getPtr(*this, Symtab.symoff));
  2428. uint64_t Index = (Symb.p - DRIstart.p) / SymbolTableEntrySize;
  2429. return Index;
  2430. }
  2431. section_iterator MachOObjectFile::section_begin() const {
  2432. DataRefImpl DRI;
  2433. return section_iterator(SectionRef(DRI, this));
  2434. }
  2435. section_iterator MachOObjectFile::section_end() const {
  2436. DataRefImpl DRI;
  2437. DRI.d.a = Sections.size();
  2438. return section_iterator(SectionRef(DRI, this));
  2439. }
  2440. uint8_t MachOObjectFile::getBytesInAddress() const {
  2441. return is64Bit() ? 8 : 4;
  2442. }
  2443. StringRef MachOObjectFile::getFileFormatName() const {
  2444. unsigned CPUType = getCPUType(*this);
  2445. if (!is64Bit()) {
  2446. switch (CPUType) {
  2447. case MachO::CPU_TYPE_I386:
  2448. return "Mach-O 32-bit i386";
  2449. case MachO::CPU_TYPE_ARM:
  2450. return "Mach-O arm";
  2451. case MachO::CPU_TYPE_ARM64_32:
  2452. return "Mach-O arm64 (ILP32)";
  2453. case MachO::CPU_TYPE_POWERPC:
  2454. return "Mach-O 32-bit ppc";
  2455. default:
  2456. return "Mach-O 32-bit unknown";
  2457. }
  2458. }
  2459. switch (CPUType) {
  2460. case MachO::CPU_TYPE_X86_64:
  2461. return "Mach-O 64-bit x86-64";
  2462. case MachO::CPU_TYPE_ARM64:
  2463. return "Mach-O arm64";
  2464. case MachO::CPU_TYPE_POWERPC64:
  2465. return "Mach-O 64-bit ppc64";
  2466. default:
  2467. return "Mach-O 64-bit unknown";
  2468. }
  2469. }
  2470. Triple::ArchType MachOObjectFile::getArch(uint32_t CPUType, uint32_t CPUSubType) {
  2471. switch (CPUType) {
  2472. case MachO::CPU_TYPE_I386:
  2473. return Triple::x86;
  2474. case MachO::CPU_TYPE_X86_64:
  2475. return Triple::x86_64;
  2476. case MachO::CPU_TYPE_ARM:
  2477. return Triple::arm;
  2478. case MachO::CPU_TYPE_ARM64:
  2479. return Triple::aarch64;
  2480. case MachO::CPU_TYPE_ARM64_32:
  2481. return Triple::aarch64_32;
  2482. case MachO::CPU_TYPE_POWERPC:
  2483. return Triple::ppc;
  2484. case MachO::CPU_TYPE_POWERPC64:
  2485. return Triple::ppc64;
  2486. default:
  2487. return Triple::UnknownArch;
  2488. }
  2489. }
  2490. Triple MachOObjectFile::getArchTriple(uint32_t CPUType, uint32_t CPUSubType,
  2491. const char **McpuDefault,
  2492. const char **ArchFlag) {
  2493. if (McpuDefault)
  2494. *McpuDefault = nullptr;
  2495. if (ArchFlag)
  2496. *ArchFlag = nullptr;
  2497. switch (CPUType) {
  2498. case MachO::CPU_TYPE_I386:
  2499. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2500. case MachO::CPU_SUBTYPE_I386_ALL:
  2501. if (ArchFlag)
  2502. *ArchFlag = "i386";
  2503. return Triple("i386-apple-darwin");
  2504. default:
  2505. return Triple();
  2506. }
  2507. case MachO::CPU_TYPE_X86_64:
  2508. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2509. case MachO::CPU_SUBTYPE_X86_64_ALL:
  2510. if (ArchFlag)
  2511. *ArchFlag = "x86_64";
  2512. return Triple("x86_64-apple-darwin");
  2513. case MachO::CPU_SUBTYPE_X86_64_H:
  2514. if (ArchFlag)
  2515. *ArchFlag = "x86_64h";
  2516. return Triple("x86_64h-apple-darwin");
  2517. default:
  2518. return Triple();
  2519. }
  2520. case MachO::CPU_TYPE_ARM:
  2521. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2522. case MachO::CPU_SUBTYPE_ARM_V4T:
  2523. if (ArchFlag)
  2524. *ArchFlag = "armv4t";
  2525. return Triple("armv4t-apple-darwin");
  2526. case MachO::CPU_SUBTYPE_ARM_V5TEJ:
  2527. if (ArchFlag)
  2528. *ArchFlag = "armv5e";
  2529. return Triple("armv5e-apple-darwin");
  2530. case MachO::CPU_SUBTYPE_ARM_XSCALE:
  2531. if (ArchFlag)
  2532. *ArchFlag = "xscale";
  2533. return Triple("xscale-apple-darwin");
  2534. case MachO::CPU_SUBTYPE_ARM_V6:
  2535. if (ArchFlag)
  2536. *ArchFlag = "armv6";
  2537. return Triple("armv6-apple-darwin");
  2538. case MachO::CPU_SUBTYPE_ARM_V6M:
  2539. if (McpuDefault)
  2540. *McpuDefault = "cortex-m0";
  2541. if (ArchFlag)
  2542. *ArchFlag = "armv6m";
  2543. return Triple("armv6m-apple-darwin");
  2544. case MachO::CPU_SUBTYPE_ARM_V7:
  2545. if (ArchFlag)
  2546. *ArchFlag = "armv7";
  2547. return Triple("armv7-apple-darwin");
  2548. case MachO::CPU_SUBTYPE_ARM_V7EM:
  2549. if (McpuDefault)
  2550. *McpuDefault = "cortex-m4";
  2551. if (ArchFlag)
  2552. *ArchFlag = "armv7em";
  2553. return Triple("thumbv7em-apple-darwin");
  2554. case MachO::CPU_SUBTYPE_ARM_V7K:
  2555. if (McpuDefault)
  2556. *McpuDefault = "cortex-a7";
  2557. if (ArchFlag)
  2558. *ArchFlag = "armv7k";
  2559. return Triple("armv7k-apple-darwin");
  2560. case MachO::CPU_SUBTYPE_ARM_V7M:
  2561. if (McpuDefault)
  2562. *McpuDefault = "cortex-m3";
  2563. if (ArchFlag)
  2564. *ArchFlag = "armv7m";
  2565. return Triple("thumbv7m-apple-darwin");
  2566. case MachO::CPU_SUBTYPE_ARM_V7S:
  2567. if (McpuDefault)
  2568. *McpuDefault = "cortex-a7";
  2569. if (ArchFlag)
  2570. *ArchFlag = "armv7s";
  2571. return Triple("armv7s-apple-darwin");
  2572. default:
  2573. return Triple();
  2574. }
  2575. case MachO::CPU_TYPE_ARM64:
  2576. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2577. case MachO::CPU_SUBTYPE_ARM64_ALL:
  2578. if (McpuDefault)
  2579. *McpuDefault = "cyclone";
  2580. if (ArchFlag)
  2581. *ArchFlag = "arm64";
  2582. return Triple("arm64-apple-darwin");
  2583. case MachO::CPU_SUBTYPE_ARM64E:
  2584. if (McpuDefault)
  2585. *McpuDefault = "apple-a12";
  2586. if (ArchFlag)
  2587. *ArchFlag = "arm64e";
  2588. return Triple("arm64e-apple-darwin");
  2589. default:
  2590. return Triple();
  2591. }
  2592. case MachO::CPU_TYPE_ARM64_32:
  2593. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2594. case MachO::CPU_SUBTYPE_ARM64_32_V8:
  2595. if (McpuDefault)
  2596. *McpuDefault = "cyclone";
  2597. if (ArchFlag)
  2598. *ArchFlag = "arm64_32";
  2599. return Triple("arm64_32-apple-darwin");
  2600. default:
  2601. return Triple();
  2602. }
  2603. case MachO::CPU_TYPE_POWERPC:
  2604. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2605. case MachO::CPU_SUBTYPE_POWERPC_ALL:
  2606. if (ArchFlag)
  2607. *ArchFlag = "ppc";
  2608. return Triple("ppc-apple-darwin");
  2609. default:
  2610. return Triple();
  2611. }
  2612. case MachO::CPU_TYPE_POWERPC64:
  2613. switch (CPUSubType & ~MachO::CPU_SUBTYPE_MASK) {
  2614. case MachO::CPU_SUBTYPE_POWERPC_ALL:
  2615. if (ArchFlag)
  2616. *ArchFlag = "ppc64";
  2617. return Triple("ppc64-apple-darwin");
  2618. default:
  2619. return Triple();
  2620. }
  2621. default:
  2622. return Triple();
  2623. }
  2624. }
  2625. Triple MachOObjectFile::getHostArch() {
  2626. return Triple(sys::getDefaultTargetTriple());
  2627. }
  2628. bool MachOObjectFile::isValidArch(StringRef ArchFlag) {
  2629. auto validArchs = getValidArchs();
  2630. return llvm::is_contained(validArchs, ArchFlag);
  2631. }
  2632. ArrayRef<StringRef> MachOObjectFile::getValidArchs() {
  2633. static const std::array<StringRef, 18> ValidArchs = {{
  2634. "i386",
  2635. "x86_64",
  2636. "x86_64h",
  2637. "armv4t",
  2638. "arm",
  2639. "armv5e",
  2640. "armv6",
  2641. "armv6m",
  2642. "armv7",
  2643. "armv7em",
  2644. "armv7k",
  2645. "armv7m",
  2646. "armv7s",
  2647. "arm64",
  2648. "arm64e",
  2649. "arm64_32",
  2650. "ppc",
  2651. "ppc64",
  2652. }};
  2653. return ValidArchs;
  2654. }
  2655. Triple::ArchType MachOObjectFile::getArch() const {
  2656. return getArch(getCPUType(*this), getCPUSubType(*this));
  2657. }
  2658. Triple MachOObjectFile::getArchTriple(const char **McpuDefault) const {
  2659. return getArchTriple(Header.cputype, Header.cpusubtype, McpuDefault);
  2660. }
  2661. relocation_iterator MachOObjectFile::section_rel_begin(unsigned Index) const {
  2662. DataRefImpl DRI;
  2663. DRI.d.a = Index;
  2664. return section_rel_begin(DRI);
  2665. }
  2666. relocation_iterator MachOObjectFile::section_rel_end(unsigned Index) const {
  2667. DataRefImpl DRI;
  2668. DRI.d.a = Index;
  2669. return section_rel_end(DRI);
  2670. }
  2671. dice_iterator MachOObjectFile::begin_dices() const {
  2672. DataRefImpl DRI;
  2673. if (!DataInCodeLoadCmd)
  2674. return dice_iterator(DiceRef(DRI, this));
  2675. MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
  2676. DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, DicLC.dataoff));
  2677. return dice_iterator(DiceRef(DRI, this));
  2678. }
  2679. dice_iterator MachOObjectFile::end_dices() const {
  2680. DataRefImpl DRI;
  2681. if (!DataInCodeLoadCmd)
  2682. return dice_iterator(DiceRef(DRI, this));
  2683. MachO::linkedit_data_command DicLC = getDataInCodeLoadCommand();
  2684. unsigned Offset = DicLC.dataoff + DicLC.datasize;
  2685. DRI.p = reinterpret_cast<uintptr_t>(getPtr(*this, Offset));
  2686. return dice_iterator(DiceRef(DRI, this));
  2687. }
  2688. ExportEntry::ExportEntry(Error *E, const MachOObjectFile *O,
  2689. ArrayRef<uint8_t> T) : E(E), O(O), Trie(T) {}
  2690. void ExportEntry::moveToFirst() {
  2691. ErrorAsOutParameter ErrAsOutParam(E);
  2692. pushNode(0);
  2693. if (*E)
  2694. return;
  2695. pushDownUntilBottom();
  2696. }
  2697. void ExportEntry::moveToEnd() {
  2698. Stack.clear();
  2699. Done = true;
  2700. }
  2701. bool ExportEntry::operator==(const ExportEntry &Other) const {
  2702. // Common case, one at end, other iterating from begin.
  2703. if (Done || Other.Done)
  2704. return (Done == Other.Done);
  2705. // Not equal if different stack sizes.
  2706. if (Stack.size() != Other.Stack.size())
  2707. return false;
  2708. // Not equal if different cumulative strings.
  2709. if (!CumulativeString.equals(Other.CumulativeString))
  2710. return false;
  2711. // Equal if all nodes in both stacks match.
  2712. for (unsigned i=0; i < Stack.size(); ++i) {
  2713. if (Stack[i].Start != Other.Stack[i].Start)
  2714. return false;
  2715. }
  2716. return true;
  2717. }
  2718. uint64_t ExportEntry::readULEB128(const uint8_t *&Ptr, const char **error) {
  2719. unsigned Count;
  2720. uint64_t Result = decodeULEB128(Ptr, &Count, Trie.end(), error);
  2721. Ptr += Count;
  2722. if (Ptr > Trie.end())
  2723. Ptr = Trie.end();
  2724. return Result;
  2725. }
  2726. StringRef ExportEntry::name() const {
  2727. return CumulativeString;
  2728. }
  2729. uint64_t ExportEntry::flags() const {
  2730. return Stack.back().Flags;
  2731. }
  2732. uint64_t ExportEntry::address() const {
  2733. return Stack.back().Address;
  2734. }
  2735. uint64_t ExportEntry::other() const {
  2736. return Stack.back().Other;
  2737. }
  2738. StringRef ExportEntry::otherName() const {
  2739. const char* ImportName = Stack.back().ImportName;
  2740. if (ImportName)
  2741. return StringRef(ImportName);
  2742. return StringRef();
  2743. }
  2744. uint32_t ExportEntry::nodeOffset() const {
  2745. return Stack.back().Start - Trie.begin();
  2746. }
  2747. ExportEntry::NodeState::NodeState(const uint8_t *Ptr)
  2748. : Start(Ptr), Current(Ptr) {}
  2749. void ExportEntry::pushNode(uint64_t offset) {
  2750. ErrorAsOutParameter ErrAsOutParam(E);
  2751. const uint8_t *Ptr = Trie.begin() + offset;
  2752. NodeState State(Ptr);
  2753. const char *error;
  2754. uint64_t ExportInfoSize = readULEB128(State.Current, &error);
  2755. if (error) {
  2756. *E = malformedError("export info size " + Twine(error) +
  2757. " in export trie data at node: 0x" +
  2758. Twine::utohexstr(offset));
  2759. moveToEnd();
  2760. return;
  2761. }
  2762. State.IsExportNode = (ExportInfoSize != 0);
  2763. const uint8_t* Children = State.Current + ExportInfoSize;
  2764. if (Children > Trie.end()) {
  2765. *E = malformedError(
  2766. "export info size: 0x" + Twine::utohexstr(ExportInfoSize) +
  2767. " in export trie data at node: 0x" + Twine::utohexstr(offset) +
  2768. " too big and extends past end of trie data");
  2769. moveToEnd();
  2770. return;
  2771. }
  2772. if (State.IsExportNode) {
  2773. const uint8_t *ExportStart = State.Current;
  2774. State.Flags = readULEB128(State.Current, &error);
  2775. if (error) {
  2776. *E = malformedError("flags " + Twine(error) +
  2777. " in export trie data at node: 0x" +
  2778. Twine::utohexstr(offset));
  2779. moveToEnd();
  2780. return;
  2781. }
  2782. uint64_t Kind = State.Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK;
  2783. if (State.Flags != 0 &&
  2784. (Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_REGULAR &&
  2785. Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE &&
  2786. Kind != MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL)) {
  2787. *E = malformedError(
  2788. "unsupported exported symbol kind: " + Twine((int)Kind) +
  2789. " in flags: 0x" + Twine::utohexstr(State.Flags) +
  2790. " in export trie data at node: 0x" + Twine::utohexstr(offset));
  2791. moveToEnd();
  2792. return;
  2793. }
  2794. if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT) {
  2795. State.Address = 0;
  2796. State.Other = readULEB128(State.Current, &error); // dylib ordinal
  2797. if (error) {
  2798. *E = malformedError("dylib ordinal of re-export " + Twine(error) +
  2799. " in export trie data at node: 0x" +
  2800. Twine::utohexstr(offset));
  2801. moveToEnd();
  2802. return;
  2803. }
  2804. if (O != nullptr) {
  2805. if (State.Other > O->getLibraryCount()) {
  2806. *E = malformedError(
  2807. "bad library ordinal: " + Twine((int)State.Other) + " (max " +
  2808. Twine((int)O->getLibraryCount()) +
  2809. ") in export trie data at node: 0x" + Twine::utohexstr(offset));
  2810. moveToEnd();
  2811. return;
  2812. }
  2813. }
  2814. State.ImportName = reinterpret_cast<const char*>(State.Current);
  2815. if (*State.ImportName == '\0') {
  2816. State.Current++;
  2817. } else {
  2818. const uint8_t *End = State.Current + 1;
  2819. if (End >= Trie.end()) {
  2820. *E = malformedError("import name of re-export in export trie data at "
  2821. "node: 0x" +
  2822. Twine::utohexstr(offset) +
  2823. " starts past end of trie data");
  2824. moveToEnd();
  2825. return;
  2826. }
  2827. while(*End != '\0' && End < Trie.end())
  2828. End++;
  2829. if (*End != '\0') {
  2830. *E = malformedError("import name of re-export in export trie data at "
  2831. "node: 0x" +
  2832. Twine::utohexstr(offset) +
  2833. " extends past end of trie data");
  2834. moveToEnd();
  2835. return;
  2836. }
  2837. State.Current = End + 1;
  2838. }
  2839. } else {
  2840. State.Address = readULEB128(State.Current, &error);
  2841. if (error) {
  2842. *E = malformedError("address " + Twine(error) +
  2843. " in export trie data at node: 0x" +
  2844. Twine::utohexstr(offset));
  2845. moveToEnd();
  2846. return;
  2847. }
  2848. if (State.Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
  2849. State.Other = readULEB128(State.Current, &error);
  2850. if (error) {
  2851. *E = malformedError("resolver of stub and resolver " + Twine(error) +
  2852. " in export trie data at node: 0x" +
  2853. Twine::utohexstr(offset));
  2854. moveToEnd();
  2855. return;
  2856. }
  2857. }
  2858. }
  2859. if(ExportStart + ExportInfoSize != State.Current) {
  2860. *E = malformedError(
  2861. "inconsistant export info size: 0x" +
  2862. Twine::utohexstr(ExportInfoSize) + " where actual size was: 0x" +
  2863. Twine::utohexstr(State.Current - ExportStart) +
  2864. " in export trie data at node: 0x" + Twine::utohexstr(offset));
  2865. moveToEnd();
  2866. return;
  2867. }
  2868. }
  2869. State.ChildCount = *Children;
  2870. if (State.ChildCount != 0 && Children + 1 >= Trie.end()) {
  2871. *E = malformedError("byte for count of childern in export trie data at "
  2872. "node: 0x" +
  2873. Twine::utohexstr(offset) +
  2874. " extends past end of trie data");
  2875. moveToEnd();
  2876. return;
  2877. }
  2878. State.Current = Children + 1;
  2879. State.NextChildIndex = 0;
  2880. State.ParentStringLength = CumulativeString.size();
  2881. Stack.push_back(State);
  2882. }
  2883. void ExportEntry::pushDownUntilBottom() {
  2884. ErrorAsOutParameter ErrAsOutParam(E);
  2885. const char *error;
  2886. while (Stack.back().NextChildIndex < Stack.back().ChildCount) {
  2887. NodeState &Top = Stack.back();
  2888. CumulativeString.resize(Top.ParentStringLength);
  2889. for (;*Top.Current != 0 && Top.Current < Trie.end(); Top.Current++) {
  2890. char C = *Top.Current;
  2891. CumulativeString.push_back(C);
  2892. }
  2893. if (Top.Current >= Trie.end()) {
  2894. *E = malformedError("edge sub-string in export trie data at node: 0x" +
  2895. Twine::utohexstr(Top.Start - Trie.begin()) +
  2896. " for child #" + Twine((int)Top.NextChildIndex) +
  2897. " extends past end of trie data");
  2898. moveToEnd();
  2899. return;
  2900. }
  2901. Top.Current += 1;
  2902. uint64_t childNodeIndex = readULEB128(Top.Current, &error);
  2903. if (error) {
  2904. *E = malformedError("child node offset " + Twine(error) +
  2905. " in export trie data at node: 0x" +
  2906. Twine::utohexstr(Top.Start - Trie.begin()));
  2907. moveToEnd();
  2908. return;
  2909. }
  2910. for (const NodeState &node : nodes()) {
  2911. if (node.Start == Trie.begin() + childNodeIndex){
  2912. *E = malformedError("loop in childern in export trie data at node: 0x" +
  2913. Twine::utohexstr(Top.Start - Trie.begin()) +
  2914. " back to node: 0x" +
  2915. Twine::utohexstr(childNodeIndex));
  2916. moveToEnd();
  2917. return;
  2918. }
  2919. }
  2920. Top.NextChildIndex += 1;
  2921. pushNode(childNodeIndex);
  2922. if (*E)
  2923. return;
  2924. }
  2925. if (!Stack.back().IsExportNode) {
  2926. *E = malformedError("node is not an export node in export trie data at "
  2927. "node: 0x" +
  2928. Twine::utohexstr(Stack.back().Start - Trie.begin()));
  2929. moveToEnd();
  2930. return;
  2931. }
  2932. }
  2933. // We have a trie data structure and need a way to walk it that is compatible
  2934. // with the C++ iterator model. The solution is a non-recursive depth first
  2935. // traversal where the iterator contains a stack of parent nodes along with a
  2936. // string that is the accumulation of all edge strings along the parent chain
  2937. // to this point.
  2938. //
  2939. // There is one "export" node for each exported symbol. But because some
  2940. // symbols may be a prefix of another symbol (e.g. _dup and _dup2), an export
  2941. // node may have child nodes too.
  2942. //
  2943. // The algorithm for moveNext() is to keep moving down the leftmost unvisited
  2944. // child until hitting a node with no children (which is an export node or
  2945. // else the trie is malformed). On the way down, each node is pushed on the
  2946. // stack ivar. If there is no more ways down, it pops up one and tries to go
  2947. // down a sibling path until a childless node is reached.
  2948. void ExportEntry::moveNext() {
  2949. assert(!Stack.empty() && "ExportEntry::moveNext() with empty node stack");
  2950. if (!Stack.back().IsExportNode) {
  2951. *E = malformedError("node is not an export node in export trie data at "
  2952. "node: 0x" +
  2953. Twine::utohexstr(Stack.back().Start - Trie.begin()));
  2954. moveToEnd();
  2955. return;
  2956. }
  2957. Stack.pop_back();
  2958. while (!Stack.empty()) {
  2959. NodeState &Top = Stack.back();
  2960. if (Top.NextChildIndex < Top.ChildCount) {
  2961. pushDownUntilBottom();
  2962. // Now at the next export node.
  2963. return;
  2964. } else {
  2965. if (Top.IsExportNode) {
  2966. // This node has no children but is itself an export node.
  2967. CumulativeString.resize(Top.ParentStringLength);
  2968. return;
  2969. }
  2970. Stack.pop_back();
  2971. }
  2972. }
  2973. Done = true;
  2974. }
  2975. iterator_range<export_iterator>
  2976. MachOObjectFile::exports(Error &E, ArrayRef<uint8_t> Trie,
  2977. const MachOObjectFile *O) {
  2978. ExportEntry Start(&E, O, Trie);
  2979. if (Trie.empty())
  2980. Start.moveToEnd();
  2981. else
  2982. Start.moveToFirst();
  2983. ExportEntry Finish(&E, O, Trie);
  2984. Finish.moveToEnd();
  2985. return make_range(export_iterator(Start), export_iterator(Finish));
  2986. }
  2987. iterator_range<export_iterator> MachOObjectFile::exports(Error &Err) const {
  2988. return exports(Err, getDyldInfoExportsTrie(), this);
  2989. }
  2990. MachORebaseEntry::MachORebaseEntry(Error *E, const MachOObjectFile *O,
  2991. ArrayRef<uint8_t> Bytes, bool is64Bit)
  2992. : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
  2993. PointerSize(is64Bit ? 8 : 4) {}
  2994. void MachORebaseEntry::moveToFirst() {
  2995. Ptr = Opcodes.begin();
  2996. moveNext();
  2997. }
  2998. void MachORebaseEntry::moveToEnd() {
  2999. Ptr = Opcodes.end();
  3000. RemainingLoopCount = 0;
  3001. Done = true;
  3002. }
  3003. void MachORebaseEntry::moveNext() {
  3004. ErrorAsOutParameter ErrAsOutParam(E);
  3005. // If in the middle of some loop, move to next rebasing in loop.
  3006. SegmentOffset += AdvanceAmount;
  3007. if (RemainingLoopCount) {
  3008. --RemainingLoopCount;
  3009. return;
  3010. }
  3011. // REBASE_OPCODE_DONE is only used for padding if we are not aligned to
  3012. // pointer size. Therefore it is possible to reach the end without ever having
  3013. // seen REBASE_OPCODE_DONE.
  3014. if (Ptr == Opcodes.end()) {
  3015. Done = true;
  3016. return;
  3017. }
  3018. bool More = true;
  3019. while (More) {
  3020. // Parse next opcode and set up next loop.
  3021. const uint8_t *OpcodeStart = Ptr;
  3022. uint8_t Byte = *Ptr++;
  3023. uint8_t ImmValue = Byte & MachO::REBASE_IMMEDIATE_MASK;
  3024. uint8_t Opcode = Byte & MachO::REBASE_OPCODE_MASK;
  3025. uint32_t Count, Skip;
  3026. const char *error = nullptr;
  3027. switch (Opcode) {
  3028. case MachO::REBASE_OPCODE_DONE:
  3029. More = false;
  3030. Done = true;
  3031. moveToEnd();
  3032. DEBUG_WITH_TYPE("mach-o-rebase", dbgs() << "REBASE_OPCODE_DONE\n");
  3033. break;
  3034. case MachO::REBASE_OPCODE_SET_TYPE_IMM:
  3035. RebaseType = ImmValue;
  3036. if (RebaseType > MachO::REBASE_TYPE_TEXT_PCREL32) {
  3037. *E = malformedError("for REBASE_OPCODE_SET_TYPE_IMM bad bind type: " +
  3038. Twine((int)RebaseType) + " for opcode at: 0x" +
  3039. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3040. moveToEnd();
  3041. return;
  3042. }
  3043. DEBUG_WITH_TYPE(
  3044. "mach-o-rebase",
  3045. dbgs() << "REBASE_OPCODE_SET_TYPE_IMM: "
  3046. << "RebaseType=" << (int) RebaseType << "\n");
  3047. break;
  3048. case MachO::REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
  3049. SegmentIndex = ImmValue;
  3050. SegmentOffset = readULEB128(&error);
  3051. if (error) {
  3052. *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
  3053. Twine(error) + " for opcode at: 0x" +
  3054. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3055. moveToEnd();
  3056. return;
  3057. }
  3058. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3059. PointerSize);
  3060. if (error) {
  3061. *E = malformedError("for REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
  3062. Twine(error) + " for opcode at: 0x" +
  3063. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3064. moveToEnd();
  3065. return;
  3066. }
  3067. DEBUG_WITH_TYPE(
  3068. "mach-o-rebase",
  3069. dbgs() << "REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
  3070. << "SegmentIndex=" << SegmentIndex << ", "
  3071. << format("SegmentOffset=0x%06X", SegmentOffset)
  3072. << "\n");
  3073. break;
  3074. case MachO::REBASE_OPCODE_ADD_ADDR_ULEB:
  3075. SegmentOffset += readULEB128(&error);
  3076. if (error) {
  3077. *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
  3078. " for opcode at: 0x" +
  3079. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3080. moveToEnd();
  3081. return;
  3082. }
  3083. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3084. PointerSize);
  3085. if (error) {
  3086. *E = malformedError("for REBASE_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
  3087. " for opcode at: 0x" +
  3088. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3089. moveToEnd();
  3090. return;
  3091. }
  3092. DEBUG_WITH_TYPE("mach-o-rebase",
  3093. dbgs() << "REBASE_OPCODE_ADD_ADDR_ULEB: "
  3094. << format("SegmentOffset=0x%06X",
  3095. SegmentOffset) << "\n");
  3096. break;
  3097. case MachO::REBASE_OPCODE_ADD_ADDR_IMM_SCALED:
  3098. SegmentOffset += ImmValue * PointerSize;
  3099. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3100. PointerSize);
  3101. if (error) {
  3102. *E = malformedError("for REBASE_OPCODE_ADD_ADDR_IMM_SCALED " +
  3103. Twine(error) + " for opcode at: 0x" +
  3104. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3105. moveToEnd();
  3106. return;
  3107. }
  3108. DEBUG_WITH_TYPE("mach-o-rebase",
  3109. dbgs() << "REBASE_OPCODE_ADD_ADDR_IMM_SCALED: "
  3110. << format("SegmentOffset=0x%06X",
  3111. SegmentOffset) << "\n");
  3112. break;
  3113. case MachO::REBASE_OPCODE_DO_REBASE_IMM_TIMES:
  3114. AdvanceAmount = PointerSize;
  3115. Skip = 0;
  3116. Count = ImmValue;
  3117. if (ImmValue != 0)
  3118. RemainingLoopCount = ImmValue - 1;
  3119. else
  3120. RemainingLoopCount = 0;
  3121. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3122. PointerSize, Count, Skip);
  3123. if (error) {
  3124. *E = malformedError("for REBASE_OPCODE_DO_REBASE_IMM_TIMES " +
  3125. Twine(error) + " for opcode at: 0x" +
  3126. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3127. moveToEnd();
  3128. return;
  3129. }
  3130. DEBUG_WITH_TYPE(
  3131. "mach-o-rebase",
  3132. dbgs() << "REBASE_OPCODE_DO_REBASE_IMM_TIMES: "
  3133. << format("SegmentOffset=0x%06X", SegmentOffset)
  3134. << ", AdvanceAmount=" << AdvanceAmount
  3135. << ", RemainingLoopCount=" << RemainingLoopCount
  3136. << "\n");
  3137. return;
  3138. case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES:
  3139. AdvanceAmount = PointerSize;
  3140. Skip = 0;
  3141. Count = readULEB128(&error);
  3142. if (error) {
  3143. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
  3144. Twine(error) + " for opcode at: 0x" +
  3145. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3146. moveToEnd();
  3147. return;
  3148. }
  3149. if (Count != 0)
  3150. RemainingLoopCount = Count - 1;
  3151. else
  3152. RemainingLoopCount = 0;
  3153. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3154. PointerSize, Count, Skip);
  3155. if (error) {
  3156. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES " +
  3157. Twine(error) + " for opcode at: 0x" +
  3158. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3159. moveToEnd();
  3160. return;
  3161. }
  3162. DEBUG_WITH_TYPE(
  3163. "mach-o-rebase",
  3164. dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES: "
  3165. << format("SegmentOffset=0x%06X", SegmentOffset)
  3166. << ", AdvanceAmount=" << AdvanceAmount
  3167. << ", RemainingLoopCount=" << RemainingLoopCount
  3168. << "\n");
  3169. return;
  3170. case MachO::REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB:
  3171. Skip = readULEB128(&error);
  3172. if (error) {
  3173. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
  3174. Twine(error) + " for opcode at: 0x" +
  3175. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3176. moveToEnd();
  3177. return;
  3178. }
  3179. AdvanceAmount = Skip + PointerSize;
  3180. Count = 1;
  3181. RemainingLoopCount = 0;
  3182. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3183. PointerSize, Count, Skip);
  3184. if (error) {
  3185. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB " +
  3186. Twine(error) + " for opcode at: 0x" +
  3187. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3188. moveToEnd();
  3189. return;
  3190. }
  3191. DEBUG_WITH_TYPE(
  3192. "mach-o-rebase",
  3193. dbgs() << "REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB: "
  3194. << format("SegmentOffset=0x%06X", SegmentOffset)
  3195. << ", AdvanceAmount=" << AdvanceAmount
  3196. << ", RemainingLoopCount=" << RemainingLoopCount
  3197. << "\n");
  3198. return;
  3199. case MachO::REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB:
  3200. Count = readULEB128(&error);
  3201. if (error) {
  3202. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
  3203. "ULEB " +
  3204. Twine(error) + " for opcode at: 0x" +
  3205. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3206. moveToEnd();
  3207. return;
  3208. }
  3209. if (Count != 0)
  3210. RemainingLoopCount = Count - 1;
  3211. else
  3212. RemainingLoopCount = 0;
  3213. Skip = readULEB128(&error);
  3214. if (error) {
  3215. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
  3216. "ULEB " +
  3217. Twine(error) + " for opcode at: 0x" +
  3218. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3219. moveToEnd();
  3220. return;
  3221. }
  3222. AdvanceAmount = Skip + PointerSize;
  3223. error = O->RebaseEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3224. PointerSize, Count, Skip);
  3225. if (error) {
  3226. *E = malformedError("for REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_"
  3227. "ULEB " +
  3228. Twine(error) + " for opcode at: 0x" +
  3229. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3230. moveToEnd();
  3231. return;
  3232. }
  3233. DEBUG_WITH_TYPE(
  3234. "mach-o-rebase",
  3235. dbgs() << "REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB: "
  3236. << format("SegmentOffset=0x%06X", SegmentOffset)
  3237. << ", AdvanceAmount=" << AdvanceAmount
  3238. << ", RemainingLoopCount=" << RemainingLoopCount
  3239. << "\n");
  3240. return;
  3241. default:
  3242. *E = malformedError("bad rebase info (bad opcode value 0x" +
  3243. Twine::utohexstr(Opcode) + " for opcode at: 0x" +
  3244. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3245. moveToEnd();
  3246. return;
  3247. }
  3248. }
  3249. }
  3250. uint64_t MachORebaseEntry::readULEB128(const char **error) {
  3251. unsigned Count;
  3252. uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
  3253. Ptr += Count;
  3254. if (Ptr > Opcodes.end())
  3255. Ptr = Opcodes.end();
  3256. return Result;
  3257. }
  3258. int32_t MachORebaseEntry::segmentIndex() const { return SegmentIndex; }
  3259. uint64_t MachORebaseEntry::segmentOffset() const { return SegmentOffset; }
  3260. StringRef MachORebaseEntry::typeName() const {
  3261. switch (RebaseType) {
  3262. case MachO::REBASE_TYPE_POINTER:
  3263. return "pointer";
  3264. case MachO::REBASE_TYPE_TEXT_ABSOLUTE32:
  3265. return "text abs32";
  3266. case MachO::REBASE_TYPE_TEXT_PCREL32:
  3267. return "text rel32";
  3268. }
  3269. return "unknown";
  3270. }
  3271. // For use with the SegIndex of a checked Mach-O Rebase entry
  3272. // to get the segment name.
  3273. StringRef MachORebaseEntry::segmentName() const {
  3274. return O->BindRebaseSegmentName(SegmentIndex);
  3275. }
  3276. // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
  3277. // to get the section name.
  3278. StringRef MachORebaseEntry::sectionName() const {
  3279. return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
  3280. }
  3281. // For use with a SegIndex,SegOffset pair from a checked Mach-O Rebase entry
  3282. // to get the address.
  3283. uint64_t MachORebaseEntry::address() const {
  3284. return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
  3285. }
  3286. bool MachORebaseEntry::operator==(const MachORebaseEntry &Other) const {
  3287. #ifdef EXPENSIVE_CHECKS
  3288. assert(Opcodes == Other.Opcodes && "compare iterators of different files");
  3289. #else
  3290. assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
  3291. #endif
  3292. return (Ptr == Other.Ptr) &&
  3293. (RemainingLoopCount == Other.RemainingLoopCount) &&
  3294. (Done == Other.Done);
  3295. }
  3296. iterator_range<rebase_iterator>
  3297. MachOObjectFile::rebaseTable(Error &Err, MachOObjectFile *O,
  3298. ArrayRef<uint8_t> Opcodes, bool is64) {
  3299. if (O->BindRebaseSectionTable == nullptr)
  3300. O->BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(O);
  3301. MachORebaseEntry Start(&Err, O, Opcodes, is64);
  3302. Start.moveToFirst();
  3303. MachORebaseEntry Finish(&Err, O, Opcodes, is64);
  3304. Finish.moveToEnd();
  3305. return make_range(rebase_iterator(Start), rebase_iterator(Finish));
  3306. }
  3307. iterator_range<rebase_iterator> MachOObjectFile::rebaseTable(Error &Err) {
  3308. return rebaseTable(Err, this, getDyldInfoRebaseOpcodes(), is64Bit());
  3309. }
  3310. MachOBindEntry::MachOBindEntry(Error *E, const MachOObjectFile *O,
  3311. ArrayRef<uint8_t> Bytes, bool is64Bit, Kind BK)
  3312. : E(E), O(O), Opcodes(Bytes), Ptr(Bytes.begin()),
  3313. PointerSize(is64Bit ? 8 : 4), TableKind(BK) {}
  3314. void MachOBindEntry::moveToFirst() {
  3315. Ptr = Opcodes.begin();
  3316. moveNext();
  3317. }
  3318. void MachOBindEntry::moveToEnd() {
  3319. Ptr = Opcodes.end();
  3320. RemainingLoopCount = 0;
  3321. Done = true;
  3322. }
  3323. void MachOBindEntry::moveNext() {
  3324. ErrorAsOutParameter ErrAsOutParam(E);
  3325. // If in the middle of some loop, move to next binding in loop.
  3326. SegmentOffset += AdvanceAmount;
  3327. if (RemainingLoopCount) {
  3328. --RemainingLoopCount;
  3329. return;
  3330. }
  3331. // BIND_OPCODE_DONE is only used for padding if we are not aligned to
  3332. // pointer size. Therefore it is possible to reach the end without ever having
  3333. // seen BIND_OPCODE_DONE.
  3334. if (Ptr == Opcodes.end()) {
  3335. Done = true;
  3336. return;
  3337. }
  3338. bool More = true;
  3339. while (More) {
  3340. // Parse next opcode and set up next loop.
  3341. const uint8_t *OpcodeStart = Ptr;
  3342. uint8_t Byte = *Ptr++;
  3343. uint8_t ImmValue = Byte & MachO::BIND_IMMEDIATE_MASK;
  3344. uint8_t Opcode = Byte & MachO::BIND_OPCODE_MASK;
  3345. int8_t SignExtended;
  3346. const uint8_t *SymStart;
  3347. uint32_t Count, Skip;
  3348. const char *error = nullptr;
  3349. switch (Opcode) {
  3350. case MachO::BIND_OPCODE_DONE:
  3351. if (TableKind == Kind::Lazy) {
  3352. // Lazying bindings have a DONE opcode between entries. Need to ignore
  3353. // it to advance to next entry. But need not if this is last entry.
  3354. bool NotLastEntry = false;
  3355. for (const uint8_t *P = Ptr; P < Opcodes.end(); ++P) {
  3356. if (*P) {
  3357. NotLastEntry = true;
  3358. }
  3359. }
  3360. if (NotLastEntry)
  3361. break;
  3362. }
  3363. More = false;
  3364. moveToEnd();
  3365. DEBUG_WITH_TYPE("mach-o-bind", dbgs() << "BIND_OPCODE_DONE\n");
  3366. break;
  3367. case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:
  3368. if (TableKind == Kind::Weak) {
  3369. *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_IMM not allowed in "
  3370. "weak bind table for opcode at: 0x" +
  3371. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3372. moveToEnd();
  3373. return;
  3374. }
  3375. Ordinal = ImmValue;
  3376. LibraryOrdinalSet = true;
  3377. if (ImmValue > O->getLibraryCount()) {
  3378. *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
  3379. "library ordinal: " +
  3380. Twine((int)ImmValue) + " (max " +
  3381. Twine((int)O->getLibraryCount()) +
  3382. ") for opcode at: 0x" +
  3383. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3384. moveToEnd();
  3385. return;
  3386. }
  3387. DEBUG_WITH_TYPE(
  3388. "mach-o-bind",
  3389. dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: "
  3390. << "Ordinal=" << Ordinal << "\n");
  3391. break;
  3392. case MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:
  3393. if (TableKind == Kind::Weak) {
  3394. *E = malformedError("BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB not allowed in "
  3395. "weak bind table for opcode at: 0x" +
  3396. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3397. moveToEnd();
  3398. return;
  3399. }
  3400. Ordinal = readULEB128(&error);
  3401. LibraryOrdinalSet = true;
  3402. if (error) {
  3403. *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB " +
  3404. Twine(error) + " for opcode at: 0x" +
  3405. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3406. moveToEnd();
  3407. return;
  3408. }
  3409. if (Ordinal > (int)O->getLibraryCount()) {
  3410. *E = malformedError("for BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB bad "
  3411. "library ordinal: " +
  3412. Twine((int)Ordinal) + " (max " +
  3413. Twine((int)O->getLibraryCount()) +
  3414. ") for opcode at: 0x" +
  3415. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3416. moveToEnd();
  3417. return;
  3418. }
  3419. DEBUG_WITH_TYPE(
  3420. "mach-o-bind",
  3421. dbgs() << "BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: "
  3422. << "Ordinal=" << Ordinal << "\n");
  3423. break;
  3424. case MachO::BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:
  3425. if (TableKind == Kind::Weak) {
  3426. *E = malformedError("BIND_OPCODE_SET_DYLIB_SPECIAL_IMM not allowed in "
  3427. "weak bind table for opcode at: 0x" +
  3428. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3429. moveToEnd();
  3430. return;
  3431. }
  3432. if (ImmValue) {
  3433. SignExtended = MachO::BIND_OPCODE_MASK | ImmValue;
  3434. Ordinal = SignExtended;
  3435. if (Ordinal < MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP) {
  3436. *E = malformedError("for BIND_OPCODE_SET_DYLIB_SPECIAL_IMM unknown "
  3437. "special ordinal: " +
  3438. Twine((int)Ordinal) + " for opcode at: 0x" +
  3439. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3440. moveToEnd();
  3441. return;
  3442. }
  3443. } else
  3444. Ordinal = 0;
  3445. LibraryOrdinalSet = true;
  3446. DEBUG_WITH_TYPE(
  3447. "mach-o-bind",
  3448. dbgs() << "BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: "
  3449. << "Ordinal=" << Ordinal << "\n");
  3450. break;
  3451. case MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:
  3452. Flags = ImmValue;
  3453. SymStart = Ptr;
  3454. while (*Ptr && (Ptr < Opcodes.end())) {
  3455. ++Ptr;
  3456. }
  3457. if (Ptr == Opcodes.end()) {
  3458. *E = malformedError(
  3459. "for BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM "
  3460. "symbol name extends past opcodes for opcode at: 0x" +
  3461. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3462. moveToEnd();
  3463. return;
  3464. }
  3465. SymbolName = StringRef(reinterpret_cast<const char*>(SymStart),
  3466. Ptr-SymStart);
  3467. ++Ptr;
  3468. DEBUG_WITH_TYPE(
  3469. "mach-o-bind",
  3470. dbgs() << "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: "
  3471. << "SymbolName=" << SymbolName << "\n");
  3472. if (TableKind == Kind::Weak) {
  3473. if (ImmValue & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION)
  3474. return;
  3475. }
  3476. break;
  3477. case MachO::BIND_OPCODE_SET_TYPE_IMM:
  3478. BindType = ImmValue;
  3479. if (ImmValue > MachO::BIND_TYPE_TEXT_PCREL32) {
  3480. *E = malformedError("for BIND_OPCODE_SET_TYPE_IMM bad bind type: " +
  3481. Twine((int)ImmValue) + " for opcode at: 0x" +
  3482. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3483. moveToEnd();
  3484. return;
  3485. }
  3486. DEBUG_WITH_TYPE(
  3487. "mach-o-bind",
  3488. dbgs() << "BIND_OPCODE_SET_TYPE_IMM: "
  3489. << "BindType=" << (int)BindType << "\n");
  3490. break;
  3491. case MachO::BIND_OPCODE_SET_ADDEND_SLEB:
  3492. Addend = readSLEB128(&error);
  3493. if (error) {
  3494. *E = malformedError("for BIND_OPCODE_SET_ADDEND_SLEB " + Twine(error) +
  3495. " for opcode at: 0x" +
  3496. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3497. moveToEnd();
  3498. return;
  3499. }
  3500. DEBUG_WITH_TYPE(
  3501. "mach-o-bind",
  3502. dbgs() << "BIND_OPCODE_SET_ADDEND_SLEB: "
  3503. << "Addend=" << Addend << "\n");
  3504. break;
  3505. case MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:
  3506. SegmentIndex = ImmValue;
  3507. SegmentOffset = readULEB128(&error);
  3508. if (error) {
  3509. *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
  3510. Twine(error) + " for opcode at: 0x" +
  3511. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3512. moveToEnd();
  3513. return;
  3514. }
  3515. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3516. PointerSize);
  3517. if (error) {
  3518. *E = malformedError("for BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB " +
  3519. Twine(error) + " for opcode at: 0x" +
  3520. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3521. moveToEnd();
  3522. return;
  3523. }
  3524. DEBUG_WITH_TYPE(
  3525. "mach-o-bind",
  3526. dbgs() << "BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: "
  3527. << "SegmentIndex=" << SegmentIndex << ", "
  3528. << format("SegmentOffset=0x%06X", SegmentOffset)
  3529. << "\n");
  3530. break;
  3531. case MachO::BIND_OPCODE_ADD_ADDR_ULEB:
  3532. SegmentOffset += readULEB128(&error);
  3533. if (error) {
  3534. *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
  3535. " for opcode at: 0x" +
  3536. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3537. moveToEnd();
  3538. return;
  3539. }
  3540. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3541. PointerSize);
  3542. if (error) {
  3543. *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB " + Twine(error) +
  3544. " for opcode at: 0x" +
  3545. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3546. moveToEnd();
  3547. return;
  3548. }
  3549. DEBUG_WITH_TYPE("mach-o-bind",
  3550. dbgs() << "BIND_OPCODE_ADD_ADDR_ULEB: "
  3551. << format("SegmentOffset=0x%06X",
  3552. SegmentOffset) << "\n");
  3553. break;
  3554. case MachO::BIND_OPCODE_DO_BIND:
  3555. AdvanceAmount = PointerSize;
  3556. RemainingLoopCount = 0;
  3557. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3558. PointerSize);
  3559. if (error) {
  3560. *E = malformedError("for BIND_OPCODE_DO_BIND " + Twine(error) +
  3561. " for opcode at: 0x" +
  3562. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3563. moveToEnd();
  3564. return;
  3565. }
  3566. if (SymbolName == StringRef()) {
  3567. *E = malformedError(
  3568. "for BIND_OPCODE_DO_BIND missing preceding "
  3569. "BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode at: 0x" +
  3570. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3571. moveToEnd();
  3572. return;
  3573. }
  3574. if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
  3575. *E =
  3576. malformedError("for BIND_OPCODE_DO_BIND missing preceding "
  3577. "BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
  3578. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3579. moveToEnd();
  3580. return;
  3581. }
  3582. DEBUG_WITH_TYPE("mach-o-bind",
  3583. dbgs() << "BIND_OPCODE_DO_BIND: "
  3584. << format("SegmentOffset=0x%06X",
  3585. SegmentOffset) << "\n");
  3586. return;
  3587. case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:
  3588. if (TableKind == Kind::Lazy) {
  3589. *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB not allowed in "
  3590. "lazy bind table for opcode at: 0x" +
  3591. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3592. moveToEnd();
  3593. return;
  3594. }
  3595. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3596. PointerSize);
  3597. if (error) {
  3598. *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
  3599. Twine(error) + " for opcode at: 0x" +
  3600. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3601. moveToEnd();
  3602. return;
  3603. }
  3604. if (SymbolName == StringRef()) {
  3605. *E = malformedError(
  3606. "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
  3607. "preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for opcode "
  3608. "at: 0x" +
  3609. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3610. moveToEnd();
  3611. return;
  3612. }
  3613. if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
  3614. *E = malformedError(
  3615. "for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB missing "
  3616. "preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode at: 0x" +
  3617. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3618. moveToEnd();
  3619. return;
  3620. }
  3621. AdvanceAmount = readULEB128(&error) + PointerSize;
  3622. if (error) {
  3623. *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB " +
  3624. Twine(error) + " for opcode at: 0x" +
  3625. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3626. moveToEnd();
  3627. return;
  3628. }
  3629. // Note, this is not really an error until the next bind but make no sense
  3630. // for a BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB to not be followed by another
  3631. // bind operation.
  3632. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
  3633. AdvanceAmount, PointerSize);
  3634. if (error) {
  3635. *E = malformedError("for BIND_OPCODE_ADD_ADDR_ULEB (after adding "
  3636. "ULEB) " +
  3637. Twine(error) + " for opcode at: 0x" +
  3638. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3639. moveToEnd();
  3640. return;
  3641. }
  3642. RemainingLoopCount = 0;
  3643. DEBUG_WITH_TYPE(
  3644. "mach-o-bind",
  3645. dbgs() << "BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: "
  3646. << format("SegmentOffset=0x%06X", SegmentOffset)
  3647. << ", AdvanceAmount=" << AdvanceAmount
  3648. << ", RemainingLoopCount=" << RemainingLoopCount
  3649. << "\n");
  3650. return;
  3651. case MachO::BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:
  3652. if (TableKind == Kind::Lazy) {
  3653. *E = malformedError("BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED not "
  3654. "allowed in lazy bind table for opcode at: 0x" +
  3655. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3656. moveToEnd();
  3657. return;
  3658. }
  3659. if (SymbolName == StringRef()) {
  3660. *E = malformedError(
  3661. "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
  3662. "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
  3663. "opcode at: 0x" +
  3664. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3665. moveToEnd();
  3666. return;
  3667. }
  3668. if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
  3669. *E = malformedError(
  3670. "for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED "
  3671. "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
  3672. "at: 0x" +
  3673. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3674. moveToEnd();
  3675. return;
  3676. }
  3677. AdvanceAmount = ImmValue * PointerSize + PointerSize;
  3678. RemainingLoopCount = 0;
  3679. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset +
  3680. AdvanceAmount, PointerSize);
  3681. if (error) {
  3682. *E = malformedError("for BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED " +
  3683. Twine(error) + " for opcode at: 0x" +
  3684. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3685. moveToEnd();
  3686. return;
  3687. }
  3688. DEBUG_WITH_TYPE("mach-o-bind",
  3689. dbgs()
  3690. << "BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: "
  3691. << format("SegmentOffset=0x%06X", SegmentOffset) << "\n");
  3692. return;
  3693. case MachO::BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:
  3694. if (TableKind == Kind::Lazy) {
  3695. *E = malformedError("BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB not "
  3696. "allowed in lazy bind table for opcode at: 0x" +
  3697. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3698. moveToEnd();
  3699. return;
  3700. }
  3701. Count = readULEB128(&error);
  3702. if (Count != 0)
  3703. RemainingLoopCount = Count - 1;
  3704. else
  3705. RemainingLoopCount = 0;
  3706. if (error) {
  3707. *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
  3708. " (count value) " +
  3709. Twine(error) + " for opcode at: 0x" +
  3710. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3711. moveToEnd();
  3712. return;
  3713. }
  3714. Skip = readULEB128(&error);
  3715. AdvanceAmount = Skip + PointerSize;
  3716. if (error) {
  3717. *E = malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
  3718. " (skip value) " +
  3719. Twine(error) + " for opcode at: 0x" +
  3720. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3721. moveToEnd();
  3722. return;
  3723. }
  3724. if (SymbolName == StringRef()) {
  3725. *E = malformedError(
  3726. "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
  3727. "missing preceding BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM for "
  3728. "opcode at: 0x" +
  3729. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3730. moveToEnd();
  3731. return;
  3732. }
  3733. if (!LibraryOrdinalSet && TableKind != Kind::Weak) {
  3734. *E = malformedError(
  3735. "for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB "
  3736. "missing preceding BIND_OPCODE_SET_DYLIB_ORDINAL_* for opcode "
  3737. "at: 0x" +
  3738. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3739. moveToEnd();
  3740. return;
  3741. }
  3742. error = O->BindEntryCheckSegAndOffsets(SegmentIndex, SegmentOffset,
  3743. PointerSize, Count, Skip);
  3744. if (error) {
  3745. *E =
  3746. malformedError("for BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB " +
  3747. Twine(error) + " for opcode at: 0x" +
  3748. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3749. moveToEnd();
  3750. return;
  3751. }
  3752. DEBUG_WITH_TYPE(
  3753. "mach-o-bind",
  3754. dbgs() << "BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: "
  3755. << format("SegmentOffset=0x%06X", SegmentOffset)
  3756. << ", AdvanceAmount=" << AdvanceAmount
  3757. << ", RemainingLoopCount=" << RemainingLoopCount
  3758. << "\n");
  3759. return;
  3760. default:
  3761. *E = malformedError("bad bind info (bad opcode value 0x" +
  3762. Twine::utohexstr(Opcode) + " for opcode at: 0x" +
  3763. Twine::utohexstr(OpcodeStart - Opcodes.begin()));
  3764. moveToEnd();
  3765. return;
  3766. }
  3767. }
  3768. }
  3769. uint64_t MachOBindEntry::readULEB128(const char **error) {
  3770. unsigned Count;
  3771. uint64_t Result = decodeULEB128(Ptr, &Count, Opcodes.end(), error);
  3772. Ptr += Count;
  3773. if (Ptr > Opcodes.end())
  3774. Ptr = Opcodes.end();
  3775. return Result;
  3776. }
  3777. int64_t MachOBindEntry::readSLEB128(const char **error) {
  3778. unsigned Count;
  3779. int64_t Result = decodeSLEB128(Ptr, &Count, Opcodes.end(), error);
  3780. Ptr += Count;
  3781. if (Ptr > Opcodes.end())
  3782. Ptr = Opcodes.end();
  3783. return Result;
  3784. }
  3785. int32_t MachOBindEntry::segmentIndex() const { return SegmentIndex; }
  3786. uint64_t MachOBindEntry::segmentOffset() const { return SegmentOffset; }
  3787. StringRef MachOBindEntry::typeName() const {
  3788. switch (BindType) {
  3789. case MachO::BIND_TYPE_POINTER:
  3790. return "pointer";
  3791. case MachO::BIND_TYPE_TEXT_ABSOLUTE32:
  3792. return "text abs32";
  3793. case MachO::BIND_TYPE_TEXT_PCREL32:
  3794. return "text rel32";
  3795. }
  3796. return "unknown";
  3797. }
  3798. StringRef MachOBindEntry::symbolName() const { return SymbolName; }
  3799. int64_t MachOBindEntry::addend() const { return Addend; }
  3800. uint32_t MachOBindEntry::flags() const { return Flags; }
  3801. int MachOBindEntry::ordinal() const { return Ordinal; }
  3802. // For use with the SegIndex of a checked Mach-O Bind entry
  3803. // to get the segment name.
  3804. StringRef MachOBindEntry::segmentName() const {
  3805. return O->BindRebaseSegmentName(SegmentIndex);
  3806. }
  3807. // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
  3808. // to get the section name.
  3809. StringRef MachOBindEntry::sectionName() const {
  3810. return O->BindRebaseSectionName(SegmentIndex, SegmentOffset);
  3811. }
  3812. // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind entry
  3813. // to get the address.
  3814. uint64_t MachOBindEntry::address() const {
  3815. return O->BindRebaseAddress(SegmentIndex, SegmentOffset);
  3816. }
  3817. bool MachOBindEntry::operator==(const MachOBindEntry &Other) const {
  3818. #ifdef EXPENSIVE_CHECKS
  3819. assert(Opcodes == Other.Opcodes && "compare iterators of different files");
  3820. #else
  3821. assert(Opcodes.data() == Other.Opcodes.data() && "compare iterators of different files");
  3822. #endif
  3823. return (Ptr == Other.Ptr) &&
  3824. (RemainingLoopCount == Other.RemainingLoopCount) &&
  3825. (Done == Other.Done);
  3826. }
  3827. // Build table of sections so SegIndex/SegOffset pairs can be translated.
  3828. BindRebaseSegInfo::BindRebaseSegInfo(const object::MachOObjectFile *Obj) {
  3829. uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
  3830. StringRef CurSegName;
  3831. uint64_t CurSegAddress;
  3832. for (const SectionRef &Section : Obj->sections()) {
  3833. SectionInfo Info;
  3834. Expected<StringRef> NameOrErr = Section.getName();
  3835. if (!NameOrErr)
  3836. consumeError(NameOrErr.takeError());
  3837. else
  3838. Info.SectionName = *NameOrErr;
  3839. Info.Address = Section.getAddress();
  3840. Info.Size = Section.getSize();
  3841. Info.SegmentName =
  3842. Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
  3843. if (!Info.SegmentName.equals(CurSegName)) {
  3844. ++CurSegIndex;
  3845. CurSegName = Info.SegmentName;
  3846. CurSegAddress = Info.Address;
  3847. }
  3848. Info.SegmentIndex = CurSegIndex - 1;
  3849. Info.OffsetInSegment = Info.Address - CurSegAddress;
  3850. Info.SegmentStartAddress = CurSegAddress;
  3851. Sections.push_back(Info);
  3852. }
  3853. MaxSegIndex = CurSegIndex;
  3854. }
  3855. // For use with a SegIndex, SegOffset, and PointerSize triple in
  3856. // MachOBindEntry::moveNext() to validate a MachOBindEntry or MachORebaseEntry.
  3857. //
  3858. // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists
  3859. // that fully contains a pointer at that location. Multiple fixups in a bind
  3860. // (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can
  3861. // be tested via the Count and Skip parameters.
  3862. const char * BindRebaseSegInfo::checkSegAndOffsets(int32_t SegIndex,
  3863. uint64_t SegOffset,
  3864. uint8_t PointerSize,
  3865. uint32_t Count,
  3866. uint32_t Skip) {
  3867. if (SegIndex == -1)
  3868. return "missing preceding *_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB";
  3869. if (SegIndex >= MaxSegIndex)
  3870. return "bad segIndex (too large)";
  3871. for (uint32_t i = 0; i < Count; ++i) {
  3872. uint32_t Start = SegOffset + i * (PointerSize + Skip);
  3873. uint32_t End = Start + PointerSize;
  3874. bool Found = false;
  3875. for (const SectionInfo &SI : Sections) {
  3876. if (SI.SegmentIndex != SegIndex)
  3877. continue;
  3878. if ((SI.OffsetInSegment<=Start) && (Start<(SI.OffsetInSegment+SI.Size))) {
  3879. if (End <= SI.OffsetInSegment + SI.Size) {
  3880. Found = true;
  3881. break;
  3882. }
  3883. else
  3884. return "bad offset, extends beyond section boundary";
  3885. }
  3886. }
  3887. if (!Found)
  3888. return "bad offset, not in section";
  3889. }
  3890. return nullptr;
  3891. }
  3892. // For use with the SegIndex of a checked Mach-O Bind or Rebase entry
  3893. // to get the segment name.
  3894. StringRef BindRebaseSegInfo::segmentName(int32_t SegIndex) {
  3895. for (const SectionInfo &SI : Sections) {
  3896. if (SI.SegmentIndex == SegIndex)
  3897. return SI.SegmentName;
  3898. }
  3899. llvm_unreachable("invalid SegIndex");
  3900. }
  3901. // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
  3902. // to get the SectionInfo.
  3903. const BindRebaseSegInfo::SectionInfo &BindRebaseSegInfo::findSection(
  3904. int32_t SegIndex, uint64_t SegOffset) {
  3905. for (const SectionInfo &SI : Sections) {
  3906. if (SI.SegmentIndex != SegIndex)
  3907. continue;
  3908. if (SI.OffsetInSegment > SegOffset)
  3909. continue;
  3910. if (SegOffset >= (SI.OffsetInSegment + SI.Size))
  3911. continue;
  3912. return SI;
  3913. }
  3914. llvm_unreachable("SegIndex and SegOffset not in any section");
  3915. }
  3916. // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
  3917. // entry to get the section name.
  3918. StringRef BindRebaseSegInfo::sectionName(int32_t SegIndex,
  3919. uint64_t SegOffset) {
  3920. return findSection(SegIndex, SegOffset).SectionName;
  3921. }
  3922. // For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or Rebase
  3923. // entry to get the address.
  3924. uint64_t BindRebaseSegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
  3925. const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
  3926. return SI.SegmentStartAddress + OffsetInSeg;
  3927. }
  3928. iterator_range<bind_iterator>
  3929. MachOObjectFile::bindTable(Error &Err, MachOObjectFile *O,
  3930. ArrayRef<uint8_t> Opcodes, bool is64,
  3931. MachOBindEntry::Kind BKind) {
  3932. if (O->BindRebaseSectionTable == nullptr)
  3933. O->BindRebaseSectionTable = std::make_unique<BindRebaseSegInfo>(O);
  3934. MachOBindEntry Start(&Err, O, Opcodes, is64, BKind);
  3935. Start.moveToFirst();
  3936. MachOBindEntry Finish(&Err, O, Opcodes, is64, BKind);
  3937. Finish.moveToEnd();
  3938. return make_range(bind_iterator(Start), bind_iterator(Finish));
  3939. }
  3940. iterator_range<bind_iterator> MachOObjectFile::bindTable(Error &Err) {
  3941. return bindTable(Err, this, getDyldInfoBindOpcodes(), is64Bit(),
  3942. MachOBindEntry::Kind::Regular);
  3943. }
  3944. iterator_range<bind_iterator> MachOObjectFile::lazyBindTable(Error &Err) {
  3945. return bindTable(Err, this, getDyldInfoLazyBindOpcodes(), is64Bit(),
  3946. MachOBindEntry::Kind::Lazy);
  3947. }
  3948. iterator_range<bind_iterator> MachOObjectFile::weakBindTable(Error &Err) {
  3949. return bindTable(Err, this, getDyldInfoWeakBindOpcodes(), is64Bit(),
  3950. MachOBindEntry::Kind::Weak);
  3951. }
  3952. MachOObjectFile::load_command_iterator
  3953. MachOObjectFile::begin_load_commands() const {
  3954. return LoadCommands.begin();
  3955. }
  3956. MachOObjectFile::load_command_iterator
  3957. MachOObjectFile::end_load_commands() const {
  3958. return LoadCommands.end();
  3959. }
  3960. iterator_range<MachOObjectFile::load_command_iterator>
  3961. MachOObjectFile::load_commands() const {
  3962. return make_range(begin_load_commands(), end_load_commands());
  3963. }
  3964. StringRef
  3965. MachOObjectFile::getSectionFinalSegmentName(DataRefImpl Sec) const {
  3966. ArrayRef<char> Raw = getSectionRawFinalSegmentName(Sec);
  3967. return parseSegmentOrSectionName(Raw.data());
  3968. }
  3969. ArrayRef<char>
  3970. MachOObjectFile::getSectionRawName(DataRefImpl Sec) const {
  3971. assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
  3972. const section_base *Base =
  3973. reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
  3974. return makeArrayRef(Base->sectname);
  3975. }
  3976. ArrayRef<char>
  3977. MachOObjectFile::getSectionRawFinalSegmentName(DataRefImpl Sec) const {
  3978. assert(Sec.d.a < Sections.size() && "Should have detected this earlier");
  3979. const section_base *Base =
  3980. reinterpret_cast<const section_base *>(Sections[Sec.d.a]);
  3981. return makeArrayRef(Base->segname);
  3982. }
  3983. bool
  3984. MachOObjectFile::isRelocationScattered(const MachO::any_relocation_info &RE)
  3985. const {
  3986. if (getCPUType(*this) == MachO::CPU_TYPE_X86_64)
  3987. return false;
  3988. return getPlainRelocationAddress(RE) & MachO::R_SCATTERED;
  3989. }
  3990. unsigned MachOObjectFile::getPlainRelocationSymbolNum(
  3991. const MachO::any_relocation_info &RE) const {
  3992. if (isLittleEndian())
  3993. return RE.r_word1 & 0xffffff;
  3994. return RE.r_word1 >> 8;
  3995. }
  3996. bool MachOObjectFile::getPlainRelocationExternal(
  3997. const MachO::any_relocation_info &RE) const {
  3998. if (isLittleEndian())
  3999. return (RE.r_word1 >> 27) & 1;
  4000. return (RE.r_word1 >> 4) & 1;
  4001. }
  4002. bool MachOObjectFile::getScatteredRelocationScattered(
  4003. const MachO::any_relocation_info &RE) const {
  4004. return RE.r_word0 >> 31;
  4005. }
  4006. uint32_t MachOObjectFile::getScatteredRelocationValue(
  4007. const MachO::any_relocation_info &RE) const {
  4008. return RE.r_word1;
  4009. }
  4010. uint32_t MachOObjectFile::getScatteredRelocationType(
  4011. const MachO::any_relocation_info &RE) const {
  4012. return (RE.r_word0 >> 24) & 0xf;
  4013. }
  4014. unsigned MachOObjectFile::getAnyRelocationAddress(
  4015. const MachO::any_relocation_info &RE) const {
  4016. if (isRelocationScattered(RE))
  4017. return getScatteredRelocationAddress(RE);
  4018. return getPlainRelocationAddress(RE);
  4019. }
  4020. unsigned MachOObjectFile::getAnyRelocationPCRel(
  4021. const MachO::any_relocation_info &RE) const {
  4022. if (isRelocationScattered(RE))
  4023. return getScatteredRelocationPCRel(RE);
  4024. return getPlainRelocationPCRel(*this, RE);
  4025. }
  4026. unsigned MachOObjectFile::getAnyRelocationLength(
  4027. const MachO::any_relocation_info &RE) const {
  4028. if (isRelocationScattered(RE))
  4029. return getScatteredRelocationLength(RE);
  4030. return getPlainRelocationLength(*this, RE);
  4031. }
  4032. unsigned
  4033. MachOObjectFile::getAnyRelocationType(
  4034. const MachO::any_relocation_info &RE) const {
  4035. if (isRelocationScattered(RE))
  4036. return getScatteredRelocationType(RE);
  4037. return getPlainRelocationType(*this, RE);
  4038. }
  4039. SectionRef
  4040. MachOObjectFile::getAnyRelocationSection(
  4041. const MachO::any_relocation_info &RE) const {
  4042. if (isRelocationScattered(RE) || getPlainRelocationExternal(RE))
  4043. return *section_end();
  4044. unsigned SecNum = getPlainRelocationSymbolNum(RE);
  4045. if (SecNum == MachO::R_ABS || SecNum > Sections.size())
  4046. return *section_end();
  4047. DataRefImpl DRI;
  4048. DRI.d.a = SecNum - 1;
  4049. return SectionRef(DRI, this);
  4050. }
  4051. MachO::section MachOObjectFile::getSection(DataRefImpl DRI) const {
  4052. assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
  4053. return getStruct<MachO::section>(*this, Sections[DRI.d.a]);
  4054. }
  4055. MachO::section_64 MachOObjectFile::getSection64(DataRefImpl DRI) const {
  4056. assert(DRI.d.a < Sections.size() && "Should have detected this earlier");
  4057. return getStruct<MachO::section_64>(*this, Sections[DRI.d.a]);
  4058. }
  4059. MachO::section MachOObjectFile::getSection(const LoadCommandInfo &L,
  4060. unsigned Index) const {
  4061. const char *Sec = getSectionPtr(*this, L, Index);
  4062. return getStruct<MachO::section>(*this, Sec);
  4063. }
  4064. MachO::section_64 MachOObjectFile::getSection64(const LoadCommandInfo &L,
  4065. unsigned Index) const {
  4066. const char *Sec = getSectionPtr(*this, L, Index);
  4067. return getStruct<MachO::section_64>(*this, Sec);
  4068. }
  4069. MachO::nlist
  4070. MachOObjectFile::getSymbolTableEntry(DataRefImpl DRI) const {
  4071. const char *P = reinterpret_cast<const char *>(DRI.p);
  4072. return getStruct<MachO::nlist>(*this, P);
  4073. }
  4074. MachO::nlist_64
  4075. MachOObjectFile::getSymbol64TableEntry(DataRefImpl DRI) const {
  4076. const char *P = reinterpret_cast<const char *>(DRI.p);
  4077. return getStruct<MachO::nlist_64>(*this, P);
  4078. }
  4079. MachO::linkedit_data_command
  4080. MachOObjectFile::getLinkeditDataLoadCommand(const LoadCommandInfo &L) const {
  4081. return getStruct<MachO::linkedit_data_command>(*this, L.Ptr);
  4082. }
  4083. MachO::segment_command
  4084. MachOObjectFile::getSegmentLoadCommand(const LoadCommandInfo &L) const {
  4085. return getStruct<MachO::segment_command>(*this, L.Ptr);
  4086. }
  4087. MachO::segment_command_64
  4088. MachOObjectFile::getSegment64LoadCommand(const LoadCommandInfo &L) const {
  4089. return getStruct<MachO::segment_command_64>(*this, L.Ptr);
  4090. }
  4091. MachO::linker_option_command
  4092. MachOObjectFile::getLinkerOptionLoadCommand(const LoadCommandInfo &L) const {
  4093. return getStruct<MachO::linker_option_command>(*this, L.Ptr);
  4094. }
  4095. MachO::version_min_command
  4096. MachOObjectFile::getVersionMinLoadCommand(const LoadCommandInfo &L) const {
  4097. return getStruct<MachO::version_min_command>(*this, L.Ptr);
  4098. }
  4099. MachO::note_command
  4100. MachOObjectFile::getNoteLoadCommand(const LoadCommandInfo &L) const {
  4101. return getStruct<MachO::note_command>(*this, L.Ptr);
  4102. }
  4103. MachO::build_version_command
  4104. MachOObjectFile::getBuildVersionLoadCommand(const LoadCommandInfo &L) const {
  4105. return getStruct<MachO::build_version_command>(*this, L.Ptr);
  4106. }
  4107. MachO::build_tool_version
  4108. MachOObjectFile::getBuildToolVersion(unsigned index) const {
  4109. return getStruct<MachO::build_tool_version>(*this, BuildTools[index]);
  4110. }
  4111. MachO::dylib_command
  4112. MachOObjectFile::getDylibIDLoadCommand(const LoadCommandInfo &L) const {
  4113. return getStruct<MachO::dylib_command>(*this, L.Ptr);
  4114. }
  4115. MachO::dyld_info_command
  4116. MachOObjectFile::getDyldInfoLoadCommand(const LoadCommandInfo &L) const {
  4117. return getStruct<MachO::dyld_info_command>(*this, L.Ptr);
  4118. }
  4119. MachO::dylinker_command
  4120. MachOObjectFile::getDylinkerCommand(const LoadCommandInfo &L) const {
  4121. return getStruct<MachO::dylinker_command>(*this, L.Ptr);
  4122. }
  4123. MachO::uuid_command
  4124. MachOObjectFile::getUuidCommand(const LoadCommandInfo &L) const {
  4125. return getStruct<MachO::uuid_command>(*this, L.Ptr);
  4126. }
  4127. MachO::rpath_command
  4128. MachOObjectFile::getRpathCommand(const LoadCommandInfo &L) const {
  4129. return getStruct<MachO::rpath_command>(*this, L.Ptr);
  4130. }
  4131. MachO::source_version_command
  4132. MachOObjectFile::getSourceVersionCommand(const LoadCommandInfo &L) const {
  4133. return getStruct<MachO::source_version_command>(*this, L.Ptr);
  4134. }
  4135. MachO::entry_point_command
  4136. MachOObjectFile::getEntryPointCommand(const LoadCommandInfo &L) const {
  4137. return getStruct<MachO::entry_point_command>(*this, L.Ptr);
  4138. }
  4139. MachO::encryption_info_command
  4140. MachOObjectFile::getEncryptionInfoCommand(const LoadCommandInfo &L) const {
  4141. return getStruct<MachO::encryption_info_command>(*this, L.Ptr);
  4142. }
  4143. MachO::encryption_info_command_64
  4144. MachOObjectFile::getEncryptionInfoCommand64(const LoadCommandInfo &L) const {
  4145. return getStruct<MachO::encryption_info_command_64>(*this, L.Ptr);
  4146. }
  4147. MachO::sub_framework_command
  4148. MachOObjectFile::getSubFrameworkCommand(const LoadCommandInfo &L) const {
  4149. return getStruct<MachO::sub_framework_command>(*this, L.Ptr);
  4150. }
  4151. MachO::sub_umbrella_command
  4152. MachOObjectFile::getSubUmbrellaCommand(const LoadCommandInfo &L) const {
  4153. return getStruct<MachO::sub_umbrella_command>(*this, L.Ptr);
  4154. }
  4155. MachO::sub_library_command
  4156. MachOObjectFile::getSubLibraryCommand(const LoadCommandInfo &L) const {
  4157. return getStruct<MachO::sub_library_command>(*this, L.Ptr);
  4158. }
  4159. MachO::sub_client_command
  4160. MachOObjectFile::getSubClientCommand(const LoadCommandInfo &L) const {
  4161. return getStruct<MachO::sub_client_command>(*this, L.Ptr);
  4162. }
  4163. MachO::routines_command
  4164. MachOObjectFile::getRoutinesCommand(const LoadCommandInfo &L) const {
  4165. return getStruct<MachO::routines_command>(*this, L.Ptr);
  4166. }
  4167. MachO::routines_command_64
  4168. MachOObjectFile::getRoutinesCommand64(const LoadCommandInfo &L) const {
  4169. return getStruct<MachO::routines_command_64>(*this, L.Ptr);
  4170. }
  4171. MachO::thread_command
  4172. MachOObjectFile::getThreadCommand(const LoadCommandInfo &L) const {
  4173. return getStruct<MachO::thread_command>(*this, L.Ptr);
  4174. }
  4175. MachO::any_relocation_info
  4176. MachOObjectFile::getRelocation(DataRefImpl Rel) const {
  4177. uint32_t Offset;
  4178. if (getHeader().filetype == MachO::MH_OBJECT) {
  4179. DataRefImpl Sec;
  4180. Sec.d.a = Rel.d.a;
  4181. if (is64Bit()) {
  4182. MachO::section_64 Sect = getSection64(Sec);
  4183. Offset = Sect.reloff;
  4184. } else {
  4185. MachO::section Sect = getSection(Sec);
  4186. Offset = Sect.reloff;
  4187. }
  4188. } else {
  4189. MachO::dysymtab_command DysymtabLoadCmd = getDysymtabLoadCommand();
  4190. if (Rel.d.a == 0)
  4191. Offset = DysymtabLoadCmd.extreloff; // Offset to the external relocations
  4192. else
  4193. Offset = DysymtabLoadCmd.locreloff; // Offset to the local relocations
  4194. }
  4195. auto P = reinterpret_cast<const MachO::any_relocation_info *>(
  4196. getPtr(*this, Offset)) + Rel.d.b;
  4197. return getStruct<MachO::any_relocation_info>(
  4198. *this, reinterpret_cast<const char *>(P));
  4199. }
  4200. MachO::data_in_code_entry
  4201. MachOObjectFile::getDice(DataRefImpl Rel) const {
  4202. const char *P = reinterpret_cast<const char *>(Rel.p);
  4203. return getStruct<MachO::data_in_code_entry>(*this, P);
  4204. }
  4205. const MachO::mach_header &MachOObjectFile::getHeader() const {
  4206. return Header;
  4207. }
  4208. const MachO::mach_header_64 &MachOObjectFile::getHeader64() const {
  4209. assert(is64Bit());
  4210. return Header64;
  4211. }
  4212. uint32_t MachOObjectFile::getIndirectSymbolTableEntry(
  4213. const MachO::dysymtab_command &DLC,
  4214. unsigned Index) const {
  4215. uint64_t Offset = DLC.indirectsymoff + Index * sizeof(uint32_t);
  4216. return getStruct<uint32_t>(*this, getPtr(*this, Offset));
  4217. }
  4218. MachO::data_in_code_entry
  4219. MachOObjectFile::getDataInCodeTableEntry(uint32_t DataOffset,
  4220. unsigned Index) const {
  4221. uint64_t Offset = DataOffset + Index * sizeof(MachO::data_in_code_entry);
  4222. return getStruct<MachO::data_in_code_entry>(*this, getPtr(*this, Offset));
  4223. }
  4224. MachO::symtab_command MachOObjectFile::getSymtabLoadCommand() const {
  4225. if (SymtabLoadCmd)
  4226. return getStruct<MachO::symtab_command>(*this, SymtabLoadCmd);
  4227. // If there is no SymtabLoadCmd return a load command with zero'ed fields.
  4228. MachO::symtab_command Cmd;
  4229. Cmd.cmd = MachO::LC_SYMTAB;
  4230. Cmd.cmdsize = sizeof(MachO::symtab_command);
  4231. Cmd.symoff = 0;
  4232. Cmd.nsyms = 0;
  4233. Cmd.stroff = 0;
  4234. Cmd.strsize = 0;
  4235. return Cmd;
  4236. }
  4237. MachO::dysymtab_command MachOObjectFile::getDysymtabLoadCommand() const {
  4238. if (DysymtabLoadCmd)
  4239. return getStruct<MachO::dysymtab_command>(*this, DysymtabLoadCmd);
  4240. // If there is no DysymtabLoadCmd return a load command with zero'ed fields.
  4241. MachO::dysymtab_command Cmd;
  4242. Cmd.cmd = MachO::LC_DYSYMTAB;
  4243. Cmd.cmdsize = sizeof(MachO::dysymtab_command);
  4244. Cmd.ilocalsym = 0;
  4245. Cmd.nlocalsym = 0;
  4246. Cmd.iextdefsym = 0;
  4247. Cmd.nextdefsym = 0;
  4248. Cmd.iundefsym = 0;
  4249. Cmd.nundefsym = 0;
  4250. Cmd.tocoff = 0;
  4251. Cmd.ntoc = 0;
  4252. Cmd.modtaboff = 0;
  4253. Cmd.nmodtab = 0;
  4254. Cmd.extrefsymoff = 0;
  4255. Cmd.nextrefsyms = 0;
  4256. Cmd.indirectsymoff = 0;
  4257. Cmd.nindirectsyms = 0;
  4258. Cmd.extreloff = 0;
  4259. Cmd.nextrel = 0;
  4260. Cmd.locreloff = 0;
  4261. Cmd.nlocrel = 0;
  4262. return Cmd;
  4263. }
  4264. MachO::linkedit_data_command
  4265. MachOObjectFile::getDataInCodeLoadCommand() const {
  4266. if (DataInCodeLoadCmd)
  4267. return getStruct<MachO::linkedit_data_command>(*this, DataInCodeLoadCmd);
  4268. // If there is no DataInCodeLoadCmd return a load command with zero'ed fields.
  4269. MachO::linkedit_data_command Cmd;
  4270. Cmd.cmd = MachO::LC_DATA_IN_CODE;
  4271. Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
  4272. Cmd.dataoff = 0;
  4273. Cmd.datasize = 0;
  4274. return Cmd;
  4275. }
  4276. MachO::linkedit_data_command
  4277. MachOObjectFile::getLinkOptHintsLoadCommand() const {
  4278. if (LinkOptHintsLoadCmd)
  4279. return getStruct<MachO::linkedit_data_command>(*this, LinkOptHintsLoadCmd);
  4280. // If there is no LinkOptHintsLoadCmd return a load command with zero'ed
  4281. // fields.
  4282. MachO::linkedit_data_command Cmd;
  4283. Cmd.cmd = MachO::LC_LINKER_OPTIMIZATION_HINT;
  4284. Cmd.cmdsize = sizeof(MachO::linkedit_data_command);
  4285. Cmd.dataoff = 0;
  4286. Cmd.datasize = 0;
  4287. return Cmd;
  4288. }
  4289. ArrayRef<uint8_t> MachOObjectFile::getDyldInfoRebaseOpcodes() const {
  4290. if (!DyldInfoLoadCmd)
  4291. return None;
  4292. auto DyldInfoOrErr =
  4293. getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
  4294. if (!DyldInfoOrErr)
  4295. return None;
  4296. MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
  4297. const uint8_t *Ptr =
  4298. reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.rebase_off));
  4299. return makeArrayRef(Ptr, DyldInfo.rebase_size);
  4300. }
  4301. ArrayRef<uint8_t> MachOObjectFile::getDyldInfoBindOpcodes() const {
  4302. if (!DyldInfoLoadCmd)
  4303. return None;
  4304. auto DyldInfoOrErr =
  4305. getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
  4306. if (!DyldInfoOrErr)
  4307. return None;
  4308. MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
  4309. const uint8_t *Ptr =
  4310. reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.bind_off));
  4311. return makeArrayRef(Ptr, DyldInfo.bind_size);
  4312. }
  4313. ArrayRef<uint8_t> MachOObjectFile::getDyldInfoWeakBindOpcodes() const {
  4314. if (!DyldInfoLoadCmd)
  4315. return None;
  4316. auto DyldInfoOrErr =
  4317. getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
  4318. if (!DyldInfoOrErr)
  4319. return None;
  4320. MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
  4321. const uint8_t *Ptr =
  4322. reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.weak_bind_off));
  4323. return makeArrayRef(Ptr, DyldInfo.weak_bind_size);
  4324. }
  4325. ArrayRef<uint8_t> MachOObjectFile::getDyldInfoLazyBindOpcodes() const {
  4326. if (!DyldInfoLoadCmd)
  4327. return None;
  4328. auto DyldInfoOrErr =
  4329. getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
  4330. if (!DyldInfoOrErr)
  4331. return None;
  4332. MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
  4333. const uint8_t *Ptr =
  4334. reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.lazy_bind_off));
  4335. return makeArrayRef(Ptr, DyldInfo.lazy_bind_size);
  4336. }
  4337. ArrayRef<uint8_t> MachOObjectFile::getDyldInfoExportsTrie() const {
  4338. if (!DyldInfoLoadCmd)
  4339. return None;
  4340. auto DyldInfoOrErr =
  4341. getStructOrErr<MachO::dyld_info_command>(*this, DyldInfoLoadCmd);
  4342. if (!DyldInfoOrErr)
  4343. return None;
  4344. MachO::dyld_info_command DyldInfo = DyldInfoOrErr.get();
  4345. const uint8_t *Ptr =
  4346. reinterpret_cast<const uint8_t *>(getPtr(*this, DyldInfo.export_off));
  4347. return makeArrayRef(Ptr, DyldInfo.export_size);
  4348. }
  4349. ArrayRef<uint8_t> MachOObjectFile::getUuid() const {
  4350. if (!UuidLoadCmd)
  4351. return None;
  4352. // Returning a pointer is fine as uuid doesn't need endian swapping.
  4353. const char *Ptr = UuidLoadCmd + offsetof(MachO::uuid_command, uuid);
  4354. return makeArrayRef(reinterpret_cast<const uint8_t *>(Ptr), 16);
  4355. }
  4356. StringRef MachOObjectFile::getStringTableData() const {
  4357. MachO::symtab_command S = getSymtabLoadCommand();
  4358. return getData().substr(S.stroff, S.strsize);
  4359. }
  4360. bool MachOObjectFile::is64Bit() const {
  4361. return getType() == getMachOType(false, true) ||
  4362. getType() == getMachOType(true, true);
  4363. }
  4364. void MachOObjectFile::ReadULEB128s(uint64_t Index,
  4365. SmallVectorImpl<uint64_t> &Out) const {
  4366. DataExtractor extractor(ObjectFile::getData(), true, 0);
  4367. uint64_t offset = Index;
  4368. uint64_t data = 0;
  4369. while (uint64_t delta = extractor.getULEB128(&offset)) {
  4370. data += delta;
  4371. Out.push_back(data);
  4372. }
  4373. }
  4374. bool MachOObjectFile::isRelocatableObject() const {
  4375. return getHeader().filetype == MachO::MH_OBJECT;
  4376. }
  4377. Expected<std::unique_ptr<MachOObjectFile>>
  4378. ObjectFile::createMachOObjectFile(MemoryBufferRef Buffer,
  4379. uint32_t UniversalCputype,
  4380. uint32_t UniversalIndex) {
  4381. StringRef Magic = Buffer.getBuffer().slice(0, 4);
  4382. if (Magic == "\xFE\xED\xFA\xCE")
  4383. return MachOObjectFile::create(Buffer, false, false,
  4384. UniversalCputype, UniversalIndex);
  4385. if (Magic == "\xCE\xFA\xED\xFE")
  4386. return MachOObjectFile::create(Buffer, true, false,
  4387. UniversalCputype, UniversalIndex);
  4388. if (Magic == "\xFE\xED\xFA\xCF")
  4389. return MachOObjectFile::create(Buffer, false, true,
  4390. UniversalCputype, UniversalIndex);
  4391. if (Magic == "\xCF\xFA\xED\xFE")
  4392. return MachOObjectFile::create(Buffer, true, true,
  4393. UniversalCputype, UniversalIndex);
  4394. return make_error<GenericBinaryError>("Unrecognized MachO magic number",
  4395. object_error::invalid_file_type);
  4396. }
  4397. StringRef MachOObjectFile::mapDebugSectionName(StringRef Name) const {
  4398. return StringSwitch<StringRef>(Name)
  4399. .Case("debug_str_offs", "debug_str_offsets")
  4400. .Default(Name);
  4401. }
  4402. Expected<std::vector<std::string>>
  4403. MachOObjectFile::findDsymObjectMembers(StringRef Path) {
  4404. SmallString<256> BundlePath(Path);
  4405. // Normalize input path. This is necessary to accept `bundle.dSYM/`.
  4406. sys::path::remove_dots(BundlePath);
  4407. if (!sys::fs::is_directory(BundlePath) ||
  4408. sys::path::extension(BundlePath) != ".dSYM")
  4409. return std::vector<std::string>();
  4410. sys::path::append(BundlePath, "Contents", "Resources", "DWARF");
  4411. bool IsDir;
  4412. auto EC = sys::fs::is_directory(BundlePath, IsDir);
  4413. if (EC == errc::no_such_file_or_directory || (!EC && !IsDir))
  4414. return createStringError(
  4415. EC, "%s: expected directory 'Contents/Resources/DWARF' in dSYM bundle",
  4416. Path.str().c_str());
  4417. if (EC)
  4418. return createFileError(BundlePath, errorCodeToError(EC));
  4419. std::vector<std::string> ObjectPaths;
  4420. for (sys::fs::directory_iterator Dir(BundlePath, EC), DirEnd;
  4421. Dir != DirEnd && !EC; Dir.increment(EC)) {
  4422. StringRef ObjectPath = Dir->path();
  4423. sys::fs::file_status Status;
  4424. if (auto EC = sys::fs::status(ObjectPath, Status))
  4425. return createFileError(ObjectPath, errorCodeToError(EC));
  4426. switch (Status.type()) {
  4427. case sys::fs::file_type::regular_file:
  4428. case sys::fs::file_type::symlink_file:
  4429. case sys::fs::file_type::type_unknown:
  4430. ObjectPaths.push_back(ObjectPath.str());
  4431. break;
  4432. default: /*ignore*/;
  4433. }
  4434. }
  4435. if (EC)
  4436. return createFileError(BundlePath, errorCodeToError(EC));
  4437. if (ObjectPaths.empty())
  4438. return createStringError(std::error_code(),
  4439. "%s: no objects found in dSYM bundle",
  4440. Path.str().c_str());
  4441. return ObjectPaths;
  4442. }
  4443. llvm::binaryformat::Swift5ReflectionSectionKind
  4444. MachOObjectFile::mapReflectionSectionNameToEnumValue(
  4445. StringRef SectionName) const {
  4446. #define HANDLE_SWIFT_SECTION(KIND, MACHO, ELF, COFF) \
  4447. .Case(MACHO, llvm::binaryformat::Swift5ReflectionSectionKind::KIND)
  4448. return StringSwitch<llvm::binaryformat::Swift5ReflectionSectionKind>(
  4449. SectionName)
  4450. #include "llvm/BinaryFormat/Swift.def"
  4451. .Default(llvm::binaryformat::Swift5ReflectionSectionKind::unknown);
  4452. #undef HANDLE_SWIFT_SECTION
  4453. }