MachOObjectFile.cpp 177 KB

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